diff --git a/.circleci/config.yml b/.circleci/config.yml index 94fed2af278951..af889bdc060522 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -12,15 +12,32 @@ parameters: default: false type: boolean + # Experimental unified release workflow + run_new_release_workflow: + default: false + type: boolean + + run_nightly_workflow: + default: false + type: boolean + release_latest: default: false type: boolean release_version: - default: "9999" + default: "" type: string - run_nightly_workflow: + release_monorepo_packages_version: + default: "" + type: string + + release_tag: + default: "" + type: string + + release_dry_run: default: false type: boolean diff --git a/.circleci/configurations/executors.yml b/.circleci/configurations/executors.yml index 1c4c6a9bfb806c..1e20c133e36590 100644 --- a/.circleci/configurations/executors.yml +++ b/.circleci/configurations/executors.yml @@ -35,11 +35,11 @@ executors: xcode: *xcode_version resource_class: macos.x86.medium.gen2 environment: - - BUILD_FROM_SOURCE: true + - RCT_BUILD_HERMES_FROM_SOURCE: true reactnativeios-lts: <<: *defaults macos: xcode: '14.3.1' resource_class: macos.x86.medium.gen2 environment: - - BUILD_FROM_SOURCE: true + - RCT_BUILD_HERMES_FROM_SOURCE: true diff --git a/.circleci/configurations/jobs.yml b/.circleci/configurations/jobs.yml index 39eb852857d3dd..d48e4b6c7b6415 100644 --- a/.circleci/configurations/jobs.yml +++ b/.circleci/configurations/jobs.yml @@ -599,7 +599,7 @@ jobs: environment: - HERMES_WS_DIR: *hermes_workspace_root - HERMES_VERSION_FILE: "packages/react-native/sdks/.hermesversion" - - BUILD_FROM_SOURCE: true + - RCT_BUILD_HERMES_FROM_SOURCE: true steps: - run: name: Install dependencies @@ -1107,6 +1107,65 @@ jobs: node ./scripts/releases-ci/prepare-package-for-release.js -v "$VERSION" -l << parameters.latest >> --dry-run << parameters.dryrun >> + # Experimental unified release workflow + # Replaces `prepare_package_for_release` + # + # Writes a new commit and tag(s), which will trigger the `publish_release` + # and `publish_bumped_packages` workflows. + prepare_release_new: + parameters: + version: + type: string + # TODO(T182538198): Required for 0.74.x, where workspace packages are out + # of sync with react-native. This will be removed for 0.75+. + monorepo_packages_version: + type: string + tag: + type: string + dry_run: + type: boolean + default: false + executor: reactnativeios + steps: + - checkout_code_with_cache + - run_yarn + - add_ssh_keys: + fingerprints: + - "1f:c7:61:c4:e2:ff:77:e3:cc:ca:a7:34:c2:79:e3:3c" + - brew_install: + package: cmake + - run: + name: Versioning workspace packages + command: | + node scripts/releases/set-version "<< parameters.monorepo_packages_version >>" --skip-react-native-version + - run: + name: Versioning react-native package + command: | + node scripts/releases/set-rn-version.js -v "<< parameters.version >>" --build-type "release" + - run: + name: Creating release commit + command: | + git commit -a -m "Release << parameters.version >>" -m "#publish-packages-to-npm&<< parameters.tag >>" + git tag -a "v<< parameters.version >>" -m "v<< parameters.version >>" + GIT_PAGER=cat git show HEAD + - when: + condition: + equal: ["latest", << parameters.tag >>] + steps: + - run: + name: Updating "latest" tag + command: | + git tag -d "latest" + git push origin :latest + git tag -a "latest" -m "latest" + - unless: + condition: << parameters.dry_run >> + steps: + run: + name: Pushing release commit + command: | + git push origin $CIRCLE_BRANCH --follow-tags + build_npm_package: parameters: release_type: diff --git a/.circleci/configurations/top_level.yml b/.circleci/configurations/top_level.yml index 5d3281d36400a6..4c76d009a026cb 100644 --- a/.circleci/configurations/top_level.yml +++ b/.circleci/configurations/top_level.yml @@ -92,7 +92,7 @@ references: # Cocoapods - RNTester pods_cache_key: &pods_cache_key v11-pods-{{ .Environment.CIRCLE_JOB }}-{{ checksum "packages/rn-tester/Podfile.lock.bak" }}-{{ checksum "packages/rn-tester/Podfile" }} cocoapods_cache_key: &cocoapods_cache_key v11-cocoapods-{{ .Environment.CIRCLE_JOB }}-{{ checksum "packages/rn-tester/Podfile.lock" }}-{{ checksum "packages/rn-tester/Podfile" }}-{{ checksum "/tmp/hermes/hermesversion" }} - rntester_podfile_lock_cache_key: &rntester_podfile_lock_cache_key v9-podfilelock-{{ .Environment.CIRCLE_JOB }}-{{ checksum "packages/rn-tester/Podfile" }}-{{ checksum "/tmp/week_year" }}-{{ checksum "/tmp/hermes/hermesversion" }} + rntester_podfile_lock_cache_key: &rntester_podfile_lock_cache_key v10-podfilelock-{{ .Environment.CIRCLE_JOB }}-{{ checksum "packages/rn-tester/Podfile" }}-{{ checksum "/tmp/week_year" }}-{{ checksum "/tmp/hermes/hermesversion" }} # Cocoapods - Template template_cocoapods_cache_key: &template_cocoapods_cache_key v6-cocoapods-{{ .Environment.CIRCLE_JOB }}-{{ checksum "/tmp/iOSTemplateProject/ios/Podfile.lock" }}-{{ checksum "/tmp/iOSTemplateProject/ios/Podfile" }}-{{ checksum "/tmp/hermes/hermesversion" }}-{{ checksum "packages/rn-tester/Podfile.lock" }} @@ -129,14 +129,30 @@ parameters: default: false type: boolean + run_new_release_workflow: + default: false + type: boolean + + run_nightly_workflow: + default: false + type: boolean + release_latest: default: false type: boolean release_version: - default: "9999" + default: "" type: string - run_nightly_workflow: + release_monorepo_packages_version: + default: "" + type: string + + release_tag: + default: "" + type: string + + release_dry_run: default: false type: boolean diff --git a/.circleci/configurations/workflows.yml b/.circleci/configurations/workflows.yml index e5c085ee4ce08a..cb74962959d3a1 100644 --- a/.circleci/configurations/workflows.yml +++ b/.circleci/configurations/workflows.yml @@ -6,6 +6,7 @@ # when: # and: # - equal: [ false, << pipeline.parameters.run_release_workflow >> ] +# - equal: [ false, << pipeline.parameters.run_new_release_workflow >> ] # - equal: [ false, << pipeline.parameters.run_nightly_workflow >> ] # # It's setup this way so we can trigger a release via a POST @@ -25,6 +26,17 @@ workflows: version: << pipeline.parameters.release_version >> latest : << pipeline.parameters.release_latest >> + # Experimental unified release workflow + create_release_new: + when: << pipeline.parameters.run_new_release_workflow >> + jobs: + - prepare_release_new: + name: prepare_release_new + version: << pipeline.parameters.release_version >> + monorepo_packages_version: << pipeline.parameters.release_monorepo_packages_version >> + tag: << pipeline.parameters.release_tag >> + dry_run: << pipeline.parameters.release_dry_run >> + # This job will run only when a tag is published due to all the jobs being filtered. publish_release: jobs: @@ -79,6 +91,7 @@ workflows: when: and: - equal: [ false, << pipeline.parameters.run_release_workflow >> ] + - equal: [ false, << pipeline.parameters.run_new_release_workflow >> ] - equal: [ false, << pipeline.parameters.run_nightly_workflow >> ] jobs: # Run lints on every commit @@ -116,6 +129,7 @@ workflows: parameters: flavor: ["Debug", "Release"] - build_npm_package: + name: build_nightly_npm_package release_type: "nightly" requires: - build_android @@ -127,6 +141,7 @@ workflows: when: and: - equal: [ false, << pipeline.parameters.run_release_workflow >> ] + - equal: [ false, << pipeline.parameters.run_new_release_workflow >> ] - equal: [ false, << pipeline.parameters.run_nightly_workflow >> ] jobs: - find_and_publish_bumped_packages: diff --git a/.eslintrc.js b/.eslintrc.js index b0410b566e3456..c1e8f5e0e9bad3 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -113,6 +113,7 @@ module.exports = { files: ['**/*.d.ts'], plugins: ['redundant-undefined'], rules: { + 'no-dupe-class-members': 'off', 'redundant-undefined/redundant-undefined': [ 'error', {followExactOptionalPropertyTypes: true}, diff --git a/.flowconfig b/.flowconfig index f240531f3d78bb..2c5ea1ed4bd627 100644 --- a/.flowconfig +++ b/.flowconfig @@ -85,4 +85,4 @@ untyped-import untyped-type-import [version] -^0.228.0 +^0.231.0 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 3dc8f24718545e..4bc1496d421726 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,9 @@ blank_issues_enabled: false contact_links: + - name: ⬆️ Upgrade - Build Regression + url: https://github.com/reactwg/react-native-releases/issues/new/choose + about: | + If you are upgrading to a new React Native version (stable or pre-release) and encounter a build regression. - name: 🚀 Expo Issue url: https://github.com/expo/expo/issues/new about: | diff --git a/.github/ISSUE_TEMPLATE/upgrade_regression_form.yml b/.github/ISSUE_TEMPLATE/upgrade_regression_form.yml deleted file mode 100644 index ed559395ecb0f8..00000000000000 --- a/.github/ISSUE_TEMPLATE/upgrade_regression_form.yml +++ /dev/null @@ -1,133 +0,0 @@ -name: ⬆️ Upgrade - Build Regression -description: If you are upgrading to a new React Native version (stable or pre-release) and encounter a build regression. -labels: ["Needs: Triage :mag:", "Type: Upgrade Issue"] - -body: - - type: markdown - attributes: - value: "## Upgrade Issues" - - type: markdown - attributes: - value: | - Please use this form to file an issue if you have upgraded or are upgrading to [latest stable release](https://github.com/facebook/react-native/releases/latest) and have experienced a regression (something that used to work in previous version). - - If you're **NOT** upgrading the React Native version, please use this [other bug type](https://github.com/facebook/react-native/issues/new?template=bug_report.yml). - - Before you continue: - * If you're using **Expo** and having problems updating it, [report it here](https://github.com/expo/expo/issues). - * If you're found a problem with our **documentation**, [report it here](https://github.com/facebook/react-native-website/issues/). - * If you're having an issue with **Metro** (the bundler), [report it here](https://github.com/facebook/metro/issues/). - * If you're using an external library, report the issue to the **library first**. - * Please [search for similar issues](https://github.com/facebook/react-native/issues) in our issue tracker. - - Make sure that your issue: - * Have a **valid reproducer** with an [empty project from template](https://github.com/react-native-community/reproducer-react-native). - * Is upgrading to the [**latest stable**](https://github.com/facebook/react-native/releases/) of React Native. - - Due to the extreme number of bugs we receive, we will be looking **ONLY** into issues with a reproducer, and on [supported versions](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported) of React Native. - - type: input - id: old-version - attributes: - label: Old Version - description: The version of react-native that you're upgrading from. - placeholder: "0.72.0" - validations: - required: true - - type: input - id: new-version - attributes: - label: New Version - description: The version of react-native that you're upgrading to. Bear in mind that only issues that are upgrading to the [latest stable](https://github.com/facebook/react-native/releases/) will be looked into. - placeholder: "0.73.0" - validations: - required: true - - type: textarea - id: description - attributes: - label: Description - description: A clear and concise description of what the bug is. - validations: - required: true - - type: textarea - id: reproduction - attributes: - label: Steps to reproduce - description: The list of steps and commands to reproduce the issue. - placeholder: | - 1. Install the application with `yarn android` - 2. Click on the button on the Home - 3. Notice the crash - validations: - required: true - - type: dropdown - id: platforms - attributes: - label: Affected Platforms - description: Please select which platform you're developing to, and which OS you're using for building. - multiple: true - options: - - Runtime - Android - - Runtime - iOS - - Runtime - Web - - Runtime - Desktop - - Build - MacOS - - Build - Windows - - Build - Linux - - Other (please specify) - validations: - required: true - - type: textarea - id: react-native-info - attributes: - label: Output of `npx react-native info` - description: Run `npx react-native info` in your terminal, copy and paste the results here. - placeholder: | - Paste the output of `npx react-native info` here. The output looks like: - ... - System: - OS: macOS 14.1.1 - CPU: (10) arm64 Apple M1 Max - Memory: 417.81 MB / 64.00 GB - Shell: - version: "5.9" - path: /bin/zsh - Binaries: - Node: ... - version: 18.14.0 - ... - render: text - validations: - required: true - - type: textarea - id: stacktrace - attributes: - label: Stacktrace or Logs - description: Please provide a stacktrace or a log of your crash or failure - render: text - placeholder: | - Paste your stacktraces and logs here. They might look like: - - java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libfabricjni.so caused by: com.facebook.react.fabric.StateWrapperImpl result: 0 - at com.facebook.soloader.SoLoader.g(Unknown Source:341) - at com.facebook.soloader.SoLoader.t(Unknown Source:124) - at com.facebook.soloader.SoLoader.s(Unknown Source:2) - at com.facebook.soloader.SoLoader.q(Unknown Source:42) - at com.facebook.soloader.SoLoader.p(Unknown Source:1) - ... - validations: - required: true - - type: input - id: reproducer - attributes: - label: Reproducer - description: A link to a Expo Snack or a public repository that reproduces this bug, using [this template](https://github.com/react-native-community/reproducer-react-native). Reproducers are **mandatory**. - placeholder: "https://github.com//" - validations: - required: true - - type: textarea - id: extra - attributes: - label: Screenshots and Videos - description: | - Please provide screenshot or a video of your bug if relevant. - Issues with videos and screenshots are more likely to **get prioritized**. diff --git a/.github/workflows/ios-tests.yml b/.github/workflows/ios-tests.yml index 7677425ab0b235..a8ccb3cbf49282 100644 --- a/.github/workflows/ios-tests.yml +++ b/.github/workflows/ios-tests.yml @@ -36,7 +36,7 @@ jobs: uses: actions/cache@v3 with: path: packages/rn-tester/Pods - key: v1-${{ runner.os }}-RNTesterPods-${{ hashFiles('packages/rn-tester/Podfile.lock') }}-${{ hashFiles('packages/rn-tester/Podfile') }}-${{ hashFiles('tmp/hermes/hermesversion') }} + key: v3-${{ runner.os }}-RNTesterPods-${{ hashFiles('packages/rn-tester/Podfile.lock') }}-${{ hashFiles('packages/rn-tester/Podfile') }}-${{ hashFiles('tmp/hermes/hermesversion') }} - name: Pod Install run: | cd packages/rn-tester diff --git a/.github/workflows/needs-attention.yml b/.github/workflows/needs-attention.yml index a92cf54504a4d7..b8da8fb37749b3 100644 --- a/.github/workflows/needs-attention.yml +++ b/.github/workflows/needs-attention.yml @@ -10,15 +10,15 @@ permissions: jobs: applyNeedsAttentionLabel: permissions: - contents: read # for actions/checkout to fetch code - issues: write # for hramos/needs-attention to label issues + contents: read # for actions/checkout to fetch code + issues: write # for react-native-community/needs-attention to label issues name: Apply Needs Attention Label runs-on: ubuntu-latest if: github.repository == 'facebook/react-native' steps: - uses: actions/checkout@v4 - name: Apply Needs Attention Label - uses: hramos/needs-attention@v1 + uses: react-native-community/needs-attention@v2.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} response-required-label: "Needs: Author Feedback" diff --git a/.github/workflows/stale-bot.yml b/.github/workflows/stale-bot.yml index 168ee6fa314cae..97b6c783cde94e 100644 --- a/.github/workflows/stale-bot.yml +++ b/.github/workflows/stale-bot.yml @@ -10,7 +10,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v5 + - uses: actions/stale@v9 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: 180 @@ -27,7 +27,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v5 + - uses: actions/stale@v9 with: ascending: true repo-token: ${{ secrets.GITHUB_TOKEN }} @@ -45,7 +45,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v5 + - uses: actions/stale@v9 with: repo-token: ${{ secrets.GITHUB_TOKEN }} any-of-labels: 'Needs: Author Feedback' @@ -63,7 +63,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v5 + - uses: actions/stale@v9 with: ascending: true repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 7e334430180887..626d954cfa3f18 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ project.xcworkspace /packages/react-native/ReactAndroid/hermes-engine/.cxx/ /packages/react-native/template/android/app/build/ /packages/react-native/template/android/build/ +/packages/react-native-popup-menu-android/android/build/ # Buck .buckd diff --git a/CHANGELOG.md b/CHANGELOG.md index affabe4ae515ac..f56b93c3d918d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,600 @@ # Changelog +## v0.74.0-rc.3 + +### Added + +- Add inspector proxy `nativeNetworkInspection` target capability flag ([f3ce7cd76e](https://github.com/facebook/react-native/commit/f3ce7cd76ee4f1772e2623c87b21bbbcb1edbc27) by [@byCedric](https://github.com/byCedric)) + +#### iOS specific + +- Implement cursor style prop ([73664f576a](https://github.com/facebook/react-native/commit/73664f576aaa472d5c8fb2a02e0ddd017bbb2ea4) by [@Saadnajmi](https://github.com/Saadnajmi)) + +### Changed + +#### Android specific + +- Expose `react_render_textlayoutmanager` via prefab. ([642b4e5c2c](https://github.com/facebook/react-native/commit/642b4e5c2c80b6f46429b41f36489eb81ac8a06e) by [@tomekzaw](https://github.com/tomekzaw)) +- Expose `rrc_text` via prefab. ([1c69100a2b](https://github.com/facebook/react-native/commit/1c69100a2b822309c210733a33a57ebb560a1c71) by [@tomekzaw](https://github.com/tomekzaw)) +- Expose `rrc_textinput` via prefab. ([adc9e5b0fa](https://github.com/facebook/react-native/commit/adc9e5b0faaf8c997fe0d09aecd56747026f8b01) by [@tomekzaw](https://github.com/tomekzaw)) + +### Fixed + +- Support .tsx, .ts, and .jsx in component stacks ([adaf5eba3e](https://github.com/facebook/react-native/commit/adaf5eba3e8381d0b499257ab04d30d6f3fb4c93) by [@rickhanlonii](https://github.com/rickhanlonii)) + +#### Android specific + +- Fix registration of ViewManagers in new renderer when not using lazyViewManagers. ([fb9872d4fe](https://github.com/facebook/react-native/commit/fb9872d4fe07ac7028ce536200632b3543d5e8a9) by [@javache](https://github.com/javache)) +- NullPointerException is no longer ignored in MessageQueueThreadHandler ([5f45700bd0](https://github.com/facebook/react-native/commit/5f45700bd06fb253650c8653b511b084b99eeb7f) by [@javache](https://github.com/javache)) + +#### iOS specific + +- RCTRedBox not appearing in Bridgeless when metro is not running ([4adef35e97](https://github.com/facebook/react-native/commit/4adef35e97f31db466e536aa21d5eeec6ee34fc6) by [@okwasniewski](https://github.com/okwasniewski)) + +## v0.74.0-rc.2 + +### Changed + +#### Android specific + +- Rename `PopupMenuAndroidNativeComponent.js` to `PopupMenuAndroidNativeComponent.android.js` ([fcabb2ad21](https://github.com/facebook/react-native/commit/fcabb2ad21b2c17f4e0d40b0637c22ba84568038) by [@cipolleschi](https://github.com/cipolleschi)) + +#### iOS specific + +- Rename BUILD_FROM_SOURCE to RCT_BUILD_HERMES_FROM_SOURCE ([f7644be6d4](https://github.com/facebook/react-native/commit/f7644be6d4d79b72c26f740cf5ac021dfd5fedc0) by [@cipolleschi](https://github.com/cipolleschi)) + +### Deprecated + +#### iOS specific + +- Deprecate `getSurfacePresenter` and `getModuleRegistry` for `surfacePresenter` and moduleRegistry` props. ([c3b0a8f162](https://github.com/facebook/react-native/commit/c3b0a8f1626939cf5c7b3864a5acf9d3dad26fb3) by [@cipolleschi](https://github.com/cipolleschi)) + +### Removed + +#### Android specific + +- Move PopupMenu out of React Native core ([8bced4b29d](https://github.com/facebook/react-native/commit/8bced4b29db9b41a68ef726df81449a399eff604) by [@RSNara](https://github.com/RSNara)) + +### Fixed + +- Re-enable listing Hermes debugger targets in chrome://inspect, broken in 0.74 RC ([4cfac8eea6](https://github.com/facebook/react-native/commit/4cfac8eea63129059559f0a65c038dfe95e12d7c) by [@motiz88](https://github.com/motiz88)) + +#### iOS specific + +- Properly warn about `createRootViewWithBridge` being deprecated ([a1197695fc](https://github.com/facebook/react-native/commit/a1197695fc7dd7750001dc60853fd19f162dc69e) by [@okwasniewski](https://github.com/okwasniewski)) +- Codegen correctly handles react-native.config.js. ([f5d5d9d284](https://github.com/facebook/react-native/commit/f5d5d9d284fae2bce42c9202bbfcf948e6a9ed37) by [@dmytrorykun](https://github.com/dmytrorykun)) + +## v0.74.0-rc.1 + +### Added + +- Warn with future command when using `npx react-native init` ([a6397afb7f](https://github.com/facebook/react-native/commit/a6397afb7f4279e70afa025fe6f9fa0b8e3de3fd) by [@byCedric](https://github.com/byCedric)) + +### Fixed + +- Fix undefined props crash in FlatList ([e33767a36d](https://github.com/facebook/react-native/commit/e33767a36daf7901cb46854b6612dd52b0dbdeec) by [@dieguezz](https://github.com/dieguezz)) + +#### Android specific + +- Do not crash on onJSBundleLoadedFromServer when fast-refreshing on bridgeless mode ([44e5bc9e2c](https://github.com/facebook/react-native/commit/44e5bc9e2c73235ba5d8bf0f5323181948e74197) by [@cortinico](https://github.com/cortinico)) + +## 0.74.0-rc0 + +### Breaking + +- OnLayout event batching changes ([57e49b584d](https://github.com/facebook/react-native/commit/57e49b584d60a7238b113b255898250a7d03a70d) by [@sammy-SC](https://github.com/sammy-SC)) +- Delete traitCast and identifier traits ([1170a68755](https://github.com/facebook/react-native/commit/1170a68755f953c16c85ce784aef476e6970fa7c) by [@NickGerleman](https://github.com/NickGerleman)) +- Remove static-behaves-like-relative errata ([56b9b990de](https://github.com/facebook/react-native/commit/56b9b990de1fbe6ee78a5116e404259e849a07a7) by [@joevilches](https://github.com/joevilches)) +- Make `start/end` in styles always refer to writing direction ([e859f6c773](https://github.com/facebook/react-native/commit/e859f6c773b85be8945f33e0a64ce042e3b2ab7a) by [@NickGerleman](https://github.com/NickGerleman)) +- Remove APIs for reporting bundle download status to inspector-proxy, which does not use this information. ([cfa02eec50](https://github.com/facebook/react-native/commit/cfa02eec50469059542ccbacbc51643b525ad461) by [@motiz88](https://github.com/motiz88)) +- Delete `configFilename` and `configKey` arguments from iOS codegen CLI. Now we always expect them to be `package.json` and `codegenConfig` respectively. ([33a44e68fc](https://github.com/facebook/react-native/commit/33a44e68fc4c53d48a4cf6c62337ffd13a0197ab) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Add errata for fix to marginStart/End for row-reverse flex direction ([2dad663c28](https://github.com/facebook/react-native/commit/2dad663c2870e0c098649854c8c9333e07be1793) by [@joevilches](https://github.com/joevilches)) +- Remove web performance logging from GlobalPerformanceLogger ([53a2742e13](https://github.com/facebook/react-native/commit/53a2742e13f55c3e412bde2ac7b56f6950e44b17) by [@rshest](https://github.com/rshest)) +- Rename AbsolutePositioning errata ([08eb985c33](https://github.com/facebook/react-native/commit/08eb985c333bca4fc47c854b51ad84f1353d344c) by [@joevilches](https://github.com/joevilches)) +- Get rid of old APIs in FabricUIManagerProvider ([c2c346ccaf](https://github.com/facebook/react-native/commit/c2c346ccaf9912f129b945944575c818eac99a6d)) + +#### Android specific + +- Make bridgeless the default when the New Arch is enabled ([fe337f25be](https://github.com/facebook/react-native/commit/fe337f25be65b67dc3d8d99d26a61ffd26985dd8) by [@cipolleschi](https://github.com/cipolleschi)) +- Codegen: mapping for numeric types is changed for Android native modules. `Float` -> `float`; `Int32` -> `int`. ([ccd3b04770](https://github.com/facebook/react-native/commit/ccd3b047709fda00123e8aec4294dce024b80244) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Delete ReactInstancePackage ([7141c475bf](https://github.com/facebook/react-native/commit/7141c475bf29652d02d915ff70ebe9af439826f4) by [@mdvacca](https://github.com/mdvacca)) +- Delete deprecated method LazyReactPackage.getReactModuleInfoProviderViaReflection ([118e651bc2](https://github.com/facebook/react-native/commit/118e651bc28d089f72e2ea3696ca711f21d7ada6) by [@mdvacca](https://github.com/mdvacca)) +- Reduce visibility of CoreModulesPackage class ([30b9b01e68](https://github.com/facebook/react-native/commit/30b9b01e68929b4d0d839c98e91fefe99319ec50) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of DebugCorePackage ([5ad4bdbad8](https://github.com/facebook/react-native/commit/5ad4bdbad8e3cfc33fbec14535c15985d579b7e2) by [@mdvacca](https://github.com/mdvacca)) +- Mark NativeModule.onCatalystInstanceDestroy() method as deprecated in new architecture ([b13ea1786f](https://github.com/facebook/react-native/commit/b13ea1786f9e0076654a04daaf9a626559f59194) by [@mdvacca](https://github.com/mdvacca)) +- Deprecate CompositeReactPackage from RN Android ([294c0fa208](https://github.com/facebook/react-native/commit/294c0fa208a5eac201c9b9b79dee73a852b62aa8) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactViewManager ([cb46f4cff8](https://github.com/facebook/react-native/commit/cb46f4cff8964a440aedb9ffe9c4ba7fc4a1d930) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactDrawableHelper ([120aab2e99](https://github.com/facebook/react-native/commit/120aab2e995d341e5f620475c7f2beaf61e47f5e) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactTextInputShadowNode ([dc3fc16ce5](https://github.com/facebook/react-native/commit/dc3fc16ce597dd6c24dc5dd26cf1ae9556c76848) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactTextInputLocalData ([b968cb6f97](https://github.com/facebook/react-native/commit/b968cb6f97f6779c9acd037738240b95013fe7ce) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in TextLayoutManagerMapBuffer ([c35dcb3c04](https://github.com/facebook/react-native/commit/c35dcb3c0412eb90121a9f294a049574e80c67c5) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in TextLayoutManager ([4a563f30d2](https://github.com/facebook/react-native/commit/4a563f30d2de89eee1459d8ee79c9ac042a86a96) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in TextAttributeProps ([9454587316](https://github.com/facebook/react-native/commit/94545873169314f04c00fe6e09ad0c1d504635d2) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactTextView ([31e16ee90c](https://github.com/facebook/react-native/commit/31e16ee90c42006b755aa53f0fdf8949f6b16896) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactTextShadowNode ([07e885232b](https://github.com/facebook/react-native/commit/07e885232b409d4a6e2ec48251e4cfba16d2b689) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactTextAnchorViewManager ([b138a4f72d](https://github.com/facebook/react-native/commit/b138a4f72d8d2d58b00437c93fcc8cdd325228b2) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactBaseTextShadowNode ([0505f5c28c](https://github.com/facebook/react-native/commit/0505f5c28c39d746ee19d7ce84bcee49c906f74b) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in StatusBarModule ([6eb4f1e997](https://github.com/facebook/react-native/commit/6eb4f1e997f8412b3dc9238b0068e0db874a6fd2) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in PermissionsModule ([0384e3cf1f](https://github.com/facebook/react-native/commit/0384e3cf1faec1e1cd3782a32cbb3728ac92e06e) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in RequestBodyUtil ([52ec1d87e9](https://github.com/facebook/react-native/commit/52ec1d87e927efb933fade3de2411d3884d00c1b) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in WindowOverlayCompat ([c359a44676](https://github.com/facebook/react-native/commit/c359a44676db917d7fe62b8205ee76653fe529b0) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in DebugOverlayController ([2286c123b7](https://github.com/facebook/react-native/commit/2286c123b7c405a280648ea119c881fd2f97377e) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ReactFragment ([414b25b125](https://github.com/facebook/react-native/commit/414b25b1257804ae7f1d1ae02679bb50d3213140) by [@mdvacca](https://github.com/mdvacca)) +- Remove support for Android API < 23 in ([3664b8aa22](https://github.com/facebook/react-native/commit/3664b8aa221bfc232b0f737ea97b2672a5509e35) by [@mdvacca](https://github.com/mdvacca)) +- Increase min sdk version of RN Android to 23 ([70fcb1ebf6](https://github.com/facebook/react-native/commit/70fcb1ebf664203ca9934fa12376cfa8a32d373b) by [@mdvacca](https://github.com/mdvacca)) +- Rename onCatalystInstanceDestroy -> invalidate ([5f215cdde2](https://github.com/facebook/react-native/commit/5f215cdde2485110b08940f685a8ea31a6327528) by [@mdvacca](https://github.com/mdvacca)) + +#### iOS specific + +- Removing unused `handler` param on PushNotificationIOS.removeEventListener ([fdf4ec3297](https://github.com/facebook/react-native/commit/fdf4ec32975eeec41e0b4b8145c4e45798c82607)) +- Make bridgeless the default when the New Arch is enabled ([c91af773fa](https://github.com/facebook/react-native/commit/c91af773fa2fafdc0fb8e19ccf503ee203efe0c5) by [@cipolleschi](https://github.com/cipolleschi)) +- CocoaPods: remove the `ios_folder` argument from the `use_react_native` function. ([be0c353e18](https://github.com/facebook/react-native/commit/be0c353e18da3a0996f6e2fd3fecbe3852d3d240) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Codegen: mapping for numeric types is changed for Objective-C native modules. `Float` -> `float`; `Int32` -> `NSInteger`. ([5aa425c086](https://github.com/facebook/react-native/commit/5aa425c0867e1e737cce9b7de9752cd9518b95ac) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Defining external codegen targets in `react-native.config.js` is not supported anymore. Define them as normal dependencies in `package.json`. ([ca39a11b27](https://github.com/facebook/react-native/commit/ca39a11b27bf9f90c3a792974910bb9060b2990f) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Delete configFileDir CLI argument. ([8a62d6135f](https://github.com/facebook/react-native/commit/8a62d6135f5ac8c01aa8103ddd91f94973dd6cd3) by [@dmytrorykun](https://github.com/dmytrorykun)) +- ([072a2006e0](https://github.com/facebook/react-native/commit/072a2006e0bd8bd8cc9a75385cc03759bcf63c61) by [@philIip](https://github.com/philIip)) +- Remove some usages of RCT_NEW_ARCH_ENABLED. The change should be transparent BUT some **Swift** libraries might get broken by this change. ([951efc8ce2](https://github.com/facebook/react-native/commit/951efc8ce2a6d34aa6df6d1ad205db2661143855) by [@cipolleschi](https://github.com/cipolleschi)) +- You cannot call methodQueue on RCTHTTPRequestHandler ([7503dbd784](https://github.com/facebook/react-native/commit/7503dbd7849dddbc235b42eb75be0f446bd9cf62) by [@philIip](https://github.com/philIip)) +- RepeatInterval is deprecated in PushNotificationIOS. Use fireDate and the new fireIntervalSeconds. ([a1299938a9](https://github.com/facebook/react-native/commit/a1299938a9fae9cc5b7a2dd49ab6dcb82001d5ef)) +- AlertAction is deprecated in PushNotificationIOS. getScheduledLocalNotifications now uses new iOS APIs which do not expose this property. ([9f4d66d283](https://github.com/facebook/react-native/commit/9f4d66d283905fe04900b012c58e43f5f0f2955d)) +- Make TextInput.onContentSizeChange a direct event ([744fb4a0d2](https://github.com/facebook/react-native/commit/744fb4a0d23d15a40cd591e31f6c0f6cb3a7f06b) by [@sammy-SC](https://github.com/sammy-SC)) +- Remove the Flipper integration ([899e7cdb55](https://github.com/facebook/react-native/commit/899e7cdb55197fc17a96a93af4f8bcc7519553c2) by [@cipolleschi](https://github.com/cipolleschi)) +- Deleted the no-op didRegisterUserNotificationSettings: callback in RCTPushNotificationManager ([3bea8e1bd4](https://github.com/facebook/react-native/commit/3bea8e1bd41cf019bcd01acaef8256e2b3dbd742)) + +### Added + +- Experimental macro to autolink C++ turbomodules ([01d704dd45](https://github.com/facebook/react-native/commit/01d704dd459a05208153d41e512f8be6af924ca3) by [@philIip](https://github.com/philIip)) +- Added a folder inside the `exclude` array inside `tsconfig` ([40bb425f48](https://github.com/facebook/react-native/commit/40bb425f48a65641b4882c08cf84be123b333bd6) by [@bartlomein](https://github.com/bartlomein)) +- Gradle plugin for resolving node_modules packages. ([8456ccad78](https://github.com/facebook/react-native/commit/8456ccad78dab2b0982439f8f45ea1242eb90908) by [@robhogan](https://github.com/robhogan)) +- Added missing typings for fontVariant style prop. ([8fca1c5854](https://github.com/facebook/react-native/commit/8fca1c58542a560d99adaf1408733ef95cc17797) by [@ankit-tailor](https://github.com/ankit-tailor)) +- Added missing typings for fontWeight style prop. ([fb5f79ceb5](https://github.com/facebook/react-native/commit/fb5f79ceb5ececc0ae7f22fa933eca0ac64f3e70) by [@ankit-tailor](https://github.com/ankit-tailor)) +- Enable setNativeProps in animations in the New Architecture ([a5aed1294f](https://github.com/facebook/react-native/commit/a5aed1294f91cfc58e20439ce8eee5a183f899d6) by [@sammy-SC](https://github.com/sammy-SC)) +- Fix flooring of border ([e27452a670](https://github.com/facebook/react-native/commit/e27452a670c45f4c919c9d46e08145723a2235a0) by [@NickGerleman](https://github.com/NickGerleman)) +- Add Yarn files to `.gitignore` in template ([965f2eb1fb](https://github.com/facebook/react-native/commit/965f2eb1fb4d8e9a6bf730925658f3a6baf50654) by [@szymonrybczak](https://github.com/szymonrybczak)) +- Fix missing assignment in Node move constructor ([90df90efca](https://github.com/facebook/react-native/commit/90df90efca35612be27049f7dba9650a289c12e3) by [@NickGerleman](https://github.com/NickGerleman)) +- Introduce "npx react-native codegen" command. ([a612053510](https://github.com/facebook/react-native/commit/a612053510847b7c41135a88db2dcd11d44fa77f) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Introduce the "platform" option to generate-codegen-artifacts.js ([7b10609276](https://github.com/facebook/react-native/commit/7b1060927690d48302dfdcb99bf8c651fd137871) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Introduce "headerPrefix" codegen option. ([dae4a11e90](https://github.com/facebook/react-native/commit/dae4a11e901696f7c205e19df6f0b306319be43a) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Introduce "codegenConfig.includesGeneratedCode" property. ([21784e2ce5](https://github.com/facebook/react-native/commit/21784e2ce5dbf361511a77e9546c8839321e5b74) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Introduce "outputDir" property of "codegenConfig" ([d45a01d6d1](https://github.com/facebook/react-native/commit/d45a01d6d15530e356065704adb869b1cbbb2576) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Fix issues with aligning absolute nodes ([31005b7fd9](https://github.com/facebook/react-native/commit/31005b7fd9a9579920b55f921c477a90fb3f6d10) by [@joevilches](https://github.com/joevilches)) +- Fix bug with align start not taking into account parent padding ([ea3dd6b4f2](https://github.com/facebook/react-native/commit/ea3dd6b4f2ecaac79476796ed2a11fe198299506) by [@joevilches](https://github.com/joevilches)) +- Fix issue where percentages were off of the border box, not padding box ([e826d1c336](https://github.com/facebook/react-native/commit/e826d1c33695c9901e1070d7dd7231de4e79a8d4) by [@joevilches](https://github.com/joevilches)) +- New file for layout methods related to absolute children ([0cc09f207f](https://github.com/facebook/react-native/commit/0cc09f207fc93b18e25cce3fed568647e8ad896f) by [@joevilches](https://github.com/joevilches)) +- Fix issue where start/end would not be respected in flex edge getters ([aa31c6cd75](https://github.com/facebook/react-native/commit/aa31c6cd754ca798c879bd04f955d72051906f95) by [@joevilches](https://github.com/joevilches)) +- Added JSI method for reporting native memory to the GC. ([cfe129c832](https://github.com/facebook/react-native/commit/cfe129c8329ef62c7fcd3ed25c17656b0e218d95) by [@neildhar](https://github.com/neildhar)) +- Allowing `cursorColor` and `selectionHandleColor` to override `selectionColor` on Android ([1e68e48534](https://github.com/facebook/react-native/commit/1e68e48534aedf1533327bf65f26e5cf5b80127b) by [@jakex7](https://github.com/jakex7)) +- Introduce APIs for FabricUIManager ([16fb64a9ef](https://github.com/facebook/react-native/commit/16fb64a9ef97e7ff0b8fe718d310705fa5fe6066)) +- Missing typings for the props `tabIndex` for **View** and `userSelect` in the **Text** props were added. ([b36505bf06](https://github.com/facebook/react-native/commit/b36505bf06d023472f5bee5b3b0a6db4e1ca428f) by [@wootsbot](https://github.com/wootsbot)) +- Turbo Modules Promise-returning functions reject with JS and platform stack traces information ([7612e6601a](https://github.com/facebook/react-native/commit/7612e6601a1c402c548dfe2fe548b1c481659993) by [@krystofwoldrich](https://github.com/krystofwoldrich)) +- Bindings for `alignContent: "space-evenly"` ([c9d0a006fd](https://github.com/facebook/react-native/commit/c9d0a006fd14b428b844a68e73a57986a4abb3b1) by [@NickGerleman](https://github.com/NickGerleman)) +- Support "align-content: space-evenly" ([d66ab59570](https://github.com/facebook/react-native/commit/d66ab59570a4d7542aea595e2dad4a0b5d0654d3) by [@nicoburns](https://github.com/nicoburns)) +- Rename ambiguous leading/trailingEdge functions ([594b586c7d](https://github.com/facebook/react-native/commit/594b586c7d6e90658cc72423d4cf77c4c9d68b9a) by [@joevilches](https://github.com/joevilches)) +- JSC support for the NativeState API in JSI ([7b7f128968](https://github.com/facebook/react-native/commit/7b7f128968310c466ce0a929e9964b08fe098503) by [@javache](https://github.com/javache)) +- Fixed issue with first line element gap handling. ([c7c7831ec6](https://github.com/facebook/react-native/commit/c7c7831ec64da0a5e31d90c3fa1730e4bee87265) by [@jlmip](https://github.com/jlmip)) +- Add onPress prop to TextInput ([8e36cc0293](https://github.com/facebook/react-native/commit/8e36cc02931d121832ed89efb02092125a728315)) +- Cxx TurboModules > Add example to return a JS function from Cxx to JS ([9320174df4](https://github.com/facebook/react-native/commit/9320174df4239058125b8876a0623230f6e03b02) by [@christophpurrer](https://github.com/christophpurrer)) +- Adding getFabricUIManager() APIs to ReactContext ([f941f939bf](https://github.com/facebook/react-native/commit/f941f939bfea5a5619ecabe6a0d401037e8df6f1)) + +#### Android specific + +- ([315be8290d](https://github.com/facebook/react-native/commit/315be8290d6c6524289abc9cf201f32a56e72c13) by [@philIip](https://github.com/philIip)) +- Introduce native api to access RuntimeExecutor ([d7dce975f9](https://github.com/facebook/react-native/commit/d7dce975f91255c6383f9cc6d3b8f818f6e0420b) by [@philIip](https://github.com/philIip)) +- Added `onUserLeaveHint` support into `ReactActivityDelegate` ([3b6c522942](https://github.com/facebook/react-native/commit/3b6c522942ca1b3d3f5e2115e0a4e781063747d0) by [@behenate](https://github.com/behenate)) +- Introduce PopupMenuAndroid to replace UIManager.showPopupMenu() ([35308a73a5](https://github.com/facebook/react-native/commit/35308a73a5e0f69bf32d687be52a8f739fbf2e50) by [@RSNara](https://github.com/RSNara)) +- Added `removeAllViews` to IViewGroupManager. ([3cd85dc933](https://github.com/facebook/react-native/commit/3cd85dc9331fee18ecbe1d0eb4f0f217fc803070) by [@javache](https://github.com/javache)) +- The public API of Modal has changed. We don't have anymore a NativeModalManger turbomodule; RCTModalHostViewNtiveComponent's Prop does not require to pass an identifier anymore. ([314cfa8c91](https://github.com/facebook/react-native/commit/314cfa8c9108581e027b71139c005ab3385acf1e) by [@bernhardoj](https://github.com/bernhardoj)) +- Fix static view config not to filter out "onClick" events on Android ([342041e9ee](https://github.com/facebook/react-native/commit/342041e9ee0f4c72b70a19f290a79040c200f859) by [@rshest](https://github.com/rshest)) +- ReactChoreographer can now use an implementation substitution instead of relying on android.view.Choreographer directly. ([37e509f2b6](https://github.com/facebook/react-native/commit/37e509f2b695818d19358fcd3eaf8fa0452adce3) by [@nlutsenko](https://github.com/nlutsenko)) +- ReactChoreographer can now use an implementation substitution instead of relying on android.view.Choreographer directly. ([751f7e97ba](https://github.com/facebook/react-native/commit/751f7e97ba299eb8f06231126df0a7ecbc41d607) by [@nlutsenko](https://github.com/nlutsenko)) + +#### iOS specific + +- Add error message if codegen has not run properly ([10edb9f545](https://github.com/facebook/react-native/commit/10edb9f545e3b043ed0316933f8e96509934e3a4) by [@cipolleschi](https://github.com/cipolleschi)) +- ([16276ce0f6](https://github.com/facebook/react-native/commit/16276ce0f6115fd4decaccaf33cf3364bbd2d469) by [@philIip](https://github.com/philIip)) +- Allow libraries to provide module which conforms to protocols meant to be extension points. ([46d7f8a669](https://github.com/facebook/react-native/commit/46d7f8a66925ebfad9c8474028fcb69e9735def4) by [@cipolleschi](https://github.com/cipolleschi)) +- Add nullable annotations to RCTBundleURLProvider ([12e4a5745d](https://github.com/facebook/react-native/commit/12e4a5745d54a7be86c005e4ed954c42171541b2) by [@okwasniewski](https://github.com/okwasniewski)) +- Remove unused getHeight method from StatusBar ([3dfedbc1ae](https://github.com/facebook/react-native/commit/3dfedbc1aec18a4255e126fde96d5dc7b1271ea7) by [@okwasniewski](https://github.com/okwasniewski)) +- Introduce native api to access RuntimeExecutor ([343a0d3cd8](https://github.com/facebook/react-native/commit/343a0d3cd82770bcb00bad30fdf353acf148057a) by [@philIip](https://github.com/philIip)) +- Make codegen take OOT Apple platforms into account ([ebb2b9c3fc](https://github.com/facebook/react-native/commit/ebb2b9c3fce227135f437bd86db71125eebcf21f) by [@okwasniewski](https://github.com/okwasniewski)) +- Introduce `vision` interfaceIdiom ([258d8e51b4](https://github.com/facebook/react-native/commit/258d8e51b451b221e557dad4647cbd210fe37392) by [@okwasniewski](https://github.com/okwasniewski)) +- Provide better Swift types for RCTAppDelegate and RCTBridgeDelegate ([a7c5c2821c](https://github.com/facebook/react-native/commit/a7c5c2821c39a7bf653919353897d27d29a64068) by [@okwasniewski](https://github.com/okwasniewski)) +- Add `shouldBeRecycled` method on `iOS`. ([613a5a7597](https://github.com/facebook/react-native/commit/613a5a75977d84333df7cbd5701e01a7ab5a3385) by [@WoLewicki](https://github.com/WoLewicki)) +- Added the `RCTIsNewArchEnabled()` to check whether the New Arch is enabled at runtime. ([f1a7f08feb](https://github.com/facebook/react-native/commit/f1a7f08feb2a63926e91d37b5d85130c7b74ee31) by [@cipolleschi](https://github.com/cipolleschi)) +- Added the customiseRootView method which is called in both bridge and bridgeless. Added also a warning for 0.74 with instructions on how to migrate. ([db9c9eacac](https://github.com/facebook/react-native/commit/db9c9eacac301c4a684130413423eab50bbb1d72) by [@cipolleschi](https://github.com/cipolleschi)) +- Added better support for `ccache`, to speed up subsequent builds of native code. After installing `ccache` and running `pod install`, the Xcode project is injected with compiler and linker build settings pointing scripts that loads a default Ccache configuration and invokes the `ccache` executable. ([e85d51c6f1](https://github.com/facebook/react-native/commit/e85d51c6f161c709706044c5955ac5397e746fa1) by [@kraenhansen](https://github.com/kraenhansen)) +- Add use of the `REACT_NATIVE_PATH` in the "Bundle React Native code and images" shell script build phase. This will help apps initialized into a mono-repo which hoists the `react-native` package. ([289e78388a](https://github.com/facebook/react-native/commit/289e78388a87408e215a25108cb02511a05f5c80) by [@kraenhansen](https://github.com/kraenhansen)) +- Support "highlighting updates when components render" feature from React DevTools ([758e59f1d9](https://github.com/facebook/react-native/commit/758e59f1d9752cf051b2dee900c5182ee52c4189) by [@hoxyq](https://github.com/hoxyq)) +- ([e9ecc65652](https://github.com/facebook/react-native/commit/e9ecc656528ec54e93a9bcd43e39e0b6888a6ed5) by [@philIip](https://github.com/philIip)) +- Make build-hermes-xcode.sh more extensible for out-of-tree platforms ([7bcfd02a60](https://github.com/facebook/react-native/commit/7bcfd02a60667e74041c8172e5499cfc75759da1) by [@okwasniewski](https://github.com/okwasniewski)) +- Add console.log notification in DevTools if app transitions between back/foreground. ([05967e471e](https://github.com/facebook/react-native/commit/05967e471e52512bb52108bd821edad824c98705) by [@blakef](https://github.com/blakef)) +- Add TypeScript typings for the `dismissActionSheet` function in `ActionSheetIOS`. ([89c7be890b](https://github.com/facebook/react-native/commit/89c7be890b0dcef72e465b70314ac47ca5ca0280) by [@LRNZ09](https://github.com/LRNZ09)) +- Add support for `Platform.isMacCatalyst` ([027d520d65](https://github.com/facebook/react-native/commit/027d520d657ab0c3dd30913c589692a496ad36da) by [@jacobp100](https://github.com/jacobp100)) + +### Changed + +- Bump CLI to 13.6.0 ([c99d96b7a1](https://github.com/facebook/react-native/commit/c99d96b7a1a4dc905ce642966633b4d3c78bd3c9) by [@szymonrybczak](https://github.com/szymonrybczak)) +- CodegenNativeComponent show warning and not error if not code generated at build time. ([de5619ed8c](https://github.com/facebook/react-native/commit/de5619ed8cf4a07d9a23a7714e25611e970ed46e) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Make template's .gitignore file universal for OOT platforms ([c5f48ac612](https://github.com/facebook/react-native/commit/c5f48ac61279d9af12d7aea0b0a6177ce5f54397) by [@okwasniewski](https://github.com/okwasniewski)) +- Sync React renderers to 18.3.0-canary-03d6f7cf0-20240209 ([3272b05c3d](https://github.com/facebook/react-native/commit/3272b05c3d148a814e8639e2b9784d5190f4feea) by [@sammy-SC](https://github.com/sammy-SC)) +- React@18.3.0-canary-b2d637128-20240123 ([29df29f5e2](https://github.com/facebook/react-native/commit/29df29f5e297ea46543303c28f2487dba53e243f) by [@sammy-SC](https://github.com/sammy-SC)) +- Changed community cli plugin homepage url. ([6f7e8e17e2](https://github.com/facebook/react-native/commit/6f7e8e17e28c73ba5511332bcdd8abf4122de7f6) by [@hoonjoo-park](https://github.com/hoonjoo-park)) +- Bump CLI to 13.5.1 ([78967b33c0](https://github.com/facebook/react-native/commit/78967b33c0562a07ff7b38c48056532cbf9321b4) by [@szymonrybczak](https://github.com/szymonrybczak)) +- Update API docs for scrollEventThrottle ([3ea0598341](https://github.com/facebook/react-native/commit/3ea059834145c48d2f9d4a8ecdf73adfaf0c684e) by [@NickGerleman](https://github.com/NickGerleman)) +- Updated Pressability/usePressability Docblocks ([0fd7bd3a7f](https://github.com/facebook/react-native/commit/0fd7bd3a7f62b72f70da42608ff933a9fb1a63d9) by [@yungsters](https://github.com/yungsters)) +- Bump folly version to 2024.01.01.00 ([cfeb43eaa2](https://github.com/facebook/react-native/commit/cfeb43eaa2fa99454de67c88a3a461de6ebdfe88) by [@Kudo](https://github.com/Kudo)) +- Update monorepo dependency versions to remove ^ ([6e5bc33b3c](https://github.com/facebook/react-native/commit/6e5bc33b3c9cd0ce2c30c7689982c6fb16ef4e3b) by [@lunaleaps](https://github.com/lunaleaps)) +- Be explicit about what monorepo versions we are using ([b5e08e80d9](https://github.com/facebook/react-native/commit/b5e08e80d90b6d03d1f49f0674c01f03ee300c46) by [@lunaleaps](https://github.com/lunaleaps)) +- Bump CLI to v13.0.0 ([6e88d67b8c](https://github.com/facebook/react-native/commit/6e88d67b8c4631431bd04c1a23ae7cb520b9c0bd) by [@thymikee](https://github.com/thymikee)) +- Fix issue where we were not applying flex end correctly when justifying ([579ef2b3fb](https://github.com/facebook/react-native/commit/579ef2b3fbeb2b475ea9c6d426b1e84a964c25f1) by [@joevilches](https://github.com/joevilches)) +- Use `hermes-parser` instead of `flow-parser` to parse Flow Codegen specs. ([5abaf388cd](https://github.com/facebook/react-native/commit/5abaf388cde499747e81ecb73aa01fa819dbbd47) by [@motiz88](https://github.com/motiz88)) +- Fix issue where absolute children of row-reverse containers would inset on the wrong side ([9847bcab51](https://github.com/facebook/react-native/commit/9847bcab514142d9132dca36544fc7628ddbf437) by [@joevilches](https://github.com/joevilches)) +- Upgrade CLI to v12.0.0 ([d077239fff](https://github.com/facebook/react-native/commit/d077239fff600d41d093dfeca87f6744bd7f1cd3) by [@szymonrybczak](https://github.com/szymonrybczak)) +- Apply Babel arrow transform only on non-Hermes ([9a3b75c782](https://github.com/facebook/react-native/commit/9a3b75c7824e1b8896ffc4f05c3386587513f2be) by [@gaearon](https://github.com/gaearon)) +- Update Metro to ^v0.80.0, stop pinning to an exact version ([7853b06929](https://github.com/facebook/react-native/commit/7853b06929ea6186dbc5923393b5521c2d6ae09d) by [@robhogan](https://github.com/robhogan)) +- Use ImageRequireSource instead of number for the defaultSource prop typing of the Image component ([2be1c71cb7](https://github.com/facebook/react-native/commit/2be1c71cb7be18906c89ab8706551ce260f77f51) by [@ellouzeskandercs](https://github.com/ellouzeskandercs)) +- Gate new debugger frontend behind `--experimental-debugger` flag, restore Flipper as base launch flow ([9e068ac163](https://github.com/facebook/react-native/commit/9e068ac163db057cc76bac2caba76136d19bcf49) by [@huntie](https://github.com/huntie)) +- Make layout events top-down on Android classic renderer ([25478321f9](https://github.com/facebook/react-native/commit/25478321f9d88730d006221a90f5d84f32d3ffcd) by [@NickGerleman](https://github.com/NickGerleman)) +- UIManagerModule: Make reactTags required ([fafd00ab1a](https://github.com/facebook/react-native/commit/fafd00ab1ad8e78fb0b992f5ce1b35211d4089ee) by [@RSNara](https://github.com/RSNara)) +- Make ImageManager implementation overridable ([ac1cdaa716](https://github.com/facebook/react-native/commit/ac1cdaa71620d5bb4860237cafb108f6aeae9aef) by [@rshest](https://github.com/rshest)) +- Share ImageRequest implementation across the platforms ([7625a50296](https://github.com/facebook/react-native/commit/7625a502960e6b107e77542ff0d6f40fbf957322) by [@rshest](https://github.com/rshest)) +- Support for (de)serializing config values ([e1afa023aa](https://github.com/facebook/react-native/commit/e1afa023aa434cf8df5af70e85d6352e1abe7ca0) by [@joevilches](https://github.com/joevilches)) +- Fix mismatched cases of inlineStart/End and flexStart/End ([64d81905ac](https://github.com/facebook/react-native/commit/64d81905acbdbef01f9bc5818a20367917372be4) by [@joevilches](https://github.com/joevilches)) +- Replace CompactValue with StyleValueHandle and StyleValuePool ([92b889b89e](https://github.com/facebook/react-native/commit/92b889b89e92bb52ba2d6868bf6de4d7c3972368) by [@NickGerleman](https://github.com/NickGerleman)) +- Simplify Edge Resolution ([40c4552d02](https://github.com/facebook/react-native/commit/40c4552d0227ba5d213139c3c4e0b88743b7b4e1) by [@NickGerleman](https://github.com/NickGerleman)) +- Make position static behave like position static ([475036d2cd](https://github.com/facebook/react-native/commit/475036d2cd9852335da5c22a67700e9243b35024) by [@joevilches](https://github.com/joevilches)) +- Make positionAbsoluteChild the sole place that matters when determining absolute node's position ([6025d50925](https://github.com/facebook/react-native/commit/6025d50925b4e35b3bdfb2165e6466862544865c) by [@joevilches](https://github.com/joevilches)) +- Introduce positionAbsoluteChild ([7459529ee4](https://github.com/facebook/react-native/commit/7459529ee46cf4a9aaa3251887bf67dbc1fa3f7f) by [@joevilches](https://github.com/joevilches)) +- Use containing block to adjust absolute child position ([a48e0d590e](https://github.com/facebook/react-native/commit/a48e0d590e9e62caf14cc833d3abf41e5882b571) by [@joevilches](https://github.com/joevilches)) +- Allow the containing block to set trailing position of absolute descendants ([43ab5fe38c](https://github.com/facebook/react-native/commit/43ab5fe38ccc8a5eaa6d885b216cc45d0a9c833d) by [@joevilches](https://github.com/joevilches)) +- Let containing blocks layout their absolute descendants, not parents ([33d6a59bea](https://github.com/facebook/react-native/commit/33d6a59bea4cdc2eea116786267b4768277731c8) by [@joevilches](https://github.com/joevilches)) +- Insets no longer apply to statically positioned nodes ([e48da2aff3](https://github.com/facebook/react-native/commit/e48da2aff33b5d7831e0946b6e492b849de43344) by [@joevilches](https://github.com/joevilches)) +- Change default back to `position: "relative"` ([88a55baeaa](https://github.com/facebook/react-native/commit/88a55baeaaa68619d815f53a51e32edb937e291f) by [@NickGerleman](https://github.com/NickGerleman)) +- Remove NumericBitfield ([9078db77a9](https://github.com/facebook/react-native/commit/9078db77a900aa417c3cdf6e8e5b4217061cc442) by [@NickGerleman](https://github.com/NickGerleman)) +- Introduce isDefined() and remove cases of !isUndefined() ([3b13d3c7d0](https://github.com/facebook/react-native/commit/3b13d3c7d0ff128f766e37b630687eb52a2cce5a) by [@joevilches](https://github.com/joevilches)) +- Simplify getting padding + border for cross axis in algorithm ([1984bcc0c1](https://github.com/facebook/react-native/commit/1984bcc0c100fe24ad4d44e4bb61d8f288c1d40c) by [@joevilches](https://github.com/joevilches)) +- Add errata supporting changes to position: static ([60297d50dc](https://github.com/facebook/react-native/commit/60297d50dcb4a97d4d4d68f46047288014df5b79) by [@joevilches](https://github.com/joevilches)) +- Fix issue where position insets were not working with row reverse ([25575e57cb](https://github.com/facebook/react-native/commit/25575e57cb430bfb1e237bbe1700c2f67846f374) by [@joevilches](https://github.com/joevilches)) +- Build with MSVC /W4 ([8eb0617d95](https://github.com/facebook/react-native/commit/8eb0617d95e709ed88e36a2b0eb52d8fbea331b8) by [@NickGerleman](https://github.com/NickGerleman)) +- Rename ambiguous getLeading/Trailing... functions in Node.cpp ([ef32905172](https://github.com/facebook/react-native/commit/ef32905172aa7b559d9a677751260fd5898e5b97) by [@joevilches](https://github.com/joevilches)) +- FloatOptional GCC build fix and more constexpr ([5e5019c723](https://github.com/facebook/react-native/commit/5e5019c723db9eba5271845361e0cd46f088deab) by [@NickGerleman](https://github.com/NickGerleman)) +- Make all annotation processors derive from ProcessorBase ([fea445ee2d](https://github.com/facebook/react-native/commit/fea445ee2dfa1bf64b99f7bc1e12be0a8bcd7e71) by [@ianlevesque](https://github.com/ianlevesque)) +- Remove usage of Gutters arrays and YGGutter as index ([4da0d44e55](https://github.com/facebook/react-native/commit/4da0d44e55485bf622aae85a6b7a92e342f3eaf2) by [@NickGerleman](https://github.com/NickGerleman)) + +#### Android specific + +- Kotlin to 1.9.22 ([3c2b2b181c](https://github.com/facebook/react-native/commit/3c2b2b181c593f48a870d6d2211875590aa3da29) by [@cortinico](https://github.com/cortinico)) +- Android NDK to 26.1 ([5f75e9b90d](https://github.com/facebook/react-native/commit/5f75e9b90d4f998403101ae92924778df31d36fb) by [@cortinico](https://github.com/cortinico)) +- Fix "Show Perf Monitor" crash in Catalyst ([6f115110c4](https://github.com/facebook/react-native/commit/6f115110c4bc7c44f84446304cc5b658a5d9449a)) +- Fix dev menu not open for Bridgeless ([e4887a587a](https://github.com/facebook/react-native/commit/e4887a587a51478dc0302701f48675e8f7175b72)) +- NetworkingModuleTest.java -> NetworkingModuleTest.kt ([852f2b1758](https://github.com/facebook/react-native/commit/852f2b17587c0998ba2c5b1bfa44a2ce59239cff) by [@KrzysztofMoch](https://github.com/KrzysztofMoch)) +- Integrate binary-compatibility-validator into RN Android build system ([e9b80971c7](https://github.com/facebook/react-native/commit/e9b80971c7f510d7101998a7985e871481dc1bc6) by [@mdvacca](https://github.com/mdvacca)) +- Use null to signal a missing TurboModule instead of IllegalArgumentException. ([228193dad5](https://github.com/facebook/react-native/commit/228193dad5369cdb5e13ba8a926e0ab9d12429e7) by [@javache](https://github.com/javache)) +- Fix backward compatibility breakage ([1891d9e647](https://github.com/facebook/react-native/commit/1891d9e6470ef90dcfcf27ce05944737c235310e) by [@mdvacca](https://github.com/mdvacca)) +- Continuation of PR: 36263 ([a337f6eda7](https://github.com/facebook/react-native/commit/a337f6eda71424e2eaa765aabef2a932bfac221f) by [@ricku44](https://github.com/ricku44)) +- Bridgeless: Add support for legacy UIManager in UIManagerHelper ([10c3292694](https://github.com/facebook/react-native/commit/10c32926949aa5c6432be2d949d8412af5c3a1f2)) +- Fall back to eager view manage loading for Bridgeless ([6b3289bc73](https://github.com/facebook/react-native/commit/6b3289bc731eb5c4855dbd349d926fa2e4e3595b)) +- Ensure namespace is specified for all the 3rd party libraries ([13ae11152a](https://github.com/facebook/react-native/commit/13ae11152a51444c0d8494faa1fcd221d0d89f2f) by [@gabrieldonadel](https://github.com/gabrieldonadel)) +- Fix RNTester not showing Redbox when Metro is not connected ([b67bc3ffd3](https://github.com/facebook/react-native/commit/b67bc3ffd3fe6db3d2fd9e5796bf02815cb29408)) +- Deprecate CompositeReactPackageTurboModuleManagerDelegate ([6f11334c42](https://github.com/facebook/react-native/commit/6f11334c42169b64964bb48c2839c9d563045259) by [@mdvacca](https://github.com/mdvacca)) +- Enable fast refresh banner for Bridgeless ([66fbab2586](https://github.com/facebook/react-native/commit/66fbab258638f189734da3533ff83388be57e84e)) +- Add DoNotStripAny to JSTimerExecutor ([56683b0c77](https://github.com/facebook/react-native/commit/56683b0c777413e6d76fdb6494295922ae3d4a13)) +- Enabling Explicit API warning, this will be changed as Strict in a future version ([490b51c7c3](https://github.com/facebook/react-native/commit/490b51c7c38884f13c4b5d15ab0b7cad473a48d8) by [@mdvacca](https://github.com/mdvacca)) +- Add Add ExceptionsManagerModule to CoreReactPackage ([4d70337fb5](https://github.com/facebook/react-native/commit/4d70337fb52bb66b0f749ac9958a3da1b24f6b54)) +- Reducing visibility of FrescoBasedReactTextInlineImageSpan ([be1c3cb3ca](https://github.com/facebook/react-native/commit/be1c3cb3caf427cdf2b7a7517370af70852c0465) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of FrescoBasedReactTextInlineImageShadowNode ([f158939efa](https://github.com/facebook/react-native/commit/f158939efa544567ce37226f3b78714978b02286) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of RefreshEvent ([e96cbcc4dc](https://github.com/facebook/react-native/commit/e96cbcc4dc709ec5b7687018c06a0dc38bf967e0) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of VelocityHelper ([05064dc660](https://github.com/facebook/react-native/commit/05064dc66093974f6cd7a126bc23b72b337a4cf1) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactScrollViewAccessibilityDelegate ([a81481cb0c](https://github.com/facebook/react-native/commit/a81481cb0c02b40229af0ac83531bdbcbae2ae60) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of MaintainVisibleScrollPositionHelper ([88a4be378f](https://github.com/facebook/react-native/commit/88a4be378f47fc45e3e4f625a9be2d9662f93897) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ScaleTypeStartInside ([0d0e0e1b53](https://github.com/facebook/react-native/commit/0d0e0e1b53e17cd9844e4267ff96c9903369e226) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactImageDownloadListener ([9582f98099](https://github.com/facebook/react-native/commit/9582f98099709f1097544515e30f938b56dbf9f6) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactEventEmitter ([fa1a29bdc0](https://github.com/facebook/react-native/commit/fa1a29bdc0f29980424eaf7f788c5d85aa01fae5) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of YogaNodePool ([aa4490df11](https://github.com/facebook/react-native/commit/aa4490df11213c31749785789b39a24d13b7ec64) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ViewHierarchyDumper ([0316f8d117](https://github.com/facebook/react-native/commit/0316f8d117623167e38127d5adc9c6a647b1abd9) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ShadowNodeRegistry ([e2aae65dd4](https://github.com/facebook/react-native/commit/e2aae65dd4d6cbe57c1f1dee6c8cc6738a8cddc3) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of NoSuchNativeViewException ([4f6a74438d](https://github.com/facebook/react-native/commit/4f6a74438d38f2a82dc674b3d3c3bfac2a1e845c) by [@mdvacca](https://github.com/mdvacca)) +- Bump Gradle to 8.4 ([81213f6524](https://github.com/facebook/react-native/commit/81213f652427d35219bf491bb84418d8c9faa2cb) by [@cortinico](https://github.com/cortinico)) +- Bump AGP to 8.1.2 ([22388fe938](https://github.com/facebook/react-native/commit/22388fe938a38e0b50dbe42da688cb2e7521e637) by [@cortinico](https://github.com/cortinico)) +- Reducing visibility of UnobservedTaskException ([f4023129be](https://github.com/facebook/react-native/commit/f4023129beae7835d92ef2d968f06b180538f391) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ExecutorException ([9d3fa2715d](https://github.com/facebook/react-native/commit/9d3fa2715d6966842a17af66e5b15dbaba9bbe8f) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of Capture ([456335a7eb](https://github.com/facebook/react-native/commit/456335a7eb9b2ffd809b5f5af6a2963ac7683cf4) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of CancellationTokenRegistration ([22a3aeafcf](https://github.com/facebook/react-native/commit/22a3aeafcf80e5d29de49811cd6c93d04157d01d) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of AggregateException ([2c5d976000](https://github.com/facebook/react-native/commit/2c5d9760002d1a2d66e2afcbf3bd9f7f00e15bd2) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ProgressiveStringDecoder ([8c862f6cc4](https://github.com/facebook/react-native/commit/8c862f6cc4a01fb7f90bfdf8f0a7aaf90da824ba) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ProgressRequestBody ([4240eb06ab](https://github.com/facebook/react-native/commit/4240eb06abec070cc2cbc0ca67bdf0a79de386fb) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of HeaderUtil ([fd57f669ff](https://github.com/facebook/react-native/commit/fd57f669ff60e691e1d94460a4b30cde19613652) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of CountingOutputStream ([c5c6954596](https://github.com/facebook/react-native/commit/c5c6954596f0914fcb2057c8e5624c6e4ebf4c39) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of DidJSUpdateUiDuringFrameDetector ([366bcef631](https://github.com/facebook/react-native/commit/366bcef631e4b73fdb2489cb0683f2a4e97f72d2) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of AnimationsDebugModule ([9c8ba251a1](https://github.com/facebook/react-native/commit/9c8ba251a1a278a24556e64aac736e0240100d92) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of NoRetryPolicy ([26c5cba6a9](https://github.com/facebook/react-native/commit/26c5cba6a918327c711e5686ac692673c83e1c4a) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of SendAccessibilityEvent ([90436bb3f8](https://github.com/facebook/react-native/commit/90436bb3f868be7cb5e2f9dd0c65d110cd9d2b9d) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ViewHierarchyUtil ([6464acab36](https://github.com/facebook/react-native/commit/6464acab360565d4693a8ead44c14af6583cda47) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of RedBoxDialogSurfaceDelegate ([3e594ea3dc](https://github.com/facebook/react-native/commit/3e594ea3dc7d9d55e5afe3346b411f9b34f2ce73) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of MultipartStreamReader ([b8cded3df6](https://github.com/facebook/react-native/commit/b8cded3df63818c06df7a0e7a7a0ae79a4ac475a) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of LogBoxDialogSurfaceDelegate ([f46bc717cd](https://github.com/facebook/react-native/commit/f46bc717cd4a37140f5b96b8753f0a40c5559742) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of LogBoxDialog ([c9417ff5f4](https://github.com/facebook/react-native/commit/c9417ff5f42946ddda08df401625b9088285efce) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of FpsView ([55d0ac6ab3](https://github.com/facebook/react-native/commit/55d0ac6ab3ed8ac3440c5891fdd9ef92eca1635f) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of UIManagerProvider ([0939908f67](https://github.com/facebook/react-native/commit/0939908f670b2da68a13448f07099d32a274d6e7) by [@mdvacca](https://github.com/mdvacca)) +- Use NDK 26 ([9ce7b56413](https://github.com/facebook/react-native/commit/9ce7b564131c5b2075489c09ff05325ddc28014a) by [@NickGerleman](https://github.com/NickGerleman)) +- Rewrite RNTesterApplication to Kotlin, add AnnotationTarget property. ([c4110d0475](https://github.com/facebook/react-native/commit/c4110d0475c27da9fac4161ed8ee376757b47429) by [@Mod3rnx](https://github.com/Mod3rnx)) +- Rewrite ReactPropAnnotationSetterTest to Kotlin, ([ea88338d75](https://github.com/facebook/react-native/commit/ea88338d75d38e6639636eca58e824ed7e796403)) +- Reducing visibility of PerformanceCounter ([614afb5983](https://github.com/facebook/react-native/commit/614afb598335de388d15f9d9f2ec67d1b6db2790) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of NativeArrayInterface ([e46372ffa4](https://github.com/facebook/react-native/commit/e46372ffa4e614e903717c3c5e57a30d444ec4a4) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of NativeArgumentsParseException ([970ea5e476](https://github.com/facebook/react-native/commit/970ea5e476738399e06221fe729044e2137e0f8b) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of JSInstance ([d224816ed1](https://github.com/facebook/react-native/commit/d224816ed1095f5daf844f689d683c61c6f1a3a8) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of JSIModuleRegistry. ([e3e9b1388f](https://github.com/facebook/react-native/commit/e3e9b1388f9805636afc354032d3f7bf3ad4eb1f) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of JSIModuleHolder ([9ba05493b8](https://github.com/facebook/react-native/commit/9ba05493b82896250547499bb02529b4082b7836) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of JSCJavaScriptExecutorFactory ([11d51fe395](https://github.com/facebook/react-native/commit/11d51fe39596ad6fde37e5e3feca06dcef137fa5) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of DynamicFromMap ([7a5824b416](https://github.com/facebook/react-native/commit/7a5824b4167c8f56620e5efc89b8c1f1a4cbd96d) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of DynamicFromArray ([d6cd496c44](https://github.com/facebook/react-native/commit/d6cd496c440e038053e8b5ef84092f558d242ca1) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of DecayAnimation ([5d386b795e](https://github.com/facebook/react-native/commit/5d386b795e9962217cd1571b33550bf5cac392df) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of AnimatedNodeWithUpdateableConfig ([5bbc89e4be](https://github.com/facebook/react-native/commit/5bbc89e4be6b0ccf9fda2ce1510f52839182c73d) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of AnimatedNodeValueListener ([f202d1b44b](https://github.com/facebook/react-native/commit/f202d1b44b0253e5680f72150e10fc7cbf7ba0da) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactPackageHelper ([7e00f536b3](https://github.com/facebook/react-native/commit/7e00f536b37890bc2503750468c7db7b4a9f502e) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactTextInputKeyPressEvent ([c7564c76f3](https://github.com/facebook/react-native/commit/c7564c76f3c77769629b8ae720a9d3a8417c117f) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of ReactAndroidHWInputDeviceHelper ([93b1dc9633](https://github.com/facebook/react-native/commit/93b1dc9633e9e28c24c6f20dc82e8699b430bf6b) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of EagerModuleProvider ([78097648d3](https://github.com/facebook/react-native/commit/78097648d305b35b17cbc11626a5b25a2ea77292) by [@mdvacca](https://github.com/mdvacca)) +- Reducing visibility of CanvasUtil ([aad82f5032](https://github.com/facebook/react-native/commit/aad82f50325869eeb906273e554a242ea85f715f) by [@mdvacca](https://github.com/mdvacca)) +- Fully rollout FabricSharedEventPipeline ([91fe3b484b](https://github.com/facebook/react-native/commit/91fe3b484b8e0807e4edaaa6ed4bb5c2f540e9fd) by [@mdvacca](https://github.com/mdvacca)) +- Support grouped focus for switch ([06c295c58f](https://github.com/facebook/react-native/commit/06c295c58fe5449ecbf69bfb52bb8e52cd64308b) by [@carmenvkrol](https://github.com/carmenvkrol)) + +#### iOS specific + +- Make RCTConvert an Objective-C++ (`.mm`) file in prep for DisplayP3 changes ([267ea2661a](https://github.com/facebook/react-native/commit/267ea2661aa1fb434422c39094c98713d9853be7) by [@cipolleschi](https://github.com/cipolleschi)) +- Migrated RNTester/AppDelegate to the new notification callback ([ccff2bb8d1](https://github.com/facebook/react-native/commit/ccff2bb8d19b2db244f30293b4e8d68a524c2059)) +- Add the for the dismissal snapshot only when we need it. ([7c4afa1006](https://github.com/facebook/react-native/commit/7c4afa1006ac07e07345682d91fd36ac0025b8a9) by [@cipolleschi](https://github.com/cipolleschi)) +- Use less verbose Auto Layout API for RCTRedBox constraints ([b311c3e0a0](https://github.com/facebook/react-native/commit/b311c3e0a00bf8051194bbb5072a9341cf3f6e10) by [@okwasniewski](https://github.com/okwasniewski)) +- Refactor `RCTKeyWindow` to be more resilient and work in multi-window apps ([782e9eace9](https://github.com/facebook/react-native/commit/782e9eace974baefba7d8978739f11fe1ea70dc9) by [@okwasniewski](https://github.com/okwasniewski)) +- Add `NDEBUG` flag for Release builds for both architectures ([1a0e1741c0](https://github.com/facebook/react-native/commit/1a0e1741c0ab4f22b57a6a7ee86ff4287fa09103) by [@tjzel](https://github.com/tjzel)) +- ScrollEventThrottle no longer needs to be set for continuous scroll events ([10b3e0e868](https://github.com/facebook/react-native/commit/10b3e0e8688a7a140578fe25e799d4b379595e69) by [@NickGerleman](https://github.com/NickGerleman)) +- `scrollEventThrottle` no longer needs to be set for continuous scroll events when using the new architecture. ([56b57e2db4](https://github.com/facebook/react-native/commit/56b57e2db4d75b32706ebbaa5bee02d48beab945) by [@NickGerleman](https://github.com/NickGerleman)) +- Update 'cannot calculate shadow efficiently' log message to explicitly say solid background ([94c7661206](https://github.com/facebook/react-native/commit/94c76612062c548782cb9b033398467cb8a079e4) by [@gabrieldonadel](https://github.com/gabrieldonadel)) +- Retrieve screen scale from trait collection instead of UIScreen mainScreen ([ace81ff7d8](https://github.com/facebook/react-native/commit/ace81ff7d81b2eb547ad93b8000c5906dfefd9d3) by [@okwasniewski](https://github.com/okwasniewski)) +- Migrate RCTTextView to UIEditMenuInteraction ([e08a1973f6](https://github.com/facebook/react-native/commit/e08a1973f67d85acc157111c749c43572469e4c2) by [@okwasniewski](https://github.com/okwasniewski)) +- Update SocketRocket to 0.7.0 ([bab9c839ea](https://github.com/facebook/react-native/commit/bab9c839eaad1ffc358fa5c87440a6de7cbe981b) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Align all pods to 13.4 ([c852955e4b](https://github.com/facebook/react-native/commit/c852955e4bb8454e44507c34653c5f76f4f1f130) by [@cipolleschi](https://github.com/cipolleschi)) +- Rename `RCTRootViewFrameDidChangeNotification` as it's not tracking root view frame changes ([625d0ece6d](https://github.com/facebook/react-native/commit/625d0ece6da80df6e3e3ee7daa1f7f59ddbbf387) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Matched behaviour for allowsEdgeAntialiasing to old architecture. ([6fb0fbadc0](https://github.com/facebook/react-native/commit/6fb0fbadc0a39ab95f22fdb5101dc55596aa2114) by [@javache](https://github.com/javache)) +- Bump SocketRocket to 0.6.1 ([8b88883071](https://github.com/facebook/react-native/commit/8b88883071693cf67db41fec79d4068392e77f2a) by [@gabrieldonadel](https://github.com/gabrieldonadel)) +- Deterministic onLayout event ordering for iOS Paper ([56ddace9c8](https://github.com/facebook/react-native/commit/56ddace9c8ffdde5485f1dbe4c5004070cf78262) by [@NickGerleman](https://github.com/NickGerleman)) +- Rearrange RNComponentViewUpdateMask value ([476a323e0d](https://github.com/facebook/react-native/commit/476a323e0d5c7c0876899e9de6460c069720655e) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Move `[RCTConvert RCTTransformOrigin:]` out of UIAccessibilityTraits category ([c7aa3954e3](https://github.com/facebook/react-native/commit/c7aa3954e347352b9e800cb9ec3b4e9800366250) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Remove `` import in `RCTConvert.h` ([452bf0ff06](https://github.com/facebook/react-native/commit/452bf0ff069b77fc880c57fcb86dbe44ac7285fc) by [@Saadnajmi](https://github.com/Saadnajmi)) + +### Deprecated + +- Deprecate BatchedBridge.registerCallableModule. Please use registerCallableModule instead ([7f549ec7be](https://github.com/facebook/react-native/commit/7f549ec7bebecddcb13087ab132f38c4eb68ef97) by [@RSNara](https://github.com/RSNara)) +- Warn when fabric is used without concurrent root ([c06807154b](https://github.com/facebook/react-native/commit/c06807154b309bd85626a5e9ca2f23ac7a7750b6) by [@javache](https://github.com/javache)) +- Replace RAIICallbackWrapperDestroyer with AsyncCallback (re-land) ([fbd8504cc0](https://github.com/facebook/react-native/commit/fbd8504cc0df8d65fd1782eafcab7b9d464d539b) by [@javache](https://github.com/javache)) +- Deprecated RAIICallbackWrapperDestroyer. Use AsyncCallback instead for safe jsi::Function memory ownership. ([8dd89cee1b](https://github.com/facebook/react-native/commit/8dd89cee1b69c953fa01818c588b86fd96f1ce4d) by [@javache](https://github.com/javache)) +- Refactor BaseJavaModule and ReactContextBaseJavaModule ([5af7b7038c](https://github.com/facebook/react-native/commit/5af7b7038c730289cd8420060c039197f45e7397) by [@mdvacca](https://github.com/mdvacca)) + +#### Android specific + +- Deprecate UIManager.showPopupMenu, and UIManager.dismissPopupMenu ([8a8f74b7b2](https://github.com/facebook/react-native/commit/8a8f74b7b2355b78bcdc7d8a23bf5ef5f0b93926) by [@RSNara](https://github.com/RSNara)) +- Deprecate FabricViewStateManager ([4fdc5945b1](https://github.com/facebook/react-native/commit/4fdc5945b1e00d23b6b149070b9403b436fd48ff) by [@sammy-SC](https://github.com/sammy-SC)) + +#### iOS specific + +- **Un-deprecates** `RCTAppSetupPrepareApp` (reverts #41976) ([ce3ce1194b](https://github.com/facebook/react-native/commit/ce3ce1194baacb62dbac50f59444618921d03316) by [@huntie](https://github.com/huntie)) +- Retrieving initial notification requires UNUserNotificationCenterDelegate setup instead of reading UIApplicationLaunchOptionsLocalNotificationKey ([c8ab44cf0b](https://github.com/facebook/react-native/commit/c8ab44cf0b1e63ac7224147f3df1f414a29b65a0) by [@philIip](https://github.com/philIip)) +- Deprecating RCTPushNotificationManager's didReceiveLocalNotification: and didReceiveRemoteNotification: ([1b85ed94a1](https://github.com/facebook/react-native/commit/1b85ed94a1a8b9d4c53d2129b8d5f5329fef35c5)) +- Deprecate `[RCTConvert UIBarStyle:]` ([157cb0e02b](https://github.com/facebook/react-native/commit/157cb0e02b6328e8b640f2b302a11c298a240493) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Deprecate `RCTAppSetupPrepareApp`, replaced with C++ overload ([7a4950b366](https://github.com/facebook/react-native/commit/7a4950b366ab20c1064c849a3739a3d455400d16) by [@huntie](https://github.com/huntie)) +- ([a0efa26065](https://github.com/facebook/react-native/commit/a0efa26065a4833d3f950f6ad8fd7a7deee432a3) by [@philIip](https://github.com/philIip)) +- ([9b1f8a81e9](https://github.com/facebook/react-native/commit/9b1f8a81e9af971af6ddc1dc4ef96302bf4a08d7) by [@philIip](https://github.com/philIip)) +- Deprecate RCTGetMultiplierForContentSizeCategory ([f174f028cf](https://github.com/facebook/react-native/commit/f174f028cfae29735e3f04ad5f42079b67658642) by [@Saadnajmi](https://github.com/Saadnajmi)) + +### Removed + +- Removed type definition `UIManager.takeSnapshot()` ([184b295a01](https://github.com/facebook/react-native/commit/184b295a019e2af6712d34276c741e0dae78f798) by [@maxphillipsdev](https://github.com/maxphillipsdev)) +- Remove ineffective excludes from typescript-config ([b9621976bc](https://github.com/facebook/react-native/commit/b9621976bc75c130b1e51149ced3ab4a524cd658) by [@friederbluemle](https://github.com/friederbluemle)) +- Removed deprecated prop types ([228cb80af9](https://github.com/facebook/react-native/commit/228cb80af9ded20107f3c7a30ffe00e24471bfeb) by [@yungsters](https://github.com/yungsters)) +- : removed `DevtoolsOverlay` & `TraceUpdateOverlay` from production bundle ([0004888608](https://github.com/facebook/react-native/commit/0004888608077bdd5e6e080ce2fbe4f5ff9ea6d9) by [@ecreeth](https://github.com/ecreeth)) +- : removed `Object.{values & entries}` from polyfills ([04c501fa4a](https://github.com/facebook/react-native/commit/04c501fa4ae9eccd6daa946f62b0369cf5023c5a) by [@ecreeth](https://github.com/ecreeth)) + +#### Android specific + +- Updated migrated guidance for EventEmitter and reduced visibility of internal TouchesHelper methods ([c9764c5a17](https://github.com/facebook/react-native/commit/c9764c5a17b246972928affa9d8d0162eff47ade) by [@javache](https://github.com/javache)) +- Remove deprecated DefaultNewArchitectureEntryPoint.load overload ([17824fd56c](https://github.com/facebook/react-native/commit/17824fd56c5745d80e7d80b171fe99c62686063e) by [@GijsWeterings](https://github.com/GijsWeterings)) +- Remove deprecated DefaultNewArchitectureEntryPoint.load overload ([6c8dfc8956](https://github.com/facebook/react-native/commit/6c8dfc89566d27c36f9ca3828bcf3a63dfcb6942) by [@cortinico](https://github.com/cortinico)) +- Delete UIManager.replaceExistingNonRootView ([77f3edd32c](https://github.com/facebook/react-native/commit/77f3edd32c66baa991c7d0e07142a3cef933b507) by [@RSNara](https://github.com/RSNara)) +- Delete UIManager.removeSubviewsFromContainerWithID ([f4e0061533](https://github.com/facebook/react-native/commit/f4e0061533d38d32358bf1d0c070ca20b1289207) by [@RSNara](https://github.com/RSNara)) +- Remove libevent dependency ([7f52791767](https://github.com/facebook/react-native/commit/7f527917671fa63afcf48801ec6c07867896678c) by [@cipolleschi](https://github.com/cipolleschi)) +- Remove JSCJavaScriptExecutor/Factory ([d7fd83ed5d](https://github.com/facebook/react-native/commit/d7fd83ed5d120ef12f236f028b18a0af9d319666) by [@Sunbreak](https://github.com/Sunbreak)) +- Deprecated internal ContentSizeChangeEvent ([2018a82a53](https://github.com/facebook/react-native/commit/2018a82a531c5d297b346a70f6cc629262f7108b) by [@javache](https://github.com/javache)) +- Remove ReactNative/Flipper Integration ([171a479150](https://github.com/facebook/react-native/commit/171a479150372677f069b55b8bebdf76df8b7f22) by [@cortinico](https://github.com/cortinico)) +- Deprecated ChoreographerCompat.FrameCallback, use Choreographer.FrameCallback ([248c324cca](https://github.com/facebook/react-native/commit/248c324ccae5bd40695dacf42c1048163fcc4f32) by [@javache](https://github.com/javache)) +- Remove unused translation files ([c54bfe4522](https://github.com/facebook/react-native/commit/c54bfe45226d3d5f4b8bf286c2ff776606c96287) by [@facebook-github-bot](https://github.com/facebook-github-bot)) + +#### iOS specific + +- Remove TARGET_OS_UIKITFORMAC macros ([1dd647484a](https://github.com/facebook/react-native/commit/1dd647484aff00a079923a5c0e763e3f54ccc210) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Remove deprecated RCTBundleURLProvider options ([016bb24eac](https://github.com/facebook/react-native/commit/016bb24eac5b361db283c24c9f9e11f2e36af2a8) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Remove libevent dependency ([23cf10428e](https://github.com/facebook/react-native/commit/23cf10428eb58cfcbf614b8b0728f2535f2d252f) by [@cipolleschi](https://github.com/cipolleschi)) +- Remove RCTGetMultiplierForContentSizeCategory ([6a2c245241](https://github.com/facebook/react-native/commit/6a2c245241f47700d3bdb76d2a4dace503ac689c) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Remove deprecated Snapshot tests ([0a48a72236](https://github.com/facebook/react-native/commit/0a48a72236806b0eae1f61dca5c03ba321732296) by [@Saadnajmi](https://github.com/Saadnajmi)) + +### Fixed + +- Fix JSExecutor build error on Windows ([1c4ed12370](https://github.com/facebook/react-native/commit/1c4ed12370101c12e9c5390733ec42469ca9cfd7)) +- Declare missing peer dependency `react` ([62c15bacaa](https://github.com/facebook/react-native/commit/62c15bacaac160d0858a76946217a2bfffb08b6d) by [@jbroma](https://github.com/jbroma)) +- Log Codegen supported platforms if any are available ([2ca7bec0c2](https://github.com/facebook/react-native/commit/2ca7bec0c2a7d821ceaaf39840a6cdc5eceb8678) by [@okwasniewski](https://github.com/okwasniewski)) +- Call onStartReached initially when list is small and `onEndReached` is called ([4dcc1d3efb](https://github.com/facebook/react-native/commit/4dcc1d3efbd86a4ac42c801af3303e4dae4c0418) by [@janicduplessis](https://github.com/janicduplessis)) +- Fix order of Metro hotkey console messages ([635732aa8f](https://github.com/facebook/react-native/commit/635732aa8fedc241d94eb1610dd58635f597b07d) by [@EdmondChuiHW](https://github.com/EdmondChuiHW)) +- Fix `react-native config` failing in pnpm setups ([8f4f09bf70](https://github.com/facebook/react-native/commit/8f4f09bf704fbe5851d72bc5152ada0ab8c733b2) by [@tido64](https://github.com/tido64)) +- Fix `react-native/community-cli-plugin` is unable to resolve out-of-tree platforms in monorepos ([e350859d72](https://github.com/facebook/react-native/commit/e350859d72b08ec1367dd98f89a313786171c8b9) by [@tido64](https://github.com/tido64)) +- Add type information for items of FlatList in `onViewableItemsChanged` signature ([35f5c3a204](https://github.com/facebook/react-native/commit/35f5c3a204375c2e716cdaa624f6c931ad62520e) by [@miallo](https://github.com/miallo)) +- Update typescript definition of `translateX` & `translateX` to be able to use percentage values ([b133bf6024](https://github.com/facebook/react-native/commit/b133bf60245f2b497fecf464c8a8f491294a750f) by [@retyui](https://github.com/retyui)) +- Fix UIManagerBinding's findNodeAtPoint ([62e5980954](https://github.com/facebook/react-native/commit/62e59809548034611fdce387e5b72d6bc6b9e6ea) by [@RSNara](https://github.com/RSNara)) +- Fix issue with debugger not working when device name contain two-byte UTF characters ([d16531e8a4](https://github.com/facebook/react-native/commit/d16531e8a4c20b848fd71dcca53d11aa8e1a6ac3) by [@kmagiera](https://github.com/kmagiera)) +- Inspected elements from React DevTools are now correctly highlighted on a relevant surfaces ([9d846f47c2](https://github.com/facebook/react-native/commit/9d846f47c28089b357e52e428173978df7ee34f1) by [@hoxyq](https://github.com/hoxyq)) +- Fix `compose-source-maps.js` failing if `-o` is not specified when it should output the composed source map ([ab192ced69](https://github.com/facebook/react-native/commit/ab192ced6938e647819eaaed983158a1feb3ff81) by [@tido64](https://github.com/tido64)) +- Fix remount of header and footer in `SectionList` while transiting between empty and filled state ([0c37f8c85c](https://github.com/facebook/react-native/commit/0c37f8c85cd0db1726fe8269aa0781d27c72c42b) by [@MateWW](https://github.com/MateWW)) +- Updated docs to match Android 6.0 (API 23) minimum requirement. ([192a88d522](https://github.com/facebook/react-native/commit/192a88d522befa3b5cc073d441210f8148e8ac69) by [@dcangulo](https://github.com/dcangulo)) +- Fix align-content of cross-stretched container ([b7eb0c85a2](https://github.com/facebook/react-native/commit/b7eb0c85a20ff01ae400df786fa238f362854cb6) by [@NickGerleman](https://github.com/NickGerleman)) +- Fix Yoga sizing and alignment issues with multi-line containers ([b221265f41](https://github.com/facebook/react-native/commit/b221265f4156992fea932ca74f09ac04662a4a37) by [@NickGerleman](https://github.com/NickGerleman)) +- Allow source map fetching in the inspector proxy from 127.0.0.1 ([46d304a101](https://github.com/facebook/react-native/commit/46d304a101f19f214607ac8fb93aacec4bfdbc6b)) +- Message ([da3ba74240](https://github.com/facebook/react-native/commit/da3ba742404cc71c46cf32d15c92bbd3dd62e89b) by [@Spice-Z](https://github.com/Spice-Z)) +- Lint source files, sort imports, remove unused ones ([7d1a98c43b](https://github.com/facebook/react-native/commit/7d1a98c43bc06af602f798c813cb56991447a26e) by [@okwasniewski](https://github.com/okwasniewski)) +- Allow Out Of Tree platforms to pass custom resolvers ([4ccd6e1242](https://github.com/facebook/react-native/commit/4ccd6e124278abf3c63765195715ee3ae39a769e) by [@okwasniewski](https://github.com/okwasniewski)) +- Update AcitvityIndicator spec default value ([03a840e0a9](https://github.com/facebook/react-native/commit/03a840e0a9ff6c0591557e1bac8e44dcdc72d3a9) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Update pkg/repo names in deprecation messages ([fd35c1db28](https://github.com/facebook/react-native/commit/fd35c1db2810c7c147c28ad067194744bf378069) by [@friederbluemle](https://github.com/friederbluemle)) +- "yogalayout.com" to "yogalayout.dev" ([99ebcfd3a9](https://github.com/facebook/react-native/commit/99ebcfd3a9c0907e51e8a22b8ff3169a3700747c) by [@NickGerleman](https://github.com/NickGerleman)) +- Fix `react-native/codegen` not being able to resolve dependencies in pnpm setups ([c58e19e89a](https://github.com/facebook/react-native/commit/c58e19e89aadcc01c2ac8ead876831ed8a2f6c5d) by [@tido64](https://github.com/tido64)) +- Flow syntax errors in Codegen specs are no longer ignored. ([a74765eb0a](https://github.com/facebook/react-native/commit/a74765eb0aaeba7154359ef77f31cc34ecc4b709) by [@motiz88](https://github.com/motiz88)) +- Add missing `ping()` method into `WebSocket` interface ([016b62c549](https://github.com/facebook/react-native/commit/016b62c54985e92ce43a97a07b7830b546688221) by [@alexzel](https://github.com/alexzel)) +- Add detection of logical assignment operators to `react-native-babel-preset` ([c90485eb10](https://github.com/facebook/react-native/commit/c90485eb10520f969c956b1381eba89e5cc9e072) by [@jonthysell](https://github.com/jonthysell)) +- Eslint config global vars redefine there is no message tip ([a2a219c27e](https://github.com/facebook/react-native/commit/a2a219c27ec607190b1c390190026d5166a51f1a) by [@rick-ast](https://github.com/rick-ast)) +- Fix windows 4018 and 4244 compiler warnings ([695a30d6b4](https://github.com/facebook/react-native/commit/695a30d6b4d03da02d02a5784f5f30ae6adb6e35) by [@TatianaKapos](https://github.com/TatianaKapos)) +- Rollout enableCloseVisibleGapBetweenPaths ([285629922c](https://github.com/facebook/react-native/commit/285629922cafd86914af9ed95ff1fbbd2c5a7c79) by [@javache](https://github.com/javache)) +- Move iOS/Android specific prop types appropriate types ([755a7dbf56](https://github.com/facebook/react-native/commit/755a7dbf5644d4f8ee08cba18bfa73a115c8d849) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Add `number | null` to `ViewProps['hitSlop']` TypeScript type ([bc16bc5b01](https://github.com/facebook/react-native/commit/bc16bc5b01c50fcfedbc3d32eed5591d9dd7cfce) by [@DimitarNestorov](https://github.com/DimitarNestorov)) +- JS Debugging: Fix inspector-proxy to allow for DevTools requests with query strings ([ab81c16b65](https://github.com/facebook/react-native/commit/ab81c16b6507000139d1af52c622e320629750ec)) +- Normalize-colors should not impose node >= 18 ([6f1b8edc7a](https://github.com/facebook/react-native/commit/6f1b8edc7a586a3e4c5408d14da1e13c1d88288a) by [@cortinico](https://github.com/cortinico)) +- Fixes type casting warnings that are treated as errors downstream in React Native Windows. ([570655d80f](https://github.com/facebook/react-native/commit/570655d80fcb1f213de07af05798897e5dbe42b9) by [@chiaramooney](https://github.com/chiaramooney)) +- - [GENERAL] [FIXED] Updated ESLint version to fix `originalKeywordKind` deprecation error ([5de0ddae30](https://github.com/facebook/react-native/commit/5de0ddae302ae1768d5ba40d09afc4ffce9ab5c1) by [@mrousavy](https://github.com/mrousavy)) +- JS debugging: prevent dev server crash when a large CDP payload is returned from the device ([d0f750e15d](https://github.com/facebook/react-native/commit/d0f750e15d1fb2e75e1263c66ac5f5be31aa0dc5) by [@motiz88](https://github.com/motiz88)) +- Fix new arch example not render in RNTester ([48dcfa1718](https://github.com/facebook/react-native/commit/48dcfa1718d088c44f925814de59ca6ad35d44f2)) +- JS debugging: prevent dev server crash when a large CDP payload is returned from the device ([2000acc6c6](https://github.com/facebook/react-native/commit/2000acc6c6cbfd3942062b33c8285e155d404d4a) by [@motiz88](https://github.com/motiz88)) +- Update stale ReactAndroid.api values after CI breakage ([a5fbe28c29](https://github.com/facebook/react-native/commit/a5fbe28c2902f0a312175ce366ee204e185efc52) by [@GijsWeterings](https://github.com/GijsWeterings)) +- Fix issue where we were not centering absolute nodes correctly when justifying ([983e784a3e](https://github.com/facebook/react-native/commit/983e784a3e7f8c2529a17dcd5850e79e17d00da3) by [@joevilches](https://github.com/joevilches)) +- Fix bug where we used border box for size of containing block in a certain case ([5b05c79d8c](https://github.com/facebook/react-native/commit/5b05c79d8cd32c25c53b195999b3866dac5a5600) by [@joevilches](https://github.com/joevilches)) +- Make runtime reference thread safe on tickleJs call ([067c989b48](https://github.com/facebook/react-native/commit/067c989b4841d55c521d7b21534e9609d9d2a0a7) by [@blakef](https://github.com/blakef)) +- Fix issue where paddingStart and paddingEnd were swapped with row reverse ([2bf1a8f4e0](https://github.com/facebook/react-native/commit/2bf1a8f4e05313287e1d81a460138f4875282e9f) by [@joevilches](https://github.com/joevilches)) +- Fix issue where borderStart and borderEnd were swapped with row reverse ([24169e28cf](https://github.com/facebook/react-native/commit/24169e28cf0477bb55be92740bb2c402d8c3eff5) by [@joevilches](https://github.com/joevilches)) +- Fix issue where marginStart and marginEnd were not working with rowReverse flex direction ([53279ba426](https://github.com/facebook/react-native/commit/53279ba4267c573d0c471380265a8e4e8fbd6f86) by [@joevilches](https://github.com/joevilches)) +- Fix style resolution functions returning FloatOptional ([72d0fed272](https://github.com/facebook/react-native/commit/72d0fed272a84f34294f59d86c79223cea880e6d) by [@NickGerleman](https://github.com/NickGerleman)) +- Fix handling of negative flex gap ([aa65e92121](https://github.com/facebook/react-native/commit/aa65e92121e86fbe978e10db80e04fb4999479ef) by [@NickGerleman](https://github.com/NickGerleman)) +- Fix ReactInstanceManager to initialize the UIManager ([0f239d3301](https://github.com/facebook/react-native/commit/0f239d3301cce409476370294f782e76cc59a1ec)) +- Fix ReactInstanceManager to add getJSIModule() as an alternate path ([e8323781fa](https://github.com/facebook/react-native/commit/e8323781fac8b19bb8a4faa53461c33ff201817b)) +- Fixing Bridgeless Exception caused by the UIManager changes ([5e406ccea0](https://github.com/facebook/react-native/commit/5e406ccea023e87a35d939b0f865aec760703035)) +- Fix warm start logging for ReactMarker ([44109dc2c0](https://github.com/facebook/react-native/commit/44109dc2c01a76baf37b836a378e6a28d96ea66c)) + +#### Android specific + +- Disable the "Open Debugger" item from dev menu if the bundler is disconnected ([7afc8b8623](https://github.com/facebook/react-native/commit/7afc8b8623cc499c3054b9fb5b08cc2b65edb19c) by [@EdmondChuiHW](https://github.com/EdmondChuiHW)) +- Fix linking of local app modules turbomodules ([eb619468c1](https://github.com/facebook/react-native/commit/eb619468c1b61b7261846e62e33f94d89e121455) by [@cortinico](https://github.com/cortinico)) +- Fix Reload behavior being different on Bridgeless ([85257a993f](https://github.com/facebook/react-native/commit/85257a993fce5e37e19f03c563bd134982302f51) by [@cortinico](https://github.com/cortinico)) +- Fixes Android compile failed. ([aefca27c67](https://github.com/facebook/react-native/commit/aefca27c67df4ab19733e33e26f5457e297e0b5f) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Fix delivery of events during initial rendering in new architecture ([7b36233ae1](https://github.com/facebook/react-native/commit/7b36233ae19ba7c1fbedc42c15103ea1cfa55ee3) by [@mdvacca](https://github.com/mdvacca)) +- Restore missing call to `convertRawPropAliases` ([5e37c1f219](https://github.com/facebook/react-native/commit/5e37c1f2191f1c4886f55a63e931979847cf49a4) by [@NickGerleman](https://github.com/NickGerleman)) +- [Android][Fixed] - Fix incorrect measurement of TextInput when new architecture is enabled ([dc2ce9e66e](https://github.com/facebook/react-native/commit/dc2ce9e66e337ef90a179853467dbb8b09b9d24c) by [@mdvacca](https://github.com/mdvacca)) +- Make Android respect metro location from shared preferences for the debugger workflow ([0ea16fd3f7](https://github.com/facebook/react-native/commit/0ea16fd3f748dd239cac6f19f80b007cb2b008f9) by [@kmagiera](https://github.com/kmagiera)) +- Assert `DefaultComponentsRegistry::registerComponentDescriptorsFromEntryPoint` is set ([8474e239df](https://github.com/facebook/react-native/commit/8474e239df9de41da2b7a12b15d38871bebdd97f) by [@tido64](https://github.com/tido64)) +- Fixed unexpected resizing of ReactRootView for dev bundles in brownfield apps ([5d68c908f1](https://github.com/facebook/react-native/commit/5d68c908f1de52cfe5d6f8b50774ba44c3dcc9be) by [@hoxyq](https://github.com/hoxyq)) +- Fix: prevent scroll event in nested scroll when scrollEnabled={false} ([c7873b77b8](https://github.com/facebook/react-native/commit/c7873b77b8149966e9171783e42cfde6971fbd41) by [@Icehunter](https://github.com/Icehunter)) +- Update getDefaultJSExecutorFactory to load Hermes first and fallback to JSC ([70a757fc1e](https://github.com/facebook/react-native/commit/70a757fc1ede08fcb9d5014f3b05c94e5badaea7) by [@cortinico](https://github.com/cortinico)) +- Update profiler button to use "Toggle" string. ([8bcaed90c1](https://github.com/facebook/react-native/commit/8bcaed90c11e292da199545f701fd44ecb07ec95) by [@szymonrybczak](https://github.com/szymonrybczak)) +- Typos in `ReactCompoundViewGroup` comments ([385473522c](https://github.com/facebook/react-native/commit/385473522cbc525aad08500f5a752dea734c14c3) by [@kkafar](https://github.com/kkafar)) +- Fix AndroidTextInputProps Detection of Padding ([4016bfbc37](https://github.com/facebook/react-native/commit/4016bfbc377215d2929de732f682bc9d1c823f39) by [@NickGerleman](https://github.com/NickGerleman)) +- Fix type in BlobCollector.h/cpp ([c267a0679d](https://github.com/facebook/react-native/commit/c267a0679d21908e6e8026ca5ee542a9b571fb8b) by [@Sunbreak](https://github.com/Sunbreak)) +- Fixed an issue where the status bar colors would not match when opening modals ([e8d622e9d1](https://github.com/facebook/react-native/commit/e8d622e9d118a7fcf71a14d665b2d2bf33dd0b1f)) +- Bump Fresco to 3.1.3 ([dca81e6172](https://github.com/facebook/react-native/commit/dca81e6172aadd62a8cb7c2fdb9d08d853119215) by [@cortinico](https://github.com/cortinico)) +- Fix crash with `java.lang.NoSuchMethodError` for Bridgeless ([b22f566104](https://github.com/facebook/react-native/commit/b22f566104d2d5d12867478a96ff5a0aa4911336) by [@cortinico](https://github.com/cortinico)) +- B1fccb05ccb306005dc7616a4eaaa182b0b1deaf bumped fresco version to 3.1.0. ([fbc28fa73d](https://github.com/facebook/react-native/commit/fbc28fa73d075b49e263f1dd12f9a858bc8f97ef) by [@lafest](https://github.com/lafest)) +- Ensure that `configureJavaToolChains` is only executed once during configuration ([c7d969f31b](https://github.com/facebook/react-native/commit/c7d969f31b1d584f593dfcbf119765b5efa4bc95) by [@UNIDY2002](https://github.com/UNIDY2002)) +- Fix the crash in ReactViewGroup of https://github.com/facebook/react-native/issues/30785 ([b9418315e2](https://github.com/facebook/react-native/commit/b9418315e274f8693d1f7cd3f41529ba6c0436c9)) +- Handle Crash for onRequestPermissionsResult ([925209932a](https://github.com/facebook/react-native/commit/925209932aa20f6c70e9642c5ab8dec8ac83a1cd) by [@chakrihacker](https://github.com/chakrihacker)) +- Fix instacrash on bridgeless due to calling showMessage on null instance ([2f1ecea1cb](https://github.com/facebook/react-native/commit/2f1ecea1cb70edb878bb6c984da236aec49d0ba1) by [@cortinico](https://github.com/cortinico)) +- Allow non-ascii header values on Android and add utf-8 filename fallback in FormData ([7c7e9e6571](https://github.com/facebook/react-native/commit/7c7e9e6571c1f702213e9ffbb40921cd5a1a786b) by [@robertying](https://github.com/robertying)) + +#### iOS specific + +- Resolving case sensitivity issue in header file import ([d655fee28b](https://github.com/facebook/react-native/commit/d655fee28be56ba42ae151daba4db84617683f27) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Pass the right flags to libraries ([5164e83c3b](https://github.com/facebook/react-native/commit/5164e83c3b24126c4cfcf916e88e737d26f8b76e) by [@cipolleschi](https://github.com/cipolleschi)) +- Make sure that `addUIBlock` provides a Dictionary-look-alike object that returns the right views when queried. ([f61f87c5ef](https://github.com/facebook/react-native/commit/f61f87c5ef33cc8098f937aef4a9bd0634b16159) by [@cipolleschi](https://github.com/cipolleschi)) +- Perf Monitor option not showing in Bridgeless ([209140046b](https://github.com/facebook/react-native/commit/209140046b451170315f9f30a19644a04ab80207) by [@okwasniewski](https://github.com/okwasniewski)) +- Make sure to forward touches to the wrapped component in the InteropLayer. ([ab5e2e8099](https://github.com/facebook/react-native/commit/ab5e2e8099870a313ab2d24344f336604273f573) by [@cipolleschi](https://github.com/cipolleschi)) +- Generate the RCTModulesConformingToProtocolsProvider only once in user space ([a3998f8d15](https://github.com/facebook/react-native/commit/a3998f8d15c6b0724039675ba4ead177ae9d7319) by [@cipolleschi](https://github.com/cipolleschi)) +- Make sure that Modal is dismissed correctly in Paper ([4236538cbd](https://github.com/facebook/react-native/commit/4236538cbd36d5bc607b3108df45fc51fc8335db) by [@cipolleschi](https://github.com/cipolleschi)) +- Fixed support for event name override in component specs. ([6974697b04](https://github.com/facebook/react-native/commit/6974697b049eff0038a17e3ebf962ec7451a5aa4) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Make [RCTBridge currentBridge] work in bridgeless mode ([f6f461593b](https://github.com/facebook/react-native/commit/f6f461593bf929aa5d3798fa277f8324ece36f0e) by [@cipolleschi](https://github.com/cipolleschi)) +- Initialize the A11yManager in the main queue and when we need it. ([dc38988bcc](https://github.com/facebook/react-native/commit/dc38988bcc160e387fe1d821f80eb42de47d11c5) by [@cipolleschi](https://github.com/cipolleschi)) +- Make font resolution work when using specific font name on the new architecture ([61774088d7](https://github.com/facebook/react-native/commit/61774088d79ac3ab730fa55d175d681b10ae50f3) by [@j-piasecki](https://github.com/j-piasecki)) +- Disable the "Open Debugger" item from dev menu if packager is disconnected ([bc3fe0d76d](https://github.com/facebook/react-native/commit/bc3fe0d76d9ca7613115d5f10b85ba7608561c02) by [@EdmondChuiHW](https://github.com/EdmondChuiHW)) +- Don't add compiler conditionals when no platforms are specified ([1ce7bfd8c9](https://github.com/facebook/react-native/commit/1ce7bfd8c97998be678884986cf774178bef1185) by [@okwasniewski](https://github.com/okwasniewski)) +- Fix TextInput vertical alignment issue when using lineHeight prop on iOS without changing Text baseline (Paper - old arch) ([349d5502d0](https://github.com/facebook/react-native/commit/349d5502d0f0a7e8f66bedb3b8416dca37a41b76) by [@fabOnReact](https://github.com/fabOnReact)) +- Align the the bundleURL API from `RCTAppDelegate` to template's `AppDelegate` ([ebb55a780a](https://github.com/facebook/react-native/commit/ebb55a780a31ee985f48536b3eb7794cdff03304) by [@cipolleschi](https://github.com/cipolleschi)) +- Bring back support for defining external libraries in react-native.config.js ([c6c23042a4](https://github.com/facebook/react-native/commit/c6c23042a4cdad0a44eb970dd40d9536e725767a) by [@dmytrorykun](https://github.com/dmytrorykun)) +- Immediately set props of Components that goes through the interop layer ([68ae8cd5e9](https://github.com/facebook/react-native/commit/68ae8cd5e982db7778a8f9b3aa68494912d75d91) by [@cipolleschi](https://github.com/cipolleschi)) +- [iOS] Fixes the root view's background color in bridgeless mode ([0bbc311c8a](https://github.com/facebook/react-native/commit/0bbc311c8ac45577c5ba5a58443380621e807faf) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Fix retrieving current appearance in multi-window apps ([d00d35e872](https://github.com/facebook/react-native/commit/d00d35e8723293b0c1e098fa2e02756884a0f7f9) by [@okwasniewski](https://github.com/okwasniewski)) +- Refactored RCT_handleKeyCommand to avoid concurrency issues ([8d710bfaca](https://github.com/facebook/react-native/commit/8d710bfaca6b57291bf953bda848f3cf64ae2818) by [@cipolleschi](https://github.com/cipolleschi)) +- Fixed potential threading issues accessing UIKit from background in RCTAlertManager ([8c4979e7a1](https://github.com/facebook/react-native/commit/8c4979e7a1ecb140b0b068d686b1ec6aab452121) by [@fkgozali](https://github.com/fkgozali)) +- Fixed `DoubleConversion` build error from Swift integration ([631b6a12c5](https://github.com/facebook/react-native/commit/631b6a12c5968510b435080c87f06d03069615cb) by [@Kudo](https://github.com/Kudo)) +- IOS Add React-debug to ReactCommon.podspec ([ea0e826c28](https://github.com/facebook/react-native/commit/ea0e826c2804f0c775030e76776fb3ac22978fda) by [@christophpurrer](https://github.com/christophpurrer)) +- Remove an early return to suppress a deprecated API warning for `UIMenuController` ([6801fc3f9b](https://github.com/facebook/react-native/commit/6801fc3f9bf172f5ca929127576558be04e3f99c) by [@Saadnajmi](https://github.com/Saadnajmi)) +- Bring the old RCT_NEW_ARCH_ENABLED semantic back for compatibility ([3690e4413b](https://github.com/facebook/react-native/commit/3690e4413be0459b2e5fc42ca266c1a03f3c04fa) by [@cipolleschi](https://github.com/cipolleschi)) +- Fixed archiving for macos catalyst on react-native 0.73.1 in xcode ([aa2d613cfa](https://github.com/facebook/react-native/commit/aa2d613cfa760b4570ae659c5efa4620308807ce) by [@kesha-antonov](https://github.com/kesha-antonov)) +- Fix RCTAppSetupPrepareApp.h import error from Objective-C *.m files ([de0c43ead4](https://github.com/facebook/react-native/commit/de0c43ead4d1503e708d2dafa3f5b7fc550fc01a) by [@Kudo](https://github.com/Kudo)) +- Fixes `with-environment.sh` script for the case when Node can't be found prior to loading `.xcode.env` ([c684f9fc62](https://github.com/facebook/react-native/commit/c684f9fc62e865a5ecbd8ade0f5628f016eebcb2) by [@birdofpreyru](https://github.com/birdofpreyru)) +- Further cleaned up RCT_USE_HERMES ([d50c9068a9](https://github.com/facebook/react-native/commit/d50c9068a927ec1fa0c574a4483dc7c03dca75f5) by [@fkgozali](https://github.com/fkgozali)) +- Fix support for --sourcemap-output path containing spaces ([e25a9b4c5d](https://github.com/facebook/react-native/commit/e25a9b4c5d0e4c32dbc1eca071911e34faa177ce) by [@JorenVos](https://github.com/JorenVos)) +- Move old props and prop diffing to the interop layer adapter ([3b80531f32](https://github.com/facebook/react-native/commit/3b80531f3247bee83a2e63a1ee31ca56ab15d024) by [@cipolleschi](https://github.com/cipolleschi)) +- Optimise RCTKeyWindow() calls in RCTForceTouchAvailable method ([90fb73e83c](https://github.com/facebook/react-native/commit/90fb73e83caf087659b6b3173edd457b4f1d1987) by [@okwasniewski](https://github.com/okwasniewski)) +- Fixed strict prototype warning when using the RCT_EXTERN_REMAP_MODULE macro. ([746ad378c7](https://github.com/facebook/react-native/commit/746ad378c7efe3ee2f4926ab30e5401407f8b3ba) by [@dehlen](https://github.com/dehlen)) +- Add safe guard when receive network response data too long ([3c4517ffb6](https://github.com/facebook/react-native/commit/3c4517ffb63d6adfdac5f9f7d51d834a22ac2cd9) by [@zhongwuzw](https://github.com/zhongwuzw)) +- The wrong height result of onContentSizeChange callback ([5217cc972a](https://github.com/facebook/react-native/commit/5217cc972ae8b95c12f99b93619bd4399382e7e6) by [@zyestin](https://github.com/zyestin)) +- Fix cleanAssetCatalog error ([d5114a4b9f](https://github.com/facebook/react-native/commit/d5114a4b9f079bc0d643f3d6f303310bd78074eb) by [@janicduplessis](https://github.com/janicduplessis)) +- Fixes ScrollView contentInsetAdjustmentBehavior assignment ([86df742e73](https://github.com/facebook/react-native/commit/86df742e73ecacbf29921ab6f74333c36a7dca26) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Network invalidate handlers to cleanup in turbo module mode ([44d6e4310c](https://github.com/facebook/react-native/commit/44d6e4310cc9ad0d711d05e8dd5ee5220738e5b5) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Move ActionSheet UI operation to main thread ([aa9e824a75](https://github.com/facebook/react-native/commit/aa9e824a756a86f61873c270b17603468a2166ec) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Move UIRequiredDeviceCapabilities for RNTester to arm64 ([c7bd397dac](https://github.com/facebook/react-native/commit/c7bd397dacc1a809572142bb7f80adf76d6002fe) by [@fkgozali](https://github.com/fkgozali)) +- Remove duplicated category NSTextStorage+FontScaling ([6eef3661bf](https://github.com/facebook/react-native/commit/6eef3661bf22a2b0f9b4e293a501fb095004a7d2) by [@zhongwuzw](https://github.com/zhongwuzw)) +- `setState` is not working for nested inline views in text ([9b33e752c7](https://github.com/facebook/react-native/commit/9b33e752c7c414c9c04b20888a2e1e9d9f8aa8a3) by [@ehsemloh](https://github.com/ehsemloh)) +- Unbreak Cocoapods build ([05d92bf2a5](https://github.com/facebook/react-native/commit/05d92bf2a5ed54c3e7a52b78a3edd699471c710f) by [@hieu9102002](https://github.com/hieu9102002)) +- `setState` is not working properly for text inline image ([36ef6460f0](https://github.com/facebook/react-native/commit/36ef6460f04db323d8bbfc8be5e5dc26691a35ae) by [@ehsemloh](https://github.com/ehsemloh)) +- Fix running timers when the proximity sensor detects close ([79eac9666d](https://github.com/facebook/react-native/commit/79eac9666d9f0e3a3b076f64be0e6c45f035cb84) by [@saghul](https://github.com/saghul)) +- Fixes Dev menu pop up multiple times when Tap command `D` continuously ([a257e9f5f0](https://github.com/facebook/react-native/commit/a257e9f5f0cb871ead636e4dee0ce1271bb90df8) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Fix module create dead-lock when start-up ([a4a8695cec](https://github.com/facebook/react-native/commit/a4a8695cec640e5cf12be36a0c871115fbce9c87) by [@zhongwuzw](https://github.com/zhongwuzw)) +- Adjust RCTRedBox to work for iPad and support orientation changes ([e2eb26c951](https://github.com/facebook/react-native/commit/e2eb26c951c3d2a0a4721428d00ffc02b501ecfa) by [@okwasniewski](https://github.com/okwasniewski)) +- Fix autoscrollToTopThreshold on iOS old arch ([9666814750](https://github.com/facebook/react-native/commit/9666814750198574170a26e21a47b028f8060ffe) by [@janicduplessis](https://github.com/janicduplessis)) +- Fix iOS Paper Scroll Event RTL check ([c40fc313ca](https://github.com/facebook/react-native/commit/c40fc313ca9dd66f9949c44f494d50951d96fe9d) by [@NickGerleman](https://github.com/NickGerleman)) +- View flips horizontally in paper arch on RTL ([1d74b38634](https://github.com/facebook/react-native/commit/1d74b38634a27bce65eb6ea11111dac6653bd905) by [@intergalacticspacehighway](https://github.com/intergalacticspacehighway)) +- Fixed narrowing conversion compilation error. ([ed9931f456](https://github.com/facebook/react-native/commit/ed9931f456ea9b7b006d2741223c882186afe368)) +- Fix grammar in Xcode 15 helper method name ([fa87eaaebf](https://github.com/facebook/react-native/commit/fa87eaaebf4103d365adf44d1d14ed6117cb37cb) by [@mikehardy](https://github.com/mikehardy)) +- Prevent unwanted border animation ([5fbdc994f9](https://github.com/facebook/react-native/commit/5fbdc994f945ee8d834632649e3b82451660e8fe) by [@sammy-SC](https://github.com/sammy-SC)) + +### Security + +#### iOS specific + +- Bump activesupport to minimum 6.1.7.5 CVE-2023-38037. ([07a159f279](https://github.com/facebook/react-native/commit/07a159f279cdcbed29c9c437dec1c0b8ac2d852f) by [@lunaleaps](https://github.com/lunaleaps)) + +## v0.73.6 + +### Breaking + +#### iOS specific + +- Rename `BUILD_FROM_SOURCE` to `RCT_BUILD_HERMES_FROM_SOURCE` ([51b80477c7](https://github.com/facebook/react-native/commit/51b80477c7836058fb29ef92c1a1908e3c8dba58) by [@cipolleschi](https://github.com/cipolleschi)) + +### Fixed + +- Fix component stacks for tsx, ts, and jsx files ([28f604a97d](https://github.com/facebook/react-native/commit/28f604a97dc57afa631a24052ae6660c13c2c761) by [@lunaleaps](https://github.com/lunaleaps)) + +#### iOS specific + +- Prevent unwanted border animation([d979491](https://github.com/facebook/react-native/commit/d9794916b0549330513fe530abf090fa48b8a776) by [@sammy-SC](https://github.com/sammy-SC)) +- Fix flipper for Xcode 15.3 ([9d22a7fd0e](https://github.com/facebook/react-native/commit/9d22a7fd0e82d6c2660217c1fb3c004ab30d6844) by [@cipolleschi](https://github.com/cipolleschi)) + +## v0.73.5 + +### Security + +- Update CLI to 12.3.6 ([ffcd8f5249](https://github.com/facebook/react-native/commit/ffcd8f524903d5d6e92e864472aaefd52dea77cf) by [@szymonrybczak](https://github.com/szymonrybczak)) + +### Changed + +- Hermes bump ([3bdd54a51c](https://github.com/facebook/react-native/commit/3bdd54a51ceea30cbbd0d1c45e9c391a80371dd2) by [@lunaleaps](https://github.com/lunaleaps)) + +### Fixed + +- Fix: fix codegen not finding all third-party libraries ([67e2bb455f](https://github.com/facebook/react-native/commit/67e2bb455fd39f00fbf2b4d4f2f019327929efa6) by [@tido64](https://github.com/tido64)) +- Fix compiler flags passed to libraries ([929df582c8](https://github.com/facebook/react-native/commit/929df582c885ad60bd34e52ced481f8e9d5666d9) by [@cipolleschi](https://github.com/cipolleschi)) + ## v0.73.4 ### Fixed @@ -49,6 +644,41 @@ - Fix race condition between A11yManager and UIManager ([f39f34ed82](https://github.com/facebook/react-native/commit/f39f34ed82997d0595522a285c3cb8693594e718) by [@cipolleschi](https://github.com/cipolleschi)) - Fix symbol not found _jump_fcontext with use_frameworks ([a2771ce58a](https://github.com/facebook/react-native/commit/a2771ce58ac221d1ac0de265c1ce571212fbcf83) by [@cipolleschi](https://github.com/cipolleschi)) +## v0.72.12 + +### Changed + +- Rename BUILD_FROM_SOURCE to RCT_BUILD_HERMES_FROM_SOURCE ([a215805eb7](https://github.com/facebook/react-native/commit/a215805eb73f687116af4aa74461ff4e17b05f42) by [@cipolleschi](https://github.com/cipolleschi)) + +#### iOS specific + +- [0.72] Fix flipper for Xcode 15.3 ([a316e0154e](https://github.com/facebook/react-native/commit/a316e0154ee8d1dd809be47694abb62d245bff0b) by [@cipolleschi](https://github.com/cipolleschi)) + +### Fixed + +- Fix component stacks for tsx, ts, and jsx files ([dd311c9782](https://github.com/facebook/react-native/commit/dd311c9782c9f4d0f9d98423de2ae71227a24a7d) by [@rickhanlonii](https://github.com/rickhanlonii)) + +- Fix flags for new arch ([0724c2769a](https://github.com/facebook/react-native/commit/0724c2769a3dea8f7886c8c541ffb49ae5c045dc) by [@cipolleschi](https://github.com/cipolleschi)) + +## v0.72.11 + +### Changed + +- Upgrade CLI to 11.4.1 ([c57a29a08c](https://github.com/facebook/react-native/commit/c57a29a08c086728ea3bbb6b077c92fae6792d11) by [@szymonrybczak](https://github.com/szymonrybczak)) +- Update Metro to ^0.76.9, CLI to ^11.4.0 ([ddff36f770](https://github.com/facebook/react-native/commit/ddff36f7705f1b5b2e27bfb2ee62f6726dfdd7bd) by [@robhogan](https://github.com/robhogan)) + +#### iOS specific + +- Improve Swift support for 3rd party libs ([6939021518](https://github.com/facebook/react-native/commit/693902151899c85ff00418d75df4377a1096efee) by [@cipolleschi](https://github.com/cipolleschi)) + +### Fixed + +- Fix overriding EXCLUDED_ARCHS when installing Hermes on RN v0.72 ([a4282a91c3](https://github.com/facebook/react-native/commit/a4282a91c32f947adfb4f210e296e8dfeefdae34) by [@ken0nek](https://github.com/ken0nek)) + +#### iOS specific + +- Don't allow cocoapods 1.15. ([08fd9170fc](https://github.com/facebook/react-native/commit/08fd9170fcdc7042fdcfe5f54eec71ed245d9795) by [@blakef](https://github.com/blakef)) + ## v0.72.10 ### Added @@ -991,6 +1621,12 @@ This file contains all changelogs for latest releases, from 0.70.0 onward. Pleas - Enable Address and Undefined Behavior Sanitizers on RNTester ([65e61f3c88](https://github.com/facebook/react-native/commit/65e61f3c88388d4a2ed88bcc9a2cb5ba63fd8afa) by [@Saadnajmi](https://github.com/Saadnajmi)) +## v0.71.17 + +### Security + +- Update CLI to 10.2.7 ([28998075d9](https://github.com/facebook/react-native/commit/28998075d98754bc72a65887346f027a9657b6a3) by [@szymonrybczak](https://github.com/szymonrybczak)) + ## v0.71.16 ### Changed diff --git a/flow-typed/npm/shelljs_v0.x.x.js b/flow-typed/npm/shelljs_v0.x.x.js index b1bff7b8402d51..9e1ca8fe805515 100644 --- a/flow-typed/npm/shelljs_v0.x.x.js +++ b/flow-typed/npm/shelljs_v0.x.x.js @@ -136,7 +136,6 @@ declare interface $npm$shelljs$Result { ((rest: void) => $npm$shelljs$String); } -// $FlowFixMe[unsupported-syntax] declare module 'shelljs' { declare export type ShellArray = $npm$shelljs$Array; declare export type ShellAsync = $npm$shelljs$Async; diff --git a/package.json b/package.json index ca7b08196d9d51..761a16cc7c2fce 100644 --- a/package.json +++ b/package.json @@ -59,11 +59,11 @@ "@definitelytyped/dtslint": "^0.0.127", "@jest/create-cache-key-function": "^29.6.3", "@pkgjs/parseargs": "^0.11.0", - "@react-native/metro-babel-transformer": "0.74.0", - "@react-native/metro-config": "0.74.0", + "@react-native/metro-babel-transformer": "0.75.0-main", + "@react-native/metro-config": "0.75.0-main", "@tsconfig/node18": "1.0.1", "@types/react": "^18.0.18", - "@typescript-eslint/parser": "^6.7.4", + "@typescript-eslint/parser": "^7.1.1", "ansi-styles": "^4.2.1", "async": "^3.2.2", "babel-plugin-minify-dead-code-elimination": "^0.5.2", @@ -73,12 +73,12 @@ "chalk": "^4.0.0", "clang-format": "^1.8.0", "connect": "^3.6.5", - "eslint": "^8.23.1", + "eslint": "^8.57.0", "eslint-config-prettier": "^8.5.0", "eslint-plugin-babel": "^5.3.1", "eslint-plugin-eslint-comments": "^3.2.0", "eslint-plugin-ft-flow": "^2.0.1", - "eslint-plugin-jest": "^26.5.3", + "eslint-plugin-jest": "^27.9.0", "eslint-plugin-jsx-a11y": "^6.6.0", "eslint-plugin-lint": "^1.0.0", "eslint-plugin-prettier": "^4.2.1", @@ -87,11 +87,11 @@ "eslint-plugin-react-native": "^4.0.0", "eslint-plugin-redundant-undefined": "^0.4.0", "eslint-plugin-relay": "^1.8.3", - "flow-api-translator": "0.19.1", - "flow-bin": "^0.228.0", + "flow-api-translator": "0.20.1", + "flow-bin": "^0.231.0", "glob": "^7.1.1", - "hermes-eslint": "0.19.1", - "hermes-transform": "0.19.1", + "hermes-eslint": "0.20.1", + "hermes-transform": "0.20.1", "inquirer": "^7.1.0", "jest": "^29.6.3", "jest-junit": "^10.0.0", @@ -104,7 +104,7 @@ "node-fetch": "^2.2.0", "nullthrows": "^1.1.1", "prettier": "2.8.8", - "prettier-plugin-hermes-parser": "0.19.1", + "prettier-plugin-hermes-parser": "0.20.1", "react": "18.2.0", "react-test-renderer": "18.2.0", "rimraf": "^3.0.2", diff --git a/packages/assets/package.json b/packages/assets/package.json index 616930179d1867..8c19ed7ebe9585 100644 --- a/packages/assets/package.json +++ b/packages/assets/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/assets-registry", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Asset support code for React Native.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/assets" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/assets#readme", diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json index ca3392302e261e..e93a609f60afba 100644 --- a/packages/babel-plugin-codegen/package.json +++ b/packages/babel-plugin-codegen/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/babel-plugin-codegen", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Babel plugin to generate native module and view manager code for React Native.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/babel-plugin-codegen" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/babel-plugin-codegen#readme", @@ -25,7 +25,7 @@ "index.js" ], "dependencies": { - "@react-native/codegen": "0.74.0" + "@react-native/codegen": "0.75.0-main" }, "devDependencies": { "@babel/core": "^7.20.0" diff --git a/packages/community-cli-plugin/README.md b/packages/community-cli-plugin/README.md index aebbf39d106fcc..12fcffb9c026ff 100644 --- a/packages/community-cli-plugin/README.md +++ b/packages/community-cli-plugin/README.md @@ -69,24 +69,6 @@ npx react-native bundle --entry-file [options] | `--read-global-cache` | Attempt to fetch transformed JS code from the global cache, if configured. Defaults to `false`. | | `--config ` | Path to the CLI configuration file. | -### `ram-bundle` - -Build the [RAM bundle](https://reactnative.dev/docs/ram-bundles-inline-requires) for the provided JavaScript entry file. - -#### Usage - -```sh -npx react-native ram-bundle --entry-file [options] -``` - -#### Options - -Accepts all options supported by [`bundle`](#bundle) and the following: - -| Option | Description | -| - | - | -| `--indexed-ram-bundle` | Force the "Indexed RAM" bundle file format, even when building for Android. | - ## Contributing Changes to this package can be made locally and tested against the `rn-tester` app, per the [Contributing guide](https://reactnative.dev/contributing/overview#contributing-code). During development, this package is automatically run from source with no build step. diff --git a/packages/community-cli-plugin/package.json b/packages/community-cli-plugin/package.json index 5d2f05cb845fb7..190a91b4c09759 100644 --- a/packages/community-cli-plugin/package.json +++ b/packages/community-cli-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/community-cli-plugin", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Core CLI commands for React Native", "keywords": [ "react-native", @@ -10,7 +10,7 @@ "bugs": "https://github.com/facebook/react-native/issues", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/community-cli-plugin" }, "license": "MIT", @@ -22,10 +22,10 @@ "dist" ], "dependencies": { - "@react-native-community/cli-server-api": "13.6.0", - "@react-native-community/cli-tools": "13.6.0", - "@react-native/dev-middleware": "0.74.0", - "@react-native/metro-babel-transformer": "0.74.0", + "@react-native-community/cli-server-api": "14.0.0-alpha.0", + "@react-native-community/cli-tools": "14.0.0-alpha.0", + "@react-native/dev-middleware": "0.75.0-main", + "@react-native/metro-babel-transformer": "0.75.0-main", "chalk": "^4.0.0", "execa": "^5.1.1", "metro": "^0.80.3", diff --git a/packages/community-cli-plugin/src/commands/ram-bundle/index.js b/packages/community-cli-plugin/src/commands/ram-bundle/index.js deleted file mode 100644 index eeed0819cfecdc..00000000000000 --- a/packages/community-cli-plugin/src/commands/ram-bundle/index.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -import type {BundleCommandArgs} from '../bundle'; -import type {Command, Config} from '@react-native-community/cli-types'; - -import bundleCommand from '../bundle'; -import buildBundle from '../bundle/buildBundle'; -import metroRamBundle from 'metro/src/shared/output/RamBundle'; - -const ramBundleCommand: Command = { - name: 'ram-bundle', - description: - 'Build the RAM bundle for the provided JavaScript entry file. See https://reactnative.dev/docs/ram-bundles-inline-requires.', - func: (argv: Array, config: Config, args: BundleCommandArgs) => { - return buildBundle(argv, config, args, metroRamBundle); - }, - options: [ - // $FlowFixMe[incompatible-type] options is nonnull - ...bundleCommand.options, - { - name: '--indexed-ram-bundle', - description: - 'Force the "Indexed RAM" bundle file format, even when building for android', - default: false, - }, - ], -}; - -export default ramBundleCommand; diff --git a/packages/community-cli-plugin/src/index.flow.js b/packages/community-cli-plugin/src/index.flow.js index 80adc7e51beb40..e9dbc7adc21380 100644 --- a/packages/community-cli-plugin/src/index.flow.js +++ b/packages/community-cli-plugin/src/index.flow.js @@ -10,7 +10,6 @@ */ export {default as bundleCommand} from './commands/bundle'; -export {default as ramBundleCommand} from './commands/ram-bundle'; export {default as startCommand} from './commands/start'; export {unstable_buildBundleWithConfig} from './commands/bundle/buildBundle'; diff --git a/packages/core-cli-utils/.gitignore b/packages/core-cli-utils/.gitignore new file mode 100644 index 00000000000000..849ddff3b7ec91 --- /dev/null +++ b/packages/core-cli-utils/.gitignore @@ -0,0 +1 @@ +dist/ diff --git a/packages/core-cli-utils/README.md b/packages/core-cli-utils/README.md new file mode 100644 index 00000000000000..151cdeef757568 --- /dev/null +++ b/packages/core-cli-utils/README.md @@ -0,0 +1,52 @@ +# @react-native/core-cli-utils + +![npm package](https://img.shields.io/npm/v/@react-native/core-cli-utils?color=brightgreen&label=npm%20package) + +A collection of utilites to help Frameworks build their React Native CLI tooling. This is not intended to be used directly use users of React Native. + +## Usage + +```js +import { Command } from 'commander'; +import cli from '@react-native/core-cli-utils'; +import debug from 'debug'; + +const android = new Command('android'); + +const frameworkFindsAndroidSrcDir = "..."; +const tasks = cli.clean.android(frameworkFindsAndroidSrcDir); +const log = debug('fancy-framework:android'); + +android + .command('clean') + .description(cli.clean.android) + .action(async () => { + const log = debug('fancy-framework:android:clean'); + log(`🧹 let me clean your Android caches`); + // Add other caches your framework needs besides the normal React Native caches + // here. + for (const task of tasks) { + try { + log(`\t ${task.label}`); + // See: https://github.com/sindresorhus/execa#lines + const {stdout} = await task.action({ lines: true }) + log(stdout.join('\n\tGradle: ')); + } catch (e) { + log(`\t ⚠️ whoops: ${e.message}`); + } + } + }); +``` + +And you'd be using it like this: + +```bash +$ ./fancy-framework android clean +🧹 let me clean your Android caches + Gradle: // a bunch of gradle output + Gradle: .... +``` + +## Contributing + +Changes to this package can be made locally and linked against your app. Please see the [Contributing guide](https://reactnative.dev/contributing/overview#contributing-code). diff --git a/packages/core-cli-utils/package.json b/packages/core-cli-utils/package.json new file mode 100644 index 00000000000000..58c98e847f3c97 --- /dev/null +++ b/packages/core-cli-utils/package.json @@ -0,0 +1,30 @@ +{ + "name": "@react-native/core-cli-utils", + "version": "0.75.0-main", + "description": "React Native CLI library for Frameworks to build on", + "main": "index.js", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/react-native.git", + "directory": "packages/core-cli-utils" + }, + "exports": { + ".": "./src/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/core-cli-utils#readme", + "keywords": [ + "cli-utils", + "react-native" + ], + "bugs": "https://github.com/facebook/react-native/issues", + "engines": { + "node": ">=18" + }, + "files": [ + "dist" + ], + "dependencies": {}, + "devDependencies": {} +} diff --git a/packages/core-cli-utils/src/index.js b/packages/core-cli-utils/src/index.js new file mode 100644 index 00000000000000..ad4e4c9cde6b8b --- /dev/null +++ b/packages/core-cli-utils/src/index.js @@ -0,0 +1,21 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import {tasks as android} from './private/android.js'; +import {tasks as apple} from './private/apple.js'; +import {tasks as clean} from './private/clean.js'; + +/* eslint sort-keys : "error" */ +export default { + android, + apple, + clean, +}; diff --git a/packages/core-cli-utils/src/private/android.js b/packages/core-cli-utils/src/private/android.js new file mode 100644 index 00000000000000..e6b8e1f8c8bfc9 --- /dev/null +++ b/packages/core-cli-utils/src/private/android.js @@ -0,0 +1,123 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import type {Task} from './types'; + +import {isWindows, task, toPascalCase} from './utils'; +import execa from 'execa'; + +type AndroidBuildMode = 'debug' | 'release'; + +type AndroidBuild = { + sourceDir: string, + appName: string, + mode: AndroidBuildMode, + gradleArgs?: Array, +}; + +type GradleReturn = ReturnType; + +async function gradle( + cwd: string, + ...args: string[] +): ReturnType { + const gradlew = isWindows ? 'gradlew.bat' : './gradlew'; + // $FlowFixMe[incompatible-return] Mismatch between flow and TypeScript types + return execa(gradlew, args, { + cwd, + stdio: 'inherit', + }); +} + +// +// Gradle Task wrappers +// + +/** + * Assembles an Android app using Gradle + */ +export const assemble = ( + cwd: string, + appName: string, + mode: AndroidBuildMode, + ...args: $ReadOnlyArray +): GradleReturn => + gradle(cwd, `${appName}:assemble${toPascalCase(mode)}`, ...args); + +/** + * Assembles and tests an Android app using Gradle + */ +export const build = ( + cwd: string, + appName: string, + mode: AndroidBuildMode, + ...args: $ReadOnlyArray +): GradleReturn => + gradle(cwd, `${appName}:build${toPascalCase(mode)}`, ...args); + +/** + * Installs an Android app using Gradle + */ +export const install = ( + cwd: string, + appName: string, + mode: AndroidBuildMode, + ...args: $ReadOnlyArray +): GradleReturn => + gradle(cwd, `${appName}:install${toPascalCase(mode)}`, ...args); + +/** + * Runs a custom Gradle task if your frameworks needs aren't handled by assemble, build or install. + */ +export const customTask = ( + cwd: string, + customTaskName: string, + ...args: $ReadOnlyArray +): GradleReturn => gradle(cwd, customTaskName, ...args); + +// +// Android Tasks +// + +type AndroidTasks = { + assemble: (options: AndroidBuild, ...args: $ReadOnlyArray) => Task[], + build: (options: AndroidBuild, ...args: $ReadOnlyArray) => Task[], + install: (options: AndroidBuild, ...args: $ReadOnlyArray) => Task[], +}; + +export const tasks: AndroidTasks = { + assemble: (options: AndroidBuild, ...gradleArgs: $ReadOnlyArray) => [ + task('Assemble Android App', () => + assemble(options.sourceDir, options.appName, options.mode, ...gradleArgs), + ), + ], + build: (options: AndroidBuild, ...gradleArgs: $ReadOnlyArray) => [ + task('Assembles and tests Android App', () => + build(options.sourceDir, options.appName, options.mode, ...gradleArgs), + ), + ], + /** + * Useful extra gradle arguments: + * + * -PreactNativeDevServerPort=8081 sets the port for the installed app to point towards a Metro + * server on (for example) 8081. + */ + install: (options: AndroidBuild, ...gradleArgs: $ReadOnlyArray) => [ + task('Installs the assembled Android App', () => + install(options.sourceDir, options.appName, options.mode, ...gradleArgs), + ), + ], + + // We are not supporting launching the app and setting up the tunnel for metro <-> app, this is + // a framework concern. For an example of how one could do this, please look at the community + // CLI's code: + // https://github.com/react-native-community/cli/blob/54d48a4e08a1aef334ae6168788e0157a666b4f5/packages/cli-platform-android/src/commands/runAndroid/index.ts#L272C1-L290C2 +}; diff --git a/packages/core-cli-utils/src/private/apple.js b/packages/core-cli-utils/src/private/apple.js new file mode 100644 index 00000000000000..badb841147f342 --- /dev/null +++ b/packages/core-cli-utils/src/private/apple.js @@ -0,0 +1,103 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import type {Task} from './types'; + +import {assertDependencies, isOnPath, task} from './utils'; +import execa from 'execa'; + +type AppleBuildMode = 'Debug' | 'Release'; + +type AppleBuildOptions = { + isWorkspace: boolean, + name: string, + mode: AppleBuildMode, + scheme: string, + destination?: string, // Device or Simulator or UUID +} & AppleOptions; + +type AppleBootstrapOption = { + bundleInstall: boolean, + // Enabled by default + newArchitecture: boolean, +} & AppleOptions; + +type AppleInstallApp = { + device: string, + appPath: string, +} & AppleOptions; + +type AppleOptions = {cwd: string, env?: {[key: string]: string | void, ...}}; + +type AppleBuildTasks = { + bootstrap: (options: AppleBootstrapOption) => Task[], + build: ( + options: AppleBuildOptions, + ...args: $ReadOnlyArray + ) => Task[], + ios: { + install: (options: AppleInstallApp) => Task[], + }, +}; + +export const tasks: AppleBuildTasks = { + bootstrap: (options: AppleBootstrapOption) => [ + task('Install CocoaPods dependencies', async () => { + assertDependencies( + isOnPath('pod', 'CocoaPods'), + isOnPath('bundle', "Bundler to manage Ruby's gems"), + ); + + if (options.bundleInstall) { + await execa('bundle', ['exec', 'install'], { + cwd: options.cwd, + }); + } + + return await execa('bundle', ['exec', 'pod', 'install'], { + cwd: options.cwd, + env: {RCT_NEW_ARCH_ENABLED: options.newArchitecture ? '1' : '0'}, + }); + }), + ], + + build: (options: AppleBuildOptions, ...args: $ReadOnlyArray) => [ + task('build an app artifact', () => { + assertDependencies(isOnPath('xcodebuild', 'Xcode Commandline Tools')); + const _args = [ + options.isWorkspace ? '-workspace' : '-project', + options.name, + '-scheme', + options.scheme, + ]; + if (options.destination != null) { + _args.push('-destination', options.destination); + } + _args.push(...args); + return execa('xcodebuild', _args, {cwd: options.cwd, env: options.env}); + }), + ], + + ios: { + install: (options: AppleInstallApp) => [ + task('Install the app on a simulator', () => { + assertDependencies( + isOnPath('xcrun', 'An Xcode Commandline tool: xcrun'), + ); + return execa( + 'xcrun', + ['simctl', 'install', options.device, options.appPath], + {cwd: options.cwd, env: options.env}, + ); + }), + ], + }, +}; diff --git a/packages/core-cli-utils/src/private/clean.js b/packages/core-cli-utils/src/private/clean.js new file mode 100644 index 00000000000000..7f5165e4ce0ef8 --- /dev/null +++ b/packages/core-cli-utils/src/private/clean.js @@ -0,0 +1,187 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import type {Task} from './types'; +import type {Options as ExecaOptions} from 'execa'; + +import {isMacOS, isWindows, task} from './utils'; +import execa from 'execa'; +import {existsSync, readdirSync, rm} from 'fs'; +import os from 'os'; +import path from 'path'; + +type CleanTasks = { + android: (androidSrcDir: ?string) => Task[], + metro: () => Task[], + npm: (projectRootDir: string, verifyCache?: boolean) => Task[], + bun: (projectRootDir: string) => Task[], + watchman: (projectRootDir: string) => Task[], + yarn: (projectRootDir: string) => Task[], + cocoapods?: (projectRootDir: string) => Task[], +}; + +const rmrf = (pathname: string) => { + if (!existsSync(pathname)) { + return; + } + rm(pathname, {maxRetries: 3, recursive: true, force: true}); +}; + +/** + * Removes the contents of a directory matching a given pattern, but keeps the directory. + * @private + */ +export function deleteDirectoryContents( + directory: string, + filePattern: RegExp, +): Task['action'] { + return async function deleteDirectoryContentsAction() { + const base = path.dirname(directory); + const files = readdirSync(base).filter((filename: string) => + filePattern.test(filename), + ); + for (const filename of files) { + rmrf(path.join(base, filename)); + } + }; +} + +/** + * Removes a directory recursively. + * @private + */ +export function deleteDirectory(directory: string): Task['action'] { + return async function cleanDirectoryAction() { + rmrf(directory); + }; +} + +/** + * Deletes the contents of the tmp directory matching a given pattern. + * @private + */ +export function deleteTmpDirectoryContents( + filepattern: RegExp, +): ReturnType { + return deleteDirectoryContents(os.tmpdir(), filepattern); +} + +// The tasks that cleanup various build artefacts. +export const tasks: CleanTasks = { + /** + * Cleans up the Android Gradle cache + */ + android: (androidSrcDir: ?string) => [ + task('🧹 Clean Gradle cache', async function gradle(opts?: ExecaOptions) { + const gradlew = path.join( + androidSrcDir ?? 'android', + isWindows ? 'gradlew.bat' : 'gradlew', + ); + + if (!existsSync(gradlew)) { + return; + } + const script = path.basename(gradlew); + const cwd = path.dirname(gradlew); + await execa(isWindows ? script : `./${script}`, ['clean'], { + cwd, + ...opts, + }); + }), + ], + + /** + * Agressively cleans up all Metro caches. + */ + metro: () => [ + task('🧹 Clean Metro cache', deleteTmpDirectoryContents(/^metro-.+/)), + task('🧹 Clean Haste cache', deleteTmpDirectoryContents(/^haste-map-.+/)), + task( + '🧹 Clean React Native cache', + deleteTmpDirectoryContents(/^react-.+/), + ), + ], + + /** + * Cleans up the `node_modules` folder and optionally garbage collects the npm cache. + */ + npm: (projectRootDir: string, verifyCache = false) => { + const _tasks = [ + task( + '🧹 Clean node_modules', + deleteDirectory(path.join(projectRootDir, 'node_modules')), + ), + ]; + if (verifyCache) { + _tasks.push( + task('🔬 Verify npm cache', (opts?: ExecaOptions) => + execa('npm', ['cache', 'verify'], {cwd: projectRootDir, ...opts}), + ), + ); + } + return _tasks; + }, + + /** + * Cleans up the Bun cache. + */ + bun: (projectRootDir: string) => [ + task('🧹 Clean Bun cache', (opts?: ExecaOptions) => + execa('bun', ['pm', 'cache', 'rm'], {cwd: projectRootDir, ...opts}), + ), + ], + + /** + * Stops Watchman and clears its cache + */ + watchman: (projectRootDir: string) => [ + task('✋ Stop Watchman', (opts?: ExecaOptions) => + execa(isWindows ? 'tskill' : 'killall', ['watchman'], { + cwd: projectRootDir, + ...opts, + }), + ), + task('🧹 Delete Watchman cache', (opts?: ExecaOptions) => + execa('watchman', ['watch-del-all'], {cwd: projectRootDir, ...opts}), + ), + ], + + /** + * Cleans up the Yarn cache + */ + yarn: (projectRootDir: string) => [ + task('🧹 Clean Yarn cache', (opts?: ExecaOptions) => + execa('yarn', ['cache', 'clean'], {cwd: projectRootDir, ...opts}), + ), + ], +}; + +if (isMacOS) { + /** + * Cleans up the local and global CocoaPods cache + */ + tasks.cocoapods = (projectRootDir: string) => [ + // TODO: add project root + task( + '🧹 Clean CocoaPods pod cache', + function removePodCache(opts?: ExecaOptions) { + return execa('bundle', ['exec', 'pod', 'deintegrate'], { + cwd: projectRootDir, + ...opts, + }); + }, + ), + ]; +} + +// +// Internal CLI +// diff --git a/packages/core-cli-utils/src/private/types.js b/packages/core-cli-utils/src/private/types.js new file mode 100644 index 00000000000000..7516e059d412d0 --- /dev/null +++ b/packages/core-cli-utils/src/private/types.js @@ -0,0 +1,15 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +export type Task = { + label: string, + action: () => Promise, +}; diff --git a/packages/core-cli-utils/src/private/utils.js b/packages/core-cli-utils/src/private/utils.js new file mode 100644 index 00000000000000..f70a1f59328fa3 --- /dev/null +++ b/packages/core-cli-utils/src/private/utils.js @@ -0,0 +1,53 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import type {Task} from './types'; + +import execa from 'execa'; +import os from 'os'; + +export function task(label: string, action: Task['action']): Task { + return { + label, + action, + }; +} + +export const isWindows = os.platform() === 'win32'; +export const isMacOS = os.platform() === 'darwin'; + +export const toPascalCase = (label: string): string => + label.length === 0 ? '' : label[0].toUpperCase() + label.slice(1); + +type PathCheckResult = { + found: boolean, + dep: string, + description: string, +}; + +export function isOnPath(dep: string, description: string): PathCheckResult { + const result = execa.sync(isWindows ? 'where' : 'which', [dep]); + return { + dep, + description, + found: result.exitCode === 0, + }; +} + +export function assertDependencies( + ...deps: $ReadOnlyArray> +) { + for (const {found, dep, description} of deps) { + if (!found) { + throw new Error(`"${dep}" not found, ${description}`); + } + } +} diff --git a/packages/debugger-frontend/BUILD_INFO b/packages/debugger-frontend/BUILD_INFO index ccaa289b9792be..d9f552896e3971 100644 --- a/packages/debugger-frontend/BUILD_INFO +++ b/packages/debugger-frontend/BUILD_INFO @@ -1,5 +1,5 @@ -@generated SignedSource<> -Git revision: 12a45e0628384aa80075493354159ef5d91b2698 +@generated SignedSource<<80b609f93e8535a704728e4ec9472a94>> +Git revision: 9ceb0ade8033ec165bbfbd41c08ac1fcd9f89a46 Built with --nohooks: false Is local checkout: false Remote URL: https://github.com/facebookexperimental/rn-chrome-devtools-frontend diff --git a/packages/debugger-frontend/dist/third-party/front_end/core/sdk/sdk.js b/packages/debugger-frontend/dist/third-party/front_end/core/sdk/sdk.js index ddecfcd892b878..581c33ed4f4494 100644 --- a/packages/debugger-frontend/dist/third-party/front_end/core/sdk/sdk.js +++ b/packages/debugger-frontend/dist/third-party/front_end/core/sdk/sdk.js @@ -1 +1 @@ -import*as e from"../common/common.js";import*as t from"../platform/platform.js";import{assertNotNullOrUndefined as n}from"../platform/platform.js";import*as r from"../../models/text_utils/text_utils.js";import*as s from"../i18n/i18n.js";import*as i from"../host/host.js";import*as a from"../protocol_client/protocol_client.js";import*as o from"../root/root.js";import*as l from"../../models/trace/trace.js";const d=new Map;class c extends e.ObjectWrapper.ObjectWrapper{#e;constructor(e){super(),this.#e=e}target(){return this.#e}async preSuspendModel(e){}async suspendModel(e){}async resumeModel(){}async postResumeModel(){}dispose(){}static register(e,t){if(t.early&&!t.autostart)throw new Error(`Error registering model ${e.name}: early models must be autostarted.`);d.set(e,t)}static get registeredModels(){return d}}var h=Object.freeze({__proto__:null,SDKModel:c});const u=[{longhands:["animation-delay-start","animation-delay-end"],name:"-alternative-animation-delay"},{longhands:["animation-duration","animation-timing-function","animation-delay-start","animation-delay-end","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name","animation-timeline","animation-range-start","animation-range-end"],name:"-alternative-animation-with-delay-start-end"},{longhands:["animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name","animation-timeline","animation-range-start","animation-range-end"],name:"-alternative-animation-with-timeline"},{inherited:!0,longhands:["white-space-collapse","text-wrap"],name:"-alternative-white-space"},{inherited:!0,name:"-webkit-border-horizontal-spacing"},{name:"-webkit-border-image"},{inherited:!0,name:"-webkit-border-vertical-spacing"},{keywords:["stretch","start","center","end","baseline"],name:"-webkit-box-align"},{keywords:["slice","clone"],name:"-webkit-box-decoration-break"},{inherited:!0,keywords:["normal","reverse"],name:"-webkit-box-direction"},{name:"-webkit-box-flex"},{name:"-webkit-box-ordinal-group"},{keywords:["horizontal","vertical"],name:"-webkit-box-orient"},{keywords:["start","center","end","justify"],name:"-webkit-box-pack"},{name:"-webkit-box-reflect"},{longhands:["break-after"],name:"-webkit-column-break-after"},{longhands:["break-before"],name:"-webkit-column-break-before"},{longhands:["break-inside"],name:"-webkit-column-break-inside"},{inherited:!0,name:"-webkit-font-smoothing"},{inherited:!0,name:"-webkit-highlight"},{inherited:!0,keywords:["auto","loose","normal","strict","after-white-space","anywhere"],name:"-webkit-line-break"},{name:"-webkit-line-clamp"},{inherited:!0,name:"-webkit-locale"},{longhands:["-webkit-mask-image","-webkit-mask-position-x","-webkit-mask-position-y","-webkit-mask-size","-webkit-mask-repeat-x","-webkit-mask-repeat-y","-webkit-mask-origin","-webkit-mask-clip"],name:"-webkit-mask"},{longhands:["-webkit-mask-box-image-source","-webkit-mask-box-image-slice","-webkit-mask-box-image-width","-webkit-mask-box-image-outset","-webkit-mask-box-image-repeat"],name:"-webkit-mask-box-image"},{name:"-webkit-mask-box-image-outset"},{name:"-webkit-mask-box-image-repeat"},{name:"-webkit-mask-box-image-slice"},{name:"-webkit-mask-box-image-source"},{name:"-webkit-mask-box-image-width"},{name:"-webkit-mask-clip"},{name:"-webkit-mask-composite"},{name:"-webkit-mask-image"},{name:"-webkit-mask-origin"},{longhands:["-webkit-mask-position-x","-webkit-mask-position-y"],name:"-webkit-mask-position"},{name:"-webkit-mask-position-x"},{name:"-webkit-mask-position-y"},{longhands:["-webkit-mask-repeat-x","-webkit-mask-repeat-y"],name:"-webkit-mask-repeat"},{name:"-webkit-mask-repeat-x"},{name:"-webkit-mask-repeat-y"},{name:"-webkit-mask-size"},{name:"-webkit-perspective-origin-x"},{name:"-webkit-perspective-origin-y"},{inherited:!0,keywords:["economy","exact"],name:"-webkit-print-color-adjust"},{inherited:!0,keywords:["logical","visual"],name:"-webkit-rtl-ordering"},{inherited:!0,keywords:["before","after"],name:"-webkit-ruby-position"},{inherited:!0,name:"-webkit-tap-highlight-color"},{inherited:!0,name:"-webkit-text-combine"},{inherited:!0,name:"-webkit-text-decorations-in-effect"},{inherited:!0,name:"-webkit-text-fill-color"},{inherited:!0,name:"-webkit-text-orientation"},{inherited:!0,keywords:["none","disc","circle","square"],name:"-webkit-text-security"},{inherited:!0,longhands:["-webkit-text-stroke-width","-webkit-text-stroke-color"],name:"-webkit-text-stroke"},{inherited:!0,name:"-webkit-text-stroke-color"},{inherited:!0,name:"-webkit-text-stroke-width"},{name:"-webkit-transform-origin-x"},{name:"-webkit-transform-origin-y"},{name:"-webkit-transform-origin-z"},{keywords:["auto","none","element"],name:"-webkit-user-drag"},{inherited:!0,keywords:["read-only","read-write","read-write-plaintext-only"],name:"-webkit-user-modify"},{inherited:!0,name:"-webkit-writing-mode"},{inherited:!0,keywords:["auto","currentcolor"],name:"accent-color"},{name:"additive-symbols"},{name:"align-content"},{name:"align-items"},{name:"align-self"},{keywords:["auto","baseline","alphabetic","ideographic","middle","central","mathematical","before-edge","text-before-edge","after-edge","text-after-edge","hanging"],name:"alignment-baseline"},{name:"all"},{keywords:["none"],name:"anchor-default"},{keywords:["none"],name:"anchor-name"},{keywords:["none"],name:"anchor-scroll"},{longhands:["animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name"],name:"animation"},{keywords:["replace","add","accumulate"],name:"animation-composition"},{name:"animation-delay"},{name:"animation-delay-end"},{name:"animation-delay-start"},{keywords:["normal","reverse","alternate","alternate-reverse"],name:"animation-direction"},{name:"animation-duration"},{keywords:["none","forwards","backwards","both"],name:"animation-fill-mode"},{keywords:["infinite"],name:"animation-iteration-count"},{keywords:["none"],name:"animation-name"},{keywords:["running","paused"],name:"animation-play-state"},{longhands:["animation-range-start","animation-range-end"],name:"animation-range"},{name:"animation-range-end"},{name:"animation-range-start"},{keywords:["none","auto"],name:"animation-timeline"},{keywords:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"],name:"animation-timing-function"},{keywords:["none","drag","no-drag"],name:"app-region"},{name:"appearance"},{name:"ascent-override"},{keywords:["auto"],name:"aspect-ratio"},{keywords:["none"],name:"backdrop-filter"},{keywords:["visible","hidden"],name:"backface-visibility"},{longhands:["background-image","background-position-x","background-position-y","background-size","background-repeat-x","background-repeat-y","background-attachment","background-origin","background-clip","background-color"],name:"background"},{keywords:["scroll","fixed","local"],name:"background-attachment"},{keywords:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],name:"background-blend-mode"},{keywords:["border-box","padding-box","content-box"],name:"background-clip"},{keywords:["currentcolor"],name:"background-color"},{keywords:["auto","none"],name:"background-image"},{keywords:["border-box","padding-box","content-box"],name:"background-origin"},{longhands:["background-position-x","background-position-y"],name:"background-position"},{name:"background-position-x"},{name:"background-position-y"},{longhands:["background-repeat-x","background-repeat-y"],name:"background-repeat"},{name:"background-repeat-x"},{name:"background-repeat-y"},{keywords:["auto","cover","contain"],name:"background-size"},{name:"base-palette"},{keywords:["baseline","sub","super"],name:"baseline-shift"},{keywords:["auto","first","last"],name:"baseline-source"},{keywords:["auto"],name:"block-size"},{longhands:["border-top-color","border-top-style","border-top-width","border-right-color","border-right-style","border-right-width","border-bottom-color","border-bottom-style","border-bottom-width","border-left-color","border-left-style","border-left-width","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],name:"border"},{longhands:["border-block-start-color","border-block-start-style","border-block-start-width","border-block-end-color","border-block-end-style","border-block-end-width"],name:"border-block"},{longhands:["border-block-start-color","border-block-end-color"],name:"border-block-color"},{longhands:["border-block-end-width","border-block-end-style","border-block-end-color"],name:"border-block-end"},{name:"border-block-end-color"},{name:"border-block-end-style"},{name:"border-block-end-width"},{longhands:["border-block-start-width","border-block-start-style","border-block-start-color"],name:"border-block-start"},{name:"border-block-start-color"},{name:"border-block-start-style"},{name:"border-block-start-width"},{longhands:["border-block-start-style","border-block-end-style"],name:"border-block-style"},{longhands:["border-block-start-width","border-block-end-width"],name:"border-block-width"},{longhands:["border-bottom-width","border-bottom-style","border-bottom-color"],name:"border-bottom"},{keywords:["currentcolor"],name:"border-bottom-color"},{name:"border-bottom-left-radius"},{name:"border-bottom-right-radius"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-bottom-style"},{keywords:["thin","medium","thick"],name:"border-bottom-width"},{inherited:!0,keywords:["separate","collapse"],name:"border-collapse"},{longhands:["border-top-color","border-right-color","border-bottom-color","border-left-color"],name:"border-color"},{name:"border-end-end-radius"},{name:"border-end-start-radius"},{longhands:["border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],name:"border-image"},{name:"border-image-outset"},{keywords:["stretch","repeat","round","space"],name:"border-image-repeat"},{name:"border-image-slice"},{keywords:["none"],name:"border-image-source"},{keywords:["auto"],name:"border-image-width"},{longhands:["border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-end-color","border-inline-end-style","border-inline-end-width"],name:"border-inline"},{longhands:["border-inline-start-color","border-inline-end-color"],name:"border-inline-color"},{longhands:["border-inline-end-width","border-inline-end-style","border-inline-end-color"],name:"border-inline-end"},{name:"border-inline-end-color"},{name:"border-inline-end-style"},{name:"border-inline-end-width"},{longhands:["border-inline-start-width","border-inline-start-style","border-inline-start-color"],name:"border-inline-start"},{name:"border-inline-start-color"},{name:"border-inline-start-style"},{name:"border-inline-start-width"},{longhands:["border-inline-start-style","border-inline-end-style"],name:"border-inline-style"},{longhands:["border-inline-start-width","border-inline-end-width"],name:"border-inline-width"},{longhands:["border-left-width","border-left-style","border-left-color"],name:"border-left"},{keywords:["currentcolor"],name:"border-left-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-left-style"},{keywords:["thin","medium","thick"],name:"border-left-width"},{longhands:["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],name:"border-radius"},{longhands:["border-right-width","border-right-style","border-right-color"],name:"border-right"},{keywords:["currentcolor"],name:"border-right-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-right-style"},{keywords:["thin","medium","thick"],name:"border-right-width"},{inherited:!0,longhands:["-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing"],name:"border-spacing"},{name:"border-start-end-radius"},{name:"border-start-start-radius"},{keywords:["none"],longhands:["border-top-style","border-right-style","border-bottom-style","border-left-style"],name:"border-style"},{longhands:["border-top-width","border-top-style","border-top-color"],name:"border-top"},{keywords:["currentcolor"],name:"border-top-color"},{name:"border-top-left-radius"},{name:"border-top-right-radius"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-top-style"},{keywords:["thin","medium","thick"],name:"border-top-width"},{longhands:["border-top-width","border-right-width","border-bottom-width","border-left-width"],name:"border-width"},{keywords:["auto"],name:"bottom"},{keywords:["none"],name:"box-shadow"},{keywords:["content-box","border-box"],name:"box-sizing"},{keywords:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"],name:"break-after"},{keywords:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"],name:"break-before"},{keywords:["auto","avoid","avoid-column","avoid-page"],name:"break-inside"},{keywords:["auto","dynamic","static"],name:"buffered-rendering"},{inherited:!0,keywords:["top","bottom"],name:"caption-side"},{inherited:!0,keywords:["auto","currentcolor"],name:"caret-color"},{keywords:["none","left","right","both","inline-start","inline-end"],name:"clear"},{keywords:["auto"],name:"clip"},{keywords:["none"],name:"clip-path"},{inherited:!0,keywords:["nonzero","evenodd"],name:"clip-rule"},{inherited:!0,keywords:["currentcolor"],name:"color"},{inherited:!0,keywords:["auto","srgb","linearrgb"],name:"color-interpolation"},{inherited:!0,keywords:["auto","srgb","linearrgb"],name:"color-interpolation-filters"},{inherited:!0,keywords:["auto","optimizespeed","optimizequality"],name:"color-rendering"},{inherited:!0,name:"color-scheme"},{keywords:["auto"],name:"column-count"},{keywords:["balance","auto"],name:"column-fill"},{keywords:["normal"],name:"column-gap"},{longhands:["column-rule-width","column-rule-style","column-rule-color"],name:"column-rule"},{keywords:["currentcolor"],name:"column-rule-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"column-rule-style"},{keywords:["thin","medium","thick"],name:"column-rule-width"},{keywords:["none","all"],name:"column-span"},{keywords:["auto"],name:"column-width"},{longhands:["column-width","column-count"],name:"columns"},{keywords:["none","strict","content","size","layout","style","paint","inline-size","block-size"],name:"contain"},{name:"contain-intrinsic-block-size"},{keywords:["auto","none"],name:"contain-intrinsic-height"},{name:"contain-intrinsic-inline-size"},{longhands:["contain-intrinsic-width","contain-intrinsic-height"],name:"contain-intrinsic-size"},{keywords:["auto","none"],name:"contain-intrinsic-width"},{longhands:["container-name","container-type"],name:"container"},{keywords:["none"],name:"container-name"},{keywords:["normal","inline-size","size","sticky"],name:"container-type"},{name:"content"},{keywords:["visible","auto","hidden"],name:"content-visibility"},{keywords:["none"],name:"counter-increment"},{keywords:["none"],name:"counter-reset"},{keywords:["none"],name:"counter-set"},{inherited:!0,keywords:["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","grab","grabbing"],name:"cursor"},{name:"cx"},{name:"cy"},{keywords:["none"],name:"d"},{name:"descent-override"},{inherited:!0,keywords:["ltr","rtl"],name:"direction"},{keywords:["inline","block","list-item","inline-block","table","inline-table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption","-webkit-box","-webkit-inline-box","flex","inline-flex","grid","inline-grid","contents","flow-root","none","flow","math"],name:"display"},{inherited:!0,keywords:["auto","alphabetic","ideographic","middle","central","mathematical","hanging","use-script","no-change","reset-size","text-after-edge","text-before-edge"],name:"dominant-baseline"},{inherited:!0,keywords:["show","hide"],name:"empty-cells"},{name:"fallback"},{inherited:!0,name:"fill"},{inherited:!0,name:"fill-opacity"},{inherited:!0,keywords:["nonzero","evenodd"],name:"fill-rule"},{keywords:["none"],name:"filter"},{longhands:["flex-grow","flex-shrink","flex-basis"],name:"flex"},{keywords:["auto","fit-content","min-content","max-content","content"],name:"flex-basis"},{keywords:["row","row-reverse","column","column-reverse"],name:"flex-direction"},{longhands:["flex-direction","flex-wrap"],name:"flex-flow"},{name:"flex-grow"},{name:"flex-shrink"},{keywords:["nowrap","wrap","wrap-reverse"],name:"flex-wrap"},{keywords:["none","left","right","inline-start","inline-end"],name:"float"},{keywords:["currentcolor"],name:"flood-color"},{name:"flood-opacity"},{inherited:!0,longhands:["font-style","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-variant-alternates","font-variant-position","font-weight","font-stretch","font-size","line-height","font-family","font-optical-sizing","font-size-adjust","font-kerning","font-feature-settings","font-variation-settings"],name:"font"},{name:"font-display"},{inherited:!0,name:"font-family"},{inherited:!0,keywords:["normal"],name:"font-feature-settings"},{inherited:!0,keywords:["auto","normal","none"],name:"font-kerning"},{inherited:!0,keywords:["auto","none"],name:"font-optical-sizing"},{inherited:!0,keywords:["normal","light","dark"],name:"font-palette"},{inherited:!0,keywords:["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller","-webkit-xxx-large"],name:"font-size"},{inherited:!0,keywords:["none","ex-height","cap-height","ch-width","ic-width"],name:"font-size-adjust"},{inherited:!0,keywords:["normal","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"],name:"font-stretch"},{inherited:!0,keywords:["normal","italic","oblique"],name:"font-style"},{inherited:!0,longhands:["font-synthesis-weight","font-synthesis-style","font-synthesis-small-caps"],name:"font-synthesis"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-small-caps"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-style"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-weight"},{inherited:!0,longhands:["font-variant-ligatures","font-variant-caps","font-variant-alternates","font-variant-numeric","font-variant-east-asian","font-variant-position"],name:"font-variant"},{inherited:!0,keywords:["normal"],name:"font-variant-alternates"},{inherited:!0,keywords:["normal","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps"],name:"font-variant-caps"},{inherited:!0,keywords:["normal","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"],name:"font-variant-east-asian"},{inherited:!0,keywords:["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual"],name:"font-variant-ligatures"},{inherited:!0,keywords:["normal","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero"],name:"font-variant-numeric"},{inherited:!0,keywords:["normal","sub","super"],name:"font-variant-position"},{inherited:!0,keywords:["normal"],name:"font-variation-settings"},{inherited:!0,keywords:["normal","bold","bolder","lighter"],name:"font-weight"},{inherited:!0,keywords:["auto","none","preserve-parent-color"],name:"forced-color-adjust"},{longhands:["row-gap","column-gap"],name:"gap"},{longhands:["grid-template-rows","grid-template-columns","grid-template-areas","grid-auto-flow","grid-auto-rows","grid-auto-columns"],name:"grid"},{longhands:["grid-row-start","grid-column-start","grid-row-end","grid-column-end"],name:"grid-area"},{keywords:["auto","min-content","max-content"],name:"grid-auto-columns"},{keywords:["row","column"],name:"grid-auto-flow"},{keywords:["auto","min-content","max-content"],name:"grid-auto-rows"},{longhands:["grid-column-start","grid-column-end"],name:"grid-column"},{keywords:["auto"],name:"grid-column-end"},{longhands:["column-gap"],name:"grid-column-gap"},{keywords:["auto"],name:"grid-column-start"},{longhands:["row-gap","column-gap"],name:"grid-gap"},{longhands:["grid-row-start","grid-row-end"],name:"grid-row"},{keywords:["auto"],name:"grid-row-end"},{longhands:["row-gap"],name:"grid-row-gap"},{keywords:["auto"],name:"grid-row-start"},{longhands:["grid-template-rows","grid-template-columns","grid-template-areas"],name:"grid-template"},{keywords:["none"],name:"grid-template-areas"},{keywords:["none"],name:"grid-template-columns"},{keywords:["none"],name:"grid-template-rows"},{keywords:["auto","fit-content","min-content","max-content"],name:"height"},{inherited:!0,name:"hyphenate-character"},{inherited:!0,keywords:["auto"],name:"hyphenate-limit-chars"},{inherited:!0,keywords:["none","manual","auto"],name:"hyphens"},{inherited:!0,name:"image-orientation"},{inherited:!0,keywords:["auto","optimizespeed","optimizequality","-webkit-optimize-contrast","pixelated"],name:"image-rendering"},{name:"inherits"},{inherited:!1,keywords:["drop","normal","raise"],name:"initial-letter"},{name:"initial-value"},{keywords:["auto"],name:"inline-size"},{longhands:["top","right","bottom","left"],name:"inset"},{longhands:["inset-block-start","inset-block-end"],name:"inset-block"},{name:"inset-block-end"},{name:"inset-block-start"},{longhands:["inset-inline-start","inset-inline-end"],name:"inset-inline"},{name:"inset-inline-end"},{name:"inset-inline-start"},{keywords:["auto","isolate"],name:"isolation"},{name:"justify-content"},{name:"justify-items"},{name:"justify-self"},{keywords:["auto"],name:"left"},{inherited:!0,keywords:["normal"],name:"letter-spacing"},{keywords:["currentcolor"],name:"lighting-color"},{inherited:!0,keywords:["auto","loose","normal","strict","anywhere"],name:"line-break"},{name:"line-gap-override"},{inherited:!0,keywords:["normal"],name:"line-height"},{inherited:!0,longhands:["list-style-position","list-style-image","list-style-type"],name:"list-style"},{inherited:!0,keywords:["none"],name:"list-style-image"},{inherited:!0,keywords:["outside","inside"],name:"list-style-position"},{inherited:!0,keywords:["disc","circle","square","disclosure-open","disclosure-closed","decimal","none"],name:"list-style-type"},{longhands:["margin-top","margin-right","margin-bottom","margin-left"],name:"margin"},{longhands:["margin-block-start","margin-block-end"],name:"margin-block"},{keywords:["auto"],name:"margin-block-end"},{keywords:["auto"],name:"margin-block-start"},{keywords:["auto"],name:"margin-bottom"},{longhands:["margin-inline-start","margin-inline-end"],name:"margin-inline"},{keywords:["auto"],name:"margin-inline-end"},{keywords:["auto"],name:"margin-inline-start"},{keywords:["auto"],name:"margin-left"},{keywords:["auto"],name:"margin-right"},{keywords:["auto"],name:"margin-top"},{inherited:!0,longhands:["marker-start","marker-mid","marker-end"],name:"marker"},{inherited:!0,keywords:["none"],name:"marker-end"},{inherited:!0,keywords:["none"],name:"marker-mid"},{inherited:!0,keywords:["none"],name:"marker-start"},{name:"mask"},{keywords:["luminance","alpha"],name:"mask-type"},{inherited:!0,name:"math-depth"},{inherited:!0,keywords:["normal","compact"],name:"math-shift"},{inherited:!0,keywords:["normal","compact"],name:"math-style"},{keywords:["none"],name:"max-block-size"},{keywords:["none"],name:"max-height"},{keywords:["none"],name:"max-inline-size"},{keywords:["none"],name:"max-width"},{name:"min-block-size"},{name:"min-height"},{name:"min-inline-size"},{name:"min-width"},{keywords:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],name:"mix-blend-mode"},{name:"negative"},{keywords:["fill","contain","cover","none","scale-down"],name:"object-fit"},{name:"object-position"},{keywords:["none"],name:"object-view-box"},{longhands:["offset-position","offset-path","offset-distance","offset-rotate","offset-anchor"],name:"offset"},{keywords:["auto"],name:"offset-anchor"},{name:"offset-distance"},{keywords:["none"],name:"offset-path"},{keywords:["auto","normal"],name:"offset-position"},{keywords:["auto","reverse"],name:"offset-rotate"},{name:"opacity"},{name:"order"},{keywords:["normal","none"],name:"origin-trial-test-property"},{inherited:!0,name:"orphans"},{longhands:["outline-color","outline-style","outline-width"],name:"outline"},{keywords:["currentcolor"],name:"outline-color"},{name:"outline-offset"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"outline-style"},{keywords:["thin","medium","thick"],name:"outline-width"},{longhands:["overflow-x","overflow-y"],name:"overflow"},{inherited:!1,keywords:["visible","none","auto"],name:"overflow-anchor"},{name:"overflow-block"},{keywords:["border-box","content-box","padding-box"],name:"overflow-clip-margin"},{name:"overflow-inline"},{inherited:!0,keywords:["normal","break-word","anywhere"],name:"overflow-wrap"},{keywords:["visible","hidden","scroll","auto","overlay","clip"],name:"overflow-x"},{keywords:["visible","hidden","scroll","auto","overlay","clip"],name:"overflow-y"},{keywords:["none","auto"],name:"overlay"},{name:"override-colors"},{longhands:["overscroll-behavior-x","overscroll-behavior-y"],name:"overscroll-behavior"},{name:"overscroll-behavior-block"},{name:"overscroll-behavior-inline"},{keywords:["auto","contain","none"],name:"overscroll-behavior-x"},{keywords:["auto","contain","none"],name:"overscroll-behavior-y"},{name:"pad"},{longhands:["padding-top","padding-right","padding-bottom","padding-left"],name:"padding"},{longhands:["padding-block-start","padding-block-end"],name:"padding-block"},{name:"padding-block-end"},{name:"padding-block-start"},{name:"padding-bottom"},{longhands:["padding-inline-start","padding-inline-end"],name:"padding-inline"},{name:"padding-inline-end"},{name:"padding-inline-start"},{name:"padding-left"},{name:"padding-right"},{name:"padding-top"},{keywords:["auto"],name:"page"},{longhands:["break-after"],name:"page-break-after"},{longhands:["break-before"],name:"page-break-before"},{longhands:["break-inside"],name:"page-break-inside"},{name:"page-orientation"},{inherited:!0,keywords:["normal","fill","stroke","markers"],name:"paint-order"},{keywords:["none"],name:"perspective"},{name:"perspective-origin"},{longhands:["align-content","justify-content"],name:"place-content"},{longhands:["align-items","justify-items"],name:"place-items"},{longhands:["align-self","justify-self"],name:"place-self"},{inherited:!0,keywords:["none","auto","stroke","fill","painted","visible","visiblestroke","visiblefill","visiblepainted","bounding-box","all"],name:"pointer-events"},{name:"popover-hide-delay"},{name:"popover-show-delay"},{keywords:["static","relative","absolute","fixed","sticky"],name:"position"},{keywords:["none"],name:"position-fallback"},{name:"prefix"},{inherited:!0,keywords:["auto","none"],name:"quotes"},{name:"r"},{name:"range"},{keywords:["none","both","horizontal","vertical","block","inline"],name:"resize"},{keywords:["auto"],name:"right"},{name:"rotate"},{keywords:["normal"],name:"row-gap"},{inherited:!0,name:"ruby-position"},{keywords:["auto"],name:"rx"},{keywords:["auto"],name:"ry"},{name:"scale"},{keywords:["auto","smooth"],name:"scroll-behavior"},{name:"scroll-customization"},{longhands:["scroll-margin-top","scroll-margin-right","scroll-margin-bottom","scroll-margin-left"],name:"scroll-margin"},{longhands:["scroll-margin-block-start","scroll-margin-block-end"],name:"scroll-margin-block"},{name:"scroll-margin-block-end"},{name:"scroll-margin-block-start"},{name:"scroll-margin-bottom"},{longhands:["scroll-margin-inline-start","scroll-margin-inline-end"],name:"scroll-margin-inline"},{name:"scroll-margin-inline-end"},{name:"scroll-margin-inline-start"},{name:"scroll-margin-left"},{name:"scroll-margin-right"},{name:"scroll-margin-top"},{longhands:["scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left"],name:"scroll-padding"},{longhands:["scroll-padding-block-start","scroll-padding-block-end"],name:"scroll-padding-block"},{keywords:["auto"],name:"scroll-padding-block-end"},{keywords:["auto"],name:"scroll-padding-block-start"},{keywords:["auto"],name:"scroll-padding-bottom"},{longhands:["scroll-padding-inline-start","scroll-padding-inline-end"],name:"scroll-padding-inline"},{keywords:["auto"],name:"scroll-padding-inline-end"},{keywords:["auto"],name:"scroll-padding-inline-start"},{keywords:["auto"],name:"scroll-padding-left"},{keywords:["auto"],name:"scroll-padding-right"},{keywords:["auto"],name:"scroll-padding-top"},{keywords:["none","start","end","center"],name:"scroll-snap-align"},{keywords:["normal","always"],name:"scroll-snap-stop"},{keywords:["none","x","y","block","inline","both","mandatory","proximity"],name:"scroll-snap-type"},{longhands:["scroll-start-block","scroll-start-inline"],name:"scroll-start"},{keywords:["auto","start","end","center","top","bottom","left","right"],name:"scroll-start-block"},{keywords:["auto","start","end","center","top","bottom","left","right"],name:"scroll-start-inline"},{longhands:["scroll-start-target-block","scroll-start-target-inline"],name:"scroll-start-target"},{keywords:["none","auto"],name:"scroll-start-target-block"},{keywords:["none","auto"],name:"scroll-start-target-inline"},{keywords:["none","auto"],name:"scroll-start-target-x"},{keywords:["none","auto"],name:"scroll-start-target-y"},{name:"scroll-start-x"},{name:"scroll-start-y"},{longhands:["scroll-timeline-name","scroll-timeline-axis","scroll-timeline-attachment"],name:"scroll-timeline"},{name:"scroll-timeline-attachment"},{name:"scroll-timeline-axis"},{name:"scroll-timeline-name"},{inherited:!0,keywords:["auto"],name:"scrollbar-color"},{inherited:!1,keywords:["auto","stable","both-edges"],name:"scrollbar-gutter"},{inherited:!1,keywords:["auto","thin","none"],name:"scrollbar-width"},{name:"shape-image-threshold"},{keywords:["none"],name:"shape-margin"},{keywords:["none"],name:"shape-outside"},{inherited:!0,keywords:["auto","optimizespeed","crispedges","geometricprecision"],name:"shape-rendering"},{name:"size"},{name:"size-adjust"},{inherited:!0,keywords:["none","normal","spell-out","digits","literal-punctuation","no-punctuation"],name:"speak"},{name:"speak-as"},{name:"src"},{keywords:["currentcolor"],name:"stop-color"},{name:"stop-opacity"},{inherited:!0,name:"stroke"},{inherited:!0,keywords:["none"],name:"stroke-dasharray"},{inherited:!0,name:"stroke-dashoffset"},{inherited:!0,keywords:["butt","round","square"],name:"stroke-linecap"},{inherited:!0,keywords:["miter","bevel","round"],name:"stroke-linejoin"},{inherited:!0,name:"stroke-miterlimit"},{inherited:!0,name:"stroke-opacity"},{inherited:!0,name:"stroke-width"},{name:"suffix"},{name:"symbols"},{name:"syntax"},{name:"system"},{inherited:!0,name:"tab-size"},{keywords:["auto","fixed"],name:"table-layout"},{inherited:!0,keywords:["left","right","center","justify","-webkit-left","-webkit-right","-webkit-center","start","end"],name:"text-align"},{inherited:!0,keywords:["auto","start","end","left","right","center","justify"],name:"text-align-last"},{inherited:!0,keywords:["start","middle","end"],name:"text-anchor"},{keywords:["none","start","end","both"],name:"text-box-trim"},{inherited:!0,keywords:["none","all"],name:"text-combine-upright"},{longhands:["text-decoration-line","text-decoration-thickness","text-decoration-style","text-decoration-color"],name:"text-decoration"},{keywords:["currentcolor"],name:"text-decoration-color"},{keywords:["none","underline","overline","line-through","blink","spelling-error","grammar-error"],name:"text-decoration-line"},{inherited:!0,keywords:["none","auto"],name:"text-decoration-skip-ink"},{keywords:["solid","double","dotted","dashed","wavy"],name:"text-decoration-style"},{inherited:!0,keywords:["auto","from-font"],name:"text-decoration-thickness"},{inherited:!0,longhands:["text-emphasis-style","text-emphasis-color"],name:"text-emphasis"},{inherited:!0,keywords:["currentcolor"],name:"text-emphasis-color"},{inherited:!0,name:"text-emphasis-position"},{inherited:!0,name:"text-emphasis-style"},{inherited:!0,name:"text-indent"},{inherited:!0,keywords:["sideways","mixed","upright"],name:"text-orientation"},{keywords:["clip","ellipsis"],name:"text-overflow"},{inherited:!0,keywords:["auto","optimizespeed","optimizelegibility","geometricprecision"],name:"text-rendering"},{inherited:!0,keywords:["none"],name:"text-shadow"},{inherited:!0,keywords:["none","auto"],name:"text-size-adjust"},{inherited:!0,keywords:["capitalize","uppercase","lowercase","none","math-auto"],name:"text-transform"},{inherited:!0,keywords:["auto"],name:"text-underline-offset"},{inherited:!0,keywords:["auto","from-font","under","left","right"],name:"text-underline-position"},{inherited:!0,keywords:["wrap","nowrap","balance","pretty"],name:"text-wrap"},{name:"timeline-scope"},{longhands:["toggle-root","toggle-trigger"],name:"toggle"},{keywords:["none"],name:"toggle-group"},{keywords:["none"],name:"toggle-root"},{keywords:["none"],name:"toggle-trigger"},{keywords:["normal"],name:"toggle-visibility"},{keywords:["auto"],name:"top"},{keywords:["auto","none","pan-x","pan-left","pan-right","pan-y","pan-up","pan-down","pinch-zoom","manipulation"],name:"touch-action"},{keywords:["none"],name:"transform"},{keywords:["fill-box","view-box"],name:"transform-box"},{name:"transform-origin"},{keywords:["flat","preserve-3d"],name:"transform-style"},{longhands:["transition-property","transition-duration","transition-timing-function","transition-delay"],name:"transition"},{name:"transition-delay"},{name:"transition-duration"},{keywords:["none"],name:"transition-property"},{keywords:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"],name:"transition-timing-function"},{name:"translate"},{keywords:["normal","embed","bidi-override","isolate","plaintext","isolate-override"],name:"unicode-bidi"},{name:"unicode-range"},{inherited:!0,keywords:["auto","none","text","all","contain"],name:"user-select"},{keywords:["none","non-scaling-stroke"],name:"vector-effect"},{keywords:["baseline","sub","super","text-top","text-bottom","middle"],name:"vertical-align"},{longhands:["view-timeline-name","view-timeline-axis","view-timeline-attachment"],name:"view-timeline"},{name:"view-timeline-attachment"},{name:"view-timeline-axis"},{name:"view-timeline-inset"},{name:"view-timeline-name"},{keywords:["none"],name:"view-transition-name"},{inherited:!0,keywords:["visible","hidden","collapse"],name:"visibility"},{inherited:!0,keywords:["normal","pre","pre-wrap","pre-line","nowrap","break-spaces"],name:"white-space"},{inherited:!0,keywords:["collapse","preserve","preserve-breaks","break-spaces"],name:"white-space-collapse"},{inherited:!0,name:"widows"},{keywords:["auto","fit-content","min-content","max-content"],name:"width"},{keywords:["auto"],name:"will-change"},{inherited:!0,keywords:["normal"],name:"word-boundary-detection"},{inherited:!0,keywords:["normal","break-all","keep-all","break-word"],name:"word-break"},{inherited:!0,keywords:["normal"],name:"word-spacing"},{inherited:!0,keywords:["horizontal-tb","vertical-rl","vertical-lr"],name:"writing-mode"},{name:"x"},{name:"y"},{keywords:["auto"],name:"z-index"},{name:"zoom"}],g={"-webkit-box-align":{values:["stretch","start","center","end","baseline"]},"-webkit-box-decoration-break":{values:["slice","clone"]},"-webkit-box-direction":{values:["normal","reverse"]},"-webkit-box-orient":{values:["horizontal","vertical"]},"-webkit-box-pack":{values:["start","center","end","justify"]},"-webkit-line-break":{values:["auto","loose","normal","strict","after-white-space","anywhere"]},"-webkit-print-color-adjust":{values:["economy","exact"]},"-webkit-rtl-ordering":{values:["logical","visual"]},"-webkit-ruby-position":{values:["before","after"]},"-webkit-text-security":{values:["none","disc","circle","square"]},"-webkit-user-drag":{values:["auto","none","element"]},"-webkit-user-modify":{values:["read-only","read-write","read-write-plaintext-only"]},"accent-color":{values:["auto","currentcolor"]},"alignment-baseline":{values:["auto","baseline","alphabetic","ideographic","middle","central","mathematical","before-edge","text-before-edge","after-edge","text-after-edge","hanging"]},"anchor-default":{values:["none"]},"anchor-name":{values:["none"]},"anchor-scroll":{values:["none"]},"animation-composition":{values:["replace","add","accumulate"]},"animation-direction":{values:["normal","reverse","alternate","alternate-reverse"]},"animation-fill-mode":{values:["none","forwards","backwards","both"]},"animation-iteration-count":{values:["infinite"]},"animation-name":{values:["none"]},"animation-play-state":{values:["running","paused"]},"animation-timeline":{values:["none","auto"]},"animation-timing-function":{values:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"]},"app-region":{values:["none","drag","no-drag"]},"aspect-ratio":{values:["auto"]},"backdrop-filter":{values:["none"]},"backface-visibility":{values:["visible","hidden"]},"background-attachment":{values:["scroll","fixed","local"]},"background-blend-mode":{values:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]},"background-clip":{values:["border-box","padding-box","content-box"]},"background-color":{values:["currentcolor"]},"background-image":{values:["auto","none"]},"background-origin":{values:["border-box","padding-box","content-box"]},"background-size":{values:["auto","cover","contain"]},"baseline-shift":{values:["baseline","sub","super"]},"baseline-source":{values:["auto","first","last"]},"block-size":{values:["auto"]},"border-bottom-color":{values:["currentcolor"]},"border-bottom-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-bottom-width":{values:["thin","medium","thick"]},"border-collapse":{values:["separate","collapse"]},"border-image-repeat":{values:["stretch","repeat","round","space"]},"border-image-source":{values:["none"]},"border-image-width":{values:["auto"]},"border-left-color":{values:["currentcolor"]},"border-left-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-left-width":{values:["thin","medium","thick"]},"border-right-color":{values:["currentcolor"]},"border-right-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-right-width":{values:["thin","medium","thick"]},"border-style":{values:["none"]},"border-top-color":{values:["currentcolor"]},"border-top-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-top-width":{values:["thin","medium","thick"]},bottom:{values:["auto"]},"box-shadow":{values:["none"]},"box-sizing":{values:["content-box","border-box"]},"break-after":{values:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"]},"break-before":{values:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"]},"break-inside":{values:["auto","avoid","avoid-column","avoid-page"]},"buffered-rendering":{values:["auto","dynamic","static"]},"caption-side":{values:["top","bottom"]},"caret-color":{values:["auto","currentcolor"]},clear:{values:["none","left","right","both","inline-start","inline-end"]},clip:{values:["auto"]},"clip-path":{values:["none"]},"clip-rule":{values:["nonzero","evenodd"]},color:{values:["currentcolor"]},"color-interpolation":{values:["auto","srgb","linearrgb"]},"color-interpolation-filters":{values:["auto","srgb","linearrgb"]},"color-rendering":{values:["auto","optimizespeed","optimizequality"]},"column-count":{values:["auto"]},"column-fill":{values:["balance","auto"]},"column-gap":{values:["normal"]},"column-rule-color":{values:["currentcolor"]},"column-rule-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"column-rule-width":{values:["thin","medium","thick"]},"column-span":{values:["none","all"]},"column-width":{values:["auto"]},contain:{values:["none","strict","content","size","layout","style","paint","inline-size","block-size"]},"contain-intrinsic-height":{values:["auto","none"]},"contain-intrinsic-width":{values:["auto","none"]},"container-name":{values:["none"]},"container-type":{values:["normal","inline-size","size","sticky"]},"content-visibility":{values:["visible","auto","hidden"]},"counter-increment":{values:["none"]},"counter-reset":{values:["none"]},"counter-set":{values:["none"]},cursor:{values:["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","grab","grabbing"]},d:{values:["none"]},direction:{values:["ltr","rtl"]},display:{values:["inline","block","list-item","inline-block","table","inline-table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption","-webkit-box","-webkit-inline-box","flex","inline-flex","grid","inline-grid","contents","flow-root","none","flow","math"]},"dominant-baseline":{values:["auto","alphabetic","ideographic","middle","central","mathematical","hanging","use-script","no-change","reset-size","text-after-edge","text-before-edge"]},"empty-cells":{values:["show","hide"]},"fill-rule":{values:["nonzero","evenodd"]},filter:{values:["none"]},"flex-basis":{values:["auto","fit-content","min-content","max-content","content"]},"flex-direction":{values:["row","row-reverse","column","column-reverse"]},"flex-wrap":{values:["nowrap","wrap","wrap-reverse"]},float:{values:["none","left","right","inline-start","inline-end"]},"flood-color":{values:["currentcolor"]},"font-feature-settings":{values:["normal"]},"font-kerning":{values:["auto","normal","none"]},"font-optical-sizing":{values:["auto","none"]},"font-palette":{values:["normal","light","dark"]},"font-size":{values:["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller","-webkit-xxx-large"]},"font-size-adjust":{values:["none","ex-height","cap-height","ch-width","ic-width"]},"font-stretch":{values:["normal","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"]},"font-style":{values:["normal","italic","oblique"]},"font-synthesis-small-caps":{values:["auto","none"]},"font-synthesis-style":{values:["auto","none"]},"font-synthesis-weight":{values:["auto","none"]},"font-variant-alternates":{values:["normal"]},"font-variant-caps":{values:["normal","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps"]},"font-variant-east-asian":{values:["normal","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"]},"font-variant-ligatures":{values:["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual"]},"font-variant-numeric":{values:["normal","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero"]},"font-variant-position":{values:["normal","sub","super"]},"font-variation-settings":{values:["normal"]},"font-weight":{values:["normal","bold","bolder","lighter"]},"forced-color-adjust":{values:["auto","none","preserve-parent-color"]},"grid-auto-columns":{values:["auto","min-content","max-content"]},"grid-auto-flow":{values:["row","column"]},"grid-auto-rows":{values:["auto","min-content","max-content"]},"grid-column-end":{values:["auto"]},"grid-column-start":{values:["auto"]},"grid-row-end":{values:["auto"]},"grid-row-start":{values:["auto"]},"grid-template-areas":{values:["none"]},"grid-template-columns":{values:["none"]},"grid-template-rows":{values:["none"]},height:{values:["auto","fit-content","min-content","max-content"]},"hyphenate-limit-chars":{values:["auto"]},hyphens:{values:["none","manual","auto"]},"image-rendering":{values:["auto","optimizespeed","optimizequality","-webkit-optimize-contrast","pixelated"]},"initial-letter":{values:["drop","normal","raise"]},"inline-size":{values:["auto"]},isolation:{values:["auto","isolate"]},left:{values:["auto"]},"letter-spacing":{values:["normal"]},"lighting-color":{values:["currentcolor"]},"line-break":{values:["auto","loose","normal","strict","anywhere"]},"line-height":{values:["normal"]},"list-style-image":{values:["none"]},"list-style-position":{values:["outside","inside"]},"list-style-type":{values:["disc","circle","square","disclosure-open","disclosure-closed","decimal","none"]},"margin-block-end":{values:["auto"]},"margin-block-start":{values:["auto"]},"margin-bottom":{values:["auto"]},"margin-inline-end":{values:["auto"]},"margin-inline-start":{values:["auto"]},"margin-left":{values:["auto"]},"margin-right":{values:["auto"]},"margin-top":{values:["auto"]},"marker-end":{values:["none"]},"marker-mid":{values:["none"]},"marker-start":{values:["none"]},"mask-type":{values:["luminance","alpha"]},"math-shift":{values:["normal","compact"]},"math-style":{values:["normal","compact"]},"max-block-size":{values:["none"]},"max-height":{values:["none"]},"max-inline-size":{values:["none"]},"max-width":{values:["none"]},"mix-blend-mode":{values:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"]},"object-fit":{values:["fill","contain","cover","none","scale-down"]},"object-view-box":{values:["none"]},"offset-anchor":{values:["auto"]},"offset-path":{values:["none"]},"offset-position":{values:["auto","normal"]},"offset-rotate":{values:["auto","reverse"]},"origin-trial-test-property":{values:["normal","none"]},"outline-color":{values:["currentcolor"]},"outline-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"outline-width":{values:["thin","medium","thick"]},"overflow-anchor":{values:["visible","none","auto"]},"overflow-clip-margin":{values:["border-box","content-box","padding-box"]},"overflow-wrap":{values:["normal","break-word","anywhere"]},"overflow-x":{values:["visible","hidden","scroll","auto","overlay","clip"]},"overflow-y":{values:["visible","hidden","scroll","auto","overlay","clip"]},overlay:{values:["none","auto"]},"overscroll-behavior-x":{values:["auto","contain","none"]},"overscroll-behavior-y":{values:["auto","contain","none"]},page:{values:["auto"]},"paint-order":{values:["normal","fill","stroke","markers"]},perspective:{values:["none"]},"pointer-events":{values:["none","auto","stroke","fill","painted","visible","visiblestroke","visiblefill","visiblepainted","bounding-box","all"]},position:{values:["static","relative","absolute","fixed","sticky"]},"position-fallback":{values:["none"]},quotes:{values:["auto","none"]},resize:{values:["none","both","horizontal","vertical","block","inline"]},right:{values:["auto"]},"row-gap":{values:["normal"]},rx:{values:["auto"]},ry:{values:["auto"]},"scroll-behavior":{values:["auto","smooth"]},"scroll-padding-block-end":{values:["auto"]},"scroll-padding-block-start":{values:["auto"]},"scroll-padding-bottom":{values:["auto"]},"scroll-padding-inline-end":{values:["auto"]},"scroll-padding-inline-start":{values:["auto"]},"scroll-padding-left":{values:["auto"]},"scroll-padding-right":{values:["auto"]},"scroll-padding-top":{values:["auto"]},"scroll-snap-align":{values:["none","start","end","center"]},"scroll-snap-stop":{values:["normal","always"]},"scroll-snap-type":{values:["none","x","y","block","inline","both","mandatory","proximity"]},"scroll-start-block":{values:["auto","start","end","center","top","bottom","left","right"]},"scroll-start-inline":{values:["auto","start","end","center","top","bottom","left","right"]},"scroll-start-target-block":{values:["none","auto"]},"scroll-start-target-inline":{values:["none","auto"]},"scroll-start-target-x":{values:["none","auto"]},"scroll-start-target-y":{values:["none","auto"]},"scrollbar-color":{values:["auto"]},"scrollbar-gutter":{values:["auto","stable","both-edges"]},"scrollbar-width":{values:["auto","thin","none"]},"shape-margin":{values:["none"]},"shape-outside":{values:["none"]},"shape-rendering":{values:["auto","optimizespeed","crispedges","geometricprecision"]},speak:{values:["none","normal","spell-out","digits","literal-punctuation","no-punctuation"]},"stop-color":{values:["currentcolor"]},"stroke-dasharray":{values:["none"]},"stroke-linecap":{values:["butt","round","square"]},"stroke-linejoin":{values:["miter","bevel","round"]},"table-layout":{values:["auto","fixed"]},"text-align":{values:["left","right","center","justify","-webkit-left","-webkit-right","-webkit-center","start","end"]},"text-align-last":{values:["auto","start","end","left","right","center","justify"]},"text-anchor":{values:["start","middle","end"]},"text-box-trim":{values:["none","start","end","both"]},"text-combine-upright":{values:["none","all"]},"text-decoration-color":{values:["currentcolor"]},"text-decoration-line":{values:["none","underline","overline","line-through","blink","spelling-error","grammar-error"]},"text-decoration-skip-ink":{values:["none","auto"]},"text-decoration-style":{values:["solid","double","dotted","dashed","wavy"]},"text-decoration-thickness":{values:["auto","from-font"]},"text-emphasis-color":{values:["currentcolor"]},"text-orientation":{values:["sideways","mixed","upright"]},"text-overflow":{values:["clip","ellipsis"]},"text-rendering":{values:["auto","optimizespeed","optimizelegibility","geometricprecision"]},"text-shadow":{values:["none"]},"text-size-adjust":{values:["none","auto"]},"text-transform":{values:["capitalize","uppercase","lowercase","none","math-auto"]},"text-underline-offset":{values:["auto"]},"text-underline-position":{values:["auto","from-font","under","left","right"]},"text-wrap":{values:["wrap","nowrap","balance","pretty"]},"toggle-group":{values:["none"]},"toggle-root":{values:["none"]},"toggle-trigger":{values:["none"]},"toggle-visibility":{values:["normal"]},top:{values:["auto"]},"touch-action":{values:["auto","none","pan-x","pan-left","pan-right","pan-y","pan-up","pan-down","pinch-zoom","manipulation"]},transform:{values:["none"]},"transform-box":{values:["fill-box","view-box"]},"transform-style":{values:["flat","preserve-3d"]},"transition-property":{values:["none"]},"transition-timing-function":{values:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"]},"unicode-bidi":{values:["normal","embed","bidi-override","isolate","plaintext","isolate-override"]},"user-select":{values:["auto","none","text","all","contain"]},"vector-effect":{values:["none","non-scaling-stroke"]},"vertical-align":{values:["baseline","sub","super","text-top","text-bottom","middle"]},"view-transition-name":{values:["none"]},visibility:{values:["visible","hidden","collapse"]},"white-space":{values:["normal","pre","pre-wrap","pre-line","nowrap","break-spaces"]},"white-space-collapse":{values:["collapse","preserve","preserve-breaks","break-spaces"]},width:{values:["auto","fit-content","min-content","max-content"]},"will-change":{values:["auto"]},"word-boundary-detection":{values:["normal"]},"word-break":{values:["normal","break-all","keep-all","break-word"]},"word-spacing":{values:["normal"]},"writing-mode":{values:["horizontal-tb","vertical-rl","vertical-lr"]},"z-index":{values:["auto"]}},p=new Map([["-epub-caption-side","caption-side"],["-epub-text-combine","-webkit-text-combine"],["-epub-text-emphasis","text-emphasis"],["-epub-text-emphasis-color","text-emphasis-color"],["-epub-text-emphasis-style","text-emphasis-style"],["-epub-text-orientation","-webkit-text-orientation"],["-epub-text-transform","text-transform"],["-epub-word-break","word-break"],["-epub-writing-mode","-webkit-writing-mode"],["-webkit-align-content","align-content"],["-webkit-align-items","align-items"],["-webkit-align-self","align-self"],["-webkit-alternative-animation-delay","-alternative-animation-delay"],["-webkit-alternative-animation-with-delay-start-end","-alternative-animation-with-delay-start-end"],["-webkit-alternative-animation-with-timeline","-alternative-animation-with-timeline"],["-webkit-animation","animation"],["-webkit-animation-delay","animation-delay"],["-webkit-animation-direction","animation-direction"],["-webkit-animation-duration","animation-duration"],["-webkit-animation-fill-mode","animation-fill-mode"],["-webkit-animation-iteration-count","animation-iteration-count"],["-webkit-animation-name","animation-name"],["-webkit-animation-play-state","animation-play-state"],["-webkit-animation-timing-function","animation-timing-function"],["-webkit-app-region","app-region"],["-webkit-appearance","appearance"],["-webkit-backface-visibility","backface-visibility"],["-webkit-background-clip","background-clip"],["-webkit-background-origin","background-origin"],["-webkit-background-size","background-size"],["-webkit-border-after","border-block-end"],["-webkit-border-after-color","border-block-end-color"],["-webkit-border-after-style","border-block-end-style"],["-webkit-border-after-width","border-block-end-width"],["-webkit-border-before","border-block-start"],["-webkit-border-before-color","border-block-start-color"],["-webkit-border-before-style","border-block-start-style"],["-webkit-border-before-width","border-block-start-width"],["-webkit-border-bottom-left-radius","border-bottom-left-radius"],["-webkit-border-bottom-right-radius","border-bottom-right-radius"],["-webkit-border-end","border-inline-end"],["-webkit-border-end-color","border-inline-end-color"],["-webkit-border-end-style","border-inline-end-style"],["-webkit-border-end-width","border-inline-end-width"],["-webkit-border-radius","border-radius"],["-webkit-border-start","border-inline-start"],["-webkit-border-start-color","border-inline-start-color"],["-webkit-border-start-style","border-inline-start-style"],["-webkit-border-start-width","border-inline-start-width"],["-webkit-border-top-left-radius","border-top-left-radius"],["-webkit-border-top-right-radius","border-top-right-radius"],["-webkit-box-shadow","box-shadow"],["-webkit-box-sizing","box-sizing"],["-webkit-clip-path","clip-path"],["-webkit-column-count","column-count"],["-webkit-column-gap","column-gap"],["-webkit-column-rule","column-rule"],["-webkit-column-rule-color","column-rule-color"],["-webkit-column-rule-style","column-rule-style"],["-webkit-column-rule-width","column-rule-width"],["-webkit-column-span","column-span"],["-webkit-column-width","column-width"],["-webkit-columns","columns"],["-webkit-filter","filter"],["-webkit-flex","flex"],["-webkit-flex-basis","flex-basis"],["-webkit-flex-direction","flex-direction"],["-webkit-flex-flow","flex-flow"],["-webkit-flex-grow","flex-grow"],["-webkit-flex-shrink","flex-shrink"],["-webkit-flex-wrap","flex-wrap"],["-webkit-font-feature-settings","font-feature-settings"],["-webkit-hyphenate-character","hyphenate-character"],["-webkit-justify-content","justify-content"],["-webkit-logical-height","block-size"],["-webkit-logical-width","inline-size"],["-webkit-margin-after","margin-block-end"],["-webkit-margin-before","margin-block-start"],["-webkit-margin-end","margin-inline-end"],["-webkit-margin-start","margin-inline-start"],["-webkit-max-logical-height","max-block-size"],["-webkit-max-logical-width","max-inline-size"],["-webkit-min-logical-height","min-block-size"],["-webkit-min-logical-width","min-inline-size"],["-webkit-opacity","opacity"],["-webkit-order","order"],["-webkit-padding-after","padding-block-end"],["-webkit-padding-before","padding-block-start"],["-webkit-padding-end","padding-inline-end"],["-webkit-padding-start","padding-inline-start"],["-webkit-perspective","perspective"],["-webkit-perspective-origin","perspective-origin"],["-webkit-shape-image-threshold","shape-image-threshold"],["-webkit-shape-margin","shape-margin"],["-webkit-shape-outside","shape-outside"],["-webkit-text-emphasis","text-emphasis"],["-webkit-text-emphasis-color","text-emphasis-color"],["-webkit-text-emphasis-position","text-emphasis-position"],["-webkit-text-emphasis-style","text-emphasis-style"],["-webkit-text-size-adjust","text-size-adjust"],["-webkit-transform","transform"],["-webkit-transform-origin","transform-origin"],["-webkit-transform-style","transform-style"],["-webkit-transition","transition"],["-webkit-transition-delay","transition-delay"],["-webkit-transition-duration","transition-duration"],["-webkit-transition-property","transition-property"],["-webkit-transition-timing-function","transition-timing-function"],["-webkit-user-select","user-select"],["word-wrap","overflow-wrap"]]);class m{#t;#n;#r;#s;#i;#a;#o;#l;#d;#c;constructor(e,n){this.#t=[],this.#n=new Map,this.#r=new Map,this.#s=new Set,this.#i=new Set,this.#a=new Map,this.#o=n;for(let t=0;tCSS.supports(e,t))).sort(m.sortPrefixesToEnd).map((t=>`${e}: ${t}`));this.isSVGProperty(e)||this.#d.push(...t),this.#c.push(...t)}}static sortPrefixesToEnd(e,t){const n=e.startsWith("-webkit-"),r=t.startsWith("-webkit-");return n&&!r?1:!n&&r||et?1:0}allProperties(){return this.#t}aliasesFor(){return this.#o}nameValuePresets(e){return e?this.#c:this.#d}isSVGProperty(e){return e=e.toLowerCase(),this.#i.has(e)}getLonghands(e){return this.#n.get(e)||null}getShorthands(e){return this.#r.get(e)||null}isColorAwareProperty(e){return R.has(e.toLowerCase())||this.isCustomProperty(e.toLowerCase())}isFontFamilyProperty(e){return"font-family"===e.toLowerCase()}isAngleAwareProperty(e){const t=e.toLowerCase();return R.has(t)||x.has(t)}isGridAreaDefiningProperty(e){return"grid"===(e=e.toLowerCase())||"grid-template"===e||"grid-template-areas"===e}isLengthProperty(e){return"line-height"!==(e=e.toLowerCase())&&(w.has(e)||e.startsWith("margin")||e.startsWith("padding")||-1!==e.indexOf("width")||-1!==e.indexOf("height"))}isBezierAwareProperty(e){return e=e.toLowerCase(),C.has(e)||this.isCustomProperty(e)}isFontAwareProperty(e){return e=e.toLowerCase(),T.has(e)||this.isCustomProperty(e)}isCustomProperty(e){return e.startsWith("--")}isShadowProperty(e){return"box-shadow"===(e=e.toLowerCase())||"text-shadow"===e||"-webkit-box-shadow"===e}isStringProperty(e){return"content"===(e=e.toLowerCase())}canonicalPropertyName(e){if(this.isCustomProperty(e))return e;e=e.toLowerCase();const t=this.#o.get(e);if(t)return t;if(!e||e.length<9||"-"!==e.charAt(0))return e;const n=e.match(/(?:-webkit-)(.+)/);return n&&this.#l.has(n[1])?n[1]:e}isCSSPropertyName(e){return!!((e=e.toLowerCase()).startsWith("--")&&e.length>2||e.startsWith("-moz-")||e.startsWith("-ms-")||e.startsWith("-o-")||e.startsWith("-webkit-"))||this.#l.has(e)}isPropertyInherited(e){return(e=e.toLowerCase()).startsWith("--")||this.#s.has(this.canonicalPropertyName(e))||this.#s.has(e)}specificPropertyValues(e){const t=e.replace(/^-webkit-/,""),n=this.#a;let r=n.get(e)||n.get(t);if(!r){r=[];for(const t of L)CSS.supports(e,t)&&r.push(t);n.set(e,r)}return r}getPropertyValues(t){const n=["inherit","initial","revert","unset"];if(t=t.toLowerCase(),n.push(...this.specificPropertyValues(t)),this.isColorAwareProperty(t)){n.push("currentColor");for(const t of e.Color.Nicknames.keys())n.push(t)}return n.sort(m.sortPrefixesToEnd)}propertyUsageWeight(e){return P.get(e)||P.get(this.canonicalPropertyName(e))||0}getValuePreset(e,t){const n=S.get(e);let r=n?n.get(t):null;if(!r)return null;let s=r.length,i=r.length;return r&&(s=r.indexOf("|"),i=r.lastIndexOf("|"),i=s===i?i:i-1,r=r.replace(/\|/g,"")),{text:r,startColumn:s,endColumn:i}}isHighlightPseudoType(e){return"highlight"===e||"selection"===e||"target-text"===e||"grammar-error"===e||"spelling-error"===e}}const f=/(var\(\s*--.*?\))/g,b=/((?:\[[\w\- ]+\]\s*)*(?:"[^"]+"|'[^']+'))[^'"\[]*\[?[^'"\[]*/;let y=null;function v(){if(!y){y=new m(u,p)}return y}const I=new Map([["linear-gradient","linear-gradient(|45deg, black, transparent|)"],["radial-gradient","radial-gradient(|black, transparent|)"],["repeating-linear-gradient","repeating-linear-gradient(|45deg, black, transparent 100px|)"],["repeating-radial-gradient","repeating-radial-gradient(|black, transparent 100px|)"],["url","url(||)"]]),k=new Map([["blur","blur(|1px|)"],["brightness","brightness(|0.5|)"],["contrast","contrast(|0.5|)"],["drop-shadow","drop-shadow(|2px 4px 6px black|)"],["grayscale","grayscale(|1|)"],["hue-rotate","hue-rotate(|45deg|)"],["invert","invert(|1|)"],["opacity","opacity(|0.5|)"],["saturate","saturate(|0.5|)"],["sepia","sepia(|1|)"],["url","url(||)"]]),S=new Map([["filter",k],["backdrop-filter",k],["background",I],["background-image",I],["-webkit-mask-image",I],["transform",new Map([["scale","scale(|1.5|)"],["scaleX","scaleX(|1.5|)"],["scaleY","scaleY(|1.5|)"],["scale3d","scale3d(|1.5, 1.5, 1.5|)"],["rotate","rotate(|45deg|)"],["rotateX","rotateX(|45deg|)"],["rotateY","rotateY(|45deg|)"],["rotateZ","rotateZ(|45deg|)"],["rotate3d","rotate3d(|1, 1, 1, 45deg|)"],["skew","skew(|10deg, 10deg|)"],["skewX","skewX(|10deg|)"],["skewY","skewY(|10deg|)"],["translate","translate(|10px, 10px|)"],["translateX","translateX(|10px|)"],["translateY","translateY(|10px|)"],["translateZ","translateZ(|10px|)"],["translate3d","translate3d(|10px, 10px, 10px|)"],["matrix","matrix(|1, 0, 0, 1, 0, 0|)"],["matrix3d","matrix3d(|1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1|)"],["perspective","perspective(|10px|)"]])]]),w=new Set(["background-position","border-spacing","bottom","font-size","height","left","letter-spacing","max-height","max-width","min-height","min-width","right","text-indent","top","width","word-spacing","grid-row-gap","grid-column-gap","row-gap"]),C=new Set(["animation","animation-timing-function","transition","transition-timing-function","-webkit-animation","-webkit-animation-timing-function","-webkit-transition","-webkit-transition-timing-function"]),T=new Set(["font-size","line-height","font-weight","font-family","letter-spacing"]),R=new Set(["accent-color","background","background-color","background-image","border","border-color","border-image","border-image-source","border-bottom","border-bottom-color","border-left","border-left-color","border-right","border-right-color","border-top","border-top-color","box-shadow","caret-color","color","column-rule","column-rule-color","content","fill","list-style-image","outline","outline-color","stop-color","stroke","text-decoration-color","text-shadow","-webkit-border-after","-webkit-border-after-color","-webkit-border-before","-webkit-border-before-color","-webkit-border-end","-webkit-border-end-color","-webkit-border-start","-webkit-border-start-color","-webkit-box-reflect","-webkit-box-shadow","-webkit-column-rule-color","-webkit-mask","-webkit-mask-box-image","-webkit-mask-box-image-source","-webkit-mask-image","-webkit-tap-highlight-color","-webkit-text-decoration-color","-webkit-text-emphasis","-webkit-text-emphasis-color","-webkit-text-fill-color","-webkit-text-stroke","-webkit-text-stroke-color"]),x=new Set(["-webkit-border-image","transform","-webkit-transform","rotate","filter","-webkit-filter","backdrop-filter","offset","offset-rotate","font-style"]),M={"background-repeat":{values:["repeat","repeat-x","repeat-y","no-repeat","space","round"]},content:{values:["normal","close-quote","no-close-quote","no-open-quote","open-quote"]},"baseline-shift":{values:["baseline"]},"max-height":{values:["min-content","max-content","-webkit-fill-available","fit-content"]},color:{values:["black"]},"background-color":{values:["white"]},"box-shadow":{values:["inset"]},"text-shadow":{values:["0 0 black"]},"-webkit-writing-mode":{values:["horizontal-tb","vertical-rl","vertical-lr"]},"writing-mode":{values:["lr","rl","tb","lr-tb","rl-tb","tb-rl"]},"page-break-inside":{values:["avoid"]},cursor:{values:["-webkit-zoom-in","-webkit-zoom-out","-webkit-grab","-webkit-grabbing"]},"border-width":{values:["medium","thick","thin"]},"border-style":{values:["hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"]},size:{values:["a3","a4","a5","b4","b5","landscape","ledger","legal","letter","portrait"]},overflow:{values:["hidden","visible","overlay","scroll"]},"overscroll-behavior":{values:["contain"]},"text-rendering":{values:["optimizeSpeed","optimizeLegibility","geometricPrecision"]},"text-align":{values:["-webkit-auto","-webkit-match-parent"]},"clip-path":{values:["circle","ellipse","inset","polygon","url"]},"color-interpolation":{values:["sRGB","linearRGB"]},"word-wrap":{values:["normal","break-word"]},"font-weight":{values:["100","200","300","400","500","600","700","800","900"]},"-webkit-text-emphasis":{values:["circle","filled","open","dot","double-circle","triangle","sesame"]},"color-rendering":{values:["optimizeSpeed","optimizeQuality"]},"-webkit-text-combine":{values:["horizontal"]},"text-orientation":{values:["sideways-right"]},outline:{values:["inset","groove","ridge","outset","dotted","dashed","solid","double","medium","thick","thin"]},font:{values:["caption","icon","menu","message-box","small-caption","-webkit-mini-control","-webkit-small-control","-webkit-control","status-bar"]},"dominant-baseline":{values:["text-before-edge","text-after-edge","use-script","no-change","reset-size"]},"-webkit-text-emphasis-position":{values:["over","under"]},"alignment-baseline":{values:["before-edge","after-edge","text-before-edge","text-after-edge","hanging"]},"page-break-before":{values:["left","right","always","avoid"]},"border-image":{values:["repeat","stretch","space","round"]},"text-decoration":{values:["blink","line-through","overline","underline","wavy","double","solid","dashed","dotted"]},"font-family":{values:["serif","sans-serif","cursive","fantasy","monospace","system-ui","emoji","math","fangsong","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","-webkit-body"]},zoom:{values:["normal"]},"max-width":{values:["min-content","max-content","-webkit-fill-available","fit-content"]},"-webkit-font-smoothing":{values:["antialiased","subpixel-antialiased"]},border:{values:["hidden","inset","groove","ridge","outset","dotted","dashed","solid","double","medium","thick","thin"]},"font-variant":{values:["small-caps","normal","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"]},"vertical-align":{values:["top","bottom","-webkit-baseline-middle"]},"page-break-after":{values:["left","right","always","avoid"]},"-webkit-text-emphasis-style":{values:["circle","filled","open","dot","double-circle","triangle","sesame"]},transform:{values:["scale","scaleX","scaleY","scale3d","rotate","rotateX","rotateY","rotateZ","rotate3d","skew","skewX","skewY","translate","translateX","translateY","translateZ","translate3d","matrix","matrix3d","perspective"]},"align-content":{values:["normal","baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end"]},"justify-content":{values:["normal","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right"]},"place-content":{values:["normal","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","baseline"]},"align-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"justify-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","legacy"]},"place-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"align-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"justify-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right"]},"place-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"perspective-origin":{values:["left","center","right","top","bottom"]},"transform-origin":{values:["left","center","right","top","bottom"]},"transition-timing-function":{values:["cubic-bezier","steps"]},"animation-timing-function":{values:["cubic-bezier","steps"]},"-webkit-backface-visibility":{values:["visible","hidden"]},"-webkit-column-break-after":{values:["always","avoid"]},"-webkit-column-break-before":{values:["always","avoid"]},"-webkit-column-break-inside":{values:["avoid"]},"-webkit-column-span":{values:["all"]},"-webkit-column-gap":{values:["normal"]},filter:{values:["url","blur","brightness","contrast","drop-shadow","grayscale","hue-rotate","invert","opacity","saturate","sepia"]},"backdrop-filter":{values:["url","blur","brightness","contrast","drop-shadow","grayscale","hue-rotate","invert","opacity","saturate","sepia"]},"mix-blend-mode":{values:["unset"]},"background-blend-mode":{values:["unset"]},"grid-template-columns":{values:["min-content","max-content"]},"grid-template-rows":{values:["min-content","max-content"]},"grid-auto-flow":{values:["dense"]},background:{values:["repeat","repeat-x","repeat-y","no-repeat","top","bottom","left","right","center","fixed","local","scroll","space","round","border-box","content-box","padding-box","linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"background-image":{values:["linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"background-position":{values:["top","bottom","left","right","center"]},"background-position-x":{values:["left","right","center"]},"background-position-y":{values:["top","bottom","center"]},"background-repeat-x":{values:["repeat","no-repeat"]},"background-repeat-y":{values:["repeat","no-repeat"]},"border-bottom":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-left":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-right":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-top":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"buffered-rendering":{values:["static","dynamic"]},"color-interpolation-filters":{values:["srgb","linearrgb"]},"column-rule":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"flex-flow":{values:["nowrap","row","row-reverse","column","column-reverse","wrap","wrap-reverse"]},height:{values:["-webkit-fill-available"]},"inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"list-style":{values:["outside","inside","disc","circle","square","decimal","decimal-leading-zero","arabic-indic","bengali","cambodian","khmer","devanagari","gujarati","gurmukhi","kannada","lao","malayalam","mongolian","myanmar","oriya","persian","urdu","telugu","tibetan","thai","lower-roman","upper-roman","lower-greek","lower-alpha","lower-latin","upper-alpha","upper-latin","cjk-earthly-branch","cjk-heavenly-stem","ethiopic-halehame","ethiopic-halehame-am","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","hangul","hangul-consonant","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","hebrew","armenian","lower-armenian","upper-armenian","georgian","cjk-ideographic","simp-chinese-formal","simp-chinese-informal","trad-chinese-formal","trad-chinese-informal","hiragana","katakana","hiragana-iroha","katakana-iroha"]},"max-block-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"max-inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-block-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"object-position":{values:["top","bottom","left","right","center"]},"shape-outside":{values:["border-box","content-box","padding-box","margin-box"]},"-webkit-appearance":{values:["checkbox","radio","push-button","square-button","button","inner-spin-button","listbox","media-slider","media-sliderthumb","media-volume-slider","media-volume-sliderthumb","menulist","menulist-button","meter","progress-bar","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","searchfield","searchfield-cancel-button","textfield","textarea"]},"-webkit-border-after":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-after-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-after-width":{values:["medium","thick","thin"]},"-webkit-border-before":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-before-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-before-width":{values:["medium","thick","thin"]},"-webkit-border-end":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-end-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-end-width":{values:["medium","thick","thin"]},"-webkit-border-start":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-start-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-start-width":{values:["medium","thick","thin"]},"-webkit-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-margin-collapse":{values:["collapse","separate","discard"]},"-webkit-mask-box-image":{values:["repeat","stretch","space","round"]},"-webkit-mask-box-image-repeat":{values:["repeat","stretch","space","round"]},"-webkit-mask-clip":{values:["text","border","border-box","content","content-box","padding","padding-box"]},"-webkit-mask-composite":{values:["clear","copy","source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","xor","plus-lighter"]},"-webkit-mask-image":{values:["linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"-webkit-mask-origin":{values:["border","border-box","content","content-box","padding","padding-box"]},"-webkit-mask-position":{values:["top","bottom","left","right","center"]},"-webkit-mask-position-x":{values:["left","right","center"]},"-webkit-mask-position-y":{values:["top","bottom","center"]},"-webkit-mask-repeat":{values:["repeat","repeat-x","repeat-y","no-repeat","space","round"]},"-webkit-mask-size":{values:["contain","cover"]},"-webkit-max-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-max-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-min-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-min-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-perspective-origin-x":{values:["left","right","center"]},"-webkit-perspective-origin-y":{values:["top","bottom","center"]},"-webkit-text-decorations-in-effect":{values:["blink","line-through","overline","underline"]},"-webkit-text-stroke":{values:["medium","thick","thin"]},"-webkit-text-stroke-width":{values:["medium","thick","thin"]},"-webkit-transform-origin-x":{values:["left","right","center"]},"-webkit-transform-origin-y":{values:["top","bottom","center"]},width:{values:["-webkit-fill-available"]}},P=new Map([["align-content",57],["align-items",129],["align-self",55],["animation",175],["animation-delay",114],["animation-direction",113],["animation-duration",137],["animation-fill-mode",132],["animation-iteration-count",124],["animation-name",139],["animation-play-state",104],["animation-timing-function",141],["backface-visibility",123],["background",260],["background-attachment",119],["background-clip",165],["background-color",259],["background-image",246],["background-origin",107],["background-position",237],["background-position-x",108],["background-position-y",93],["background-repeat",234],["background-size",203],["border",263],["border-bottom",233],["border-bottom-color",190],["border-bottom-left-radius",186],["border-bottom-right-radius",185],["border-bottom-style",150],["border-bottom-width",179],["border-collapse",209],["border-color",226],["border-image",89],["border-image-outset",50],["border-image-repeat",49],["border-image-slice",58],["border-image-source",32],["border-image-width",52],["border-left",221],["border-left-color",174],["border-left-style",142],["border-left-width",172],["border-radius",224],["border-right",223],["border-right-color",182],["border-right-style",130],["border-right-width",178],["border-spacing",198],["border-style",206],["border-top",231],["border-top-color",192],["border-top-left-radius",187],["border-top-right-radius",189],["border-top-style",152],["border-top-width",180],["border-width",214],["bottom",227],["box-shadow",213],["box-sizing",216],["caption-side",96],["clear",229],["clip",173],["clip-rule",5],["color",256],["content",219],["counter-increment",111],["counter-reset",110],["cursor",250],["direction",176],["display",262],["empty-cells",99],["fill",140],["fill-opacity",82],["fill-rule",22],["filter",160],["flex",133],["flex-basis",66],["flex-direction",85],["flex-flow",94],["flex-grow",112],["flex-shrink",61],["flex-wrap",68],["float",252],["font",211],["font-family",254],["font-kerning",18],["font-size",264],["font-stretch",77],["font-style",220],["font-variant",161],["font-weight",257],["height",266],["image-rendering",90],["justify-content",127],["left",248],["letter-spacing",188],["line-height",244],["list-style",215],["list-style-image",145],["list-style-position",149],["list-style-type",199],["margin",267],["margin-bottom",241],["margin-left",243],["margin-right",238],["margin-top",253],["mask",20],["max-height",205],["max-width",225],["min-height",217],["min-width",218],["object-fit",33],["opacity",251],["order",117],["orphans",146],["outline",222],["outline-color",153],["outline-offset",147],["outline-style",151],["outline-width",148],["overflow",255],["overflow-wrap",105],["overflow-x",184],["overflow-y",196],["padding",265],["padding-bottom",230],["padding-left",235],["padding-right",232],["padding-top",240],["page",8],["page-break-after",120],["page-break-before",69],["page-break-inside",121],["perspective",92],["perspective-origin",103],["pointer-events",183],["position",261],["quotes",158],["resize",168],["right",245],["shape-rendering",38],["size",64],["speak",118],["src",170],["stop-color",42],["stop-opacity",31],["stroke",98],["stroke-dasharray",36],["stroke-dashoffset",3],["stroke-linecap",30],["stroke-linejoin",21],["stroke-miterlimit",12],["stroke-opacity",34],["stroke-width",87],["table-layout",171],["tab-size",46],["text-align",260],["text-anchor",35],["text-decoration",247],["text-indent",207],["text-overflow",204],["text-rendering",155],["text-shadow",208],["text-transform",202],["top",258],["touch-action",80],["transform",181],["transform-origin",162],["transform-style",86],["transition",193],["transition-delay",134],["transition-duration",135],["transition-property",131],["transition-timing-function",122],["unicode-bidi",156],["unicode-range",136],["vertical-align",236],["visibility",242],["-webkit-appearance",191],["-webkit-backface-visibility",154],["-webkit-background-clip",164],["-webkit-background-origin",40],["-webkit-background-size",163],["-webkit-border-end",9],["-webkit-border-horizontal-spacing",81],["-webkit-border-image",75],["-webkit-border-radius",212],["-webkit-border-start",10],["-webkit-border-start-color",16],["-webkit-border-start-width",13],["-webkit-border-vertical-spacing",43],["-webkit-box-align",101],["-webkit-box-direction",51],["-webkit-box-flex",128],["-webkit-box-ordinal-group",91],["-webkit-box-orient",144],["-webkit-box-pack",106],["-webkit-box-reflect",39],["-webkit-box-shadow",210],["-webkit-column-break-inside",60],["-webkit-column-count",84],["-webkit-column-gap",76],["-webkit-column-rule",25],["-webkit-column-rule-color",23],["-webkit-columns",44],["-webkit-column-span",29],["-webkit-column-width",47],["-webkit-filter",159],["-webkit-font-feature-settings",59],["-webkit-font-smoothing",177],["-webkit-highlight",1],["-webkit-line-break",45],["-webkit-line-clamp",126],["-webkit-margin-after",67],["-webkit-margin-before",70],["-webkit-margin-collapse",14],["-webkit-margin-end",65],["-webkit-margin-start",100],["-webkit-margin-top-collapse",78],["-webkit-mask",19],["-webkit-mask-box-image",72],["-webkit-mask-image",88],["-webkit-mask-position",54],["-webkit-mask-repeat",63],["-webkit-mask-size",79],["-webkit-padding-after",15],["-webkit-padding-before",28],["-webkit-padding-end",48],["-webkit-padding-start",73],["-webkit-print-color-adjust",83],["-webkit-rtl-ordering",7],["-webkit-tap-highlight-color",169],["-webkit-text-emphasis-color",11],["-webkit-text-fill-color",71],["-webkit-text-security",17],["-webkit-text-stroke",56],["-webkit-text-stroke-color",37],["-webkit-text-stroke-width",53],["-webkit-user-drag",95],["-webkit-user-modify",62],["-webkit-user-select",194],["-webkit-writing-mode",4],["white-space",228],["widows",115],["width",268],["will-change",74],["word-break",166],["word-spacing",157],["word-wrap",197],["writing-mode",41],["z-index",239],["zoom",200]]),L=["auto","none"];var E=Object.freeze({__proto__:null,CSSMetadata:m,VariableRegex:f,CustomVariableRegex:/(var\(*--[\w\d]+-([\w]+-[\w]+)\))/g,URLRegex:/url\(\s*('.+?'|".+?"|[^)]+)\s*\)/g,GridAreaRowRegex:b,cssMetadata:v});class A{callFrame;callUID;self;total;id;parent;children;functionName;depth;deoptReason;#h;constructor(e,t){this.callFrame=e,this.callUID=`${e.functionName}@${e.scriptId}:${e.lineNumber}:${e.columnNumber}`,this.self=0,this.total=0,this.id=0,this.functionName=e.functionName,this.parent=null,this.children=[],this.#h=t}get scriptId(){return String(this.callFrame.scriptId)}get url(){return this.callFrame.url}get lineNumber(){return this.callFrame.lineNumber}get columnNumber(){return this.callFrame.columnNumber}setFunctionName(e){null!==e&&(this.functionName=e)}target(){return this.#h}}class O{#e;root;total;maxDepth;constructor(e){this.#e=e||null}initialize(e){this.root=e,this.assignDepthsAndParents(),this.total=this.calculateTotals(this.root)}assignDepthsAndParents(){const e=this.root;e.depth=-1,e.parent=null,this.maxDepth=0;const t=[e];for(;t.length;){const e=t.pop(),n=e.depth+1;n>this.maxDepth&&(this.maxDepth=n);const r=e.children;for(const s of r)s.depth=n,s.parent=e,s.children.length&&t.push(s)}}calculateTotals(e){const t=[e],n=[];for(;t.length;){const e=t.pop();e.total=e.self,n.push(e),t.push(...e.children)}for(;n.length>1;){const e=n.pop();e.parent&&(e.parent.total+=e.total)}return e.total}target(){return this.#e}}var N=Object.freeze({__proto__:null,ProfileNode:A,ProfileTreeModel:O});class F{#u;#g;#p;#m;#f;#b;#y;constructor(e,t,n,r){this.#u=e,this.#g=t,this.#p=n,this.#m={},this.#f=0,this.#b=r||"Medium",this.#y=null}static fromProtocolCookie(e){const t=new F(e.name,e.value,null,e.priority);return t.addAttribute("domain",e.domain),t.addAttribute("path",e.path),e.expires&&t.addAttribute("expires",1e3*e.expires),e.httpOnly&&t.addAttribute("httpOnly"),e.secure&&t.addAttribute("secure"),e.sameSite&&t.addAttribute("sameSite",e.sameSite),"sourcePort"in e&&t.addAttribute("sourcePort",e.sourcePort),"sourceScheme"in e&&t.addAttribute("sourceScheme",e.sourceScheme),"partitionKey"in e&&t.addAttribute("partitionKey",e.partitionKey),"partitionKeyOpaque"in e&&t.addAttribute("partitionKey",""),t.setSize(e.size),t}key(){return(this.domain()||"-")+" "+this.name()+" "+(this.path()||"-")}name(){return this.#u}value(){return this.#g}type(){return this.#p}httpOnly(){return"httponly"in this.#m}secure(){return"secure"in this.#m}sameSite(){return this.#m.samesite}partitionKey(){return this.#m.partitionkey}setPartitionKey(e){this.addAttribute("partitionKey",e)}partitionKeyOpaque(){return""===this.#m.partitionkey}setPartitionKeyOpaque(){this.addAttribute("partitionKey","")}priority(){return this.#b}session(){return!("expires"in this.#m||"max-age"in this.#m)}path(){return this.#m.path}domain(){return this.#m.domain}expires(){return this.#m.expires}maxAge(){return this.#m["max-age"]}sourcePort(){return this.#m.sourceport}sourceScheme(){return this.#m.sourcescheme}size(){return this.#f}url(){if(!this.domain()||!this.path())return null;let e="";const t=this.sourcePort();return t&&80!==t&&443!==t&&(e=`:${this.sourcePort()}`),(this.secure()?"https://":"http://")+this.domain()+e+this.path()}setSize(e){this.#f=e}expiresDate(e){return this.maxAge()?new Date(e.getTime()+1e3*this.maxAge()):this.expires()?new Date(this.expires()):null}addAttribute(e,t){const n=e.toLowerCase();if("priority"===n)this.#b=t;else this.#m[n]=t}setCookieLine(e){this.#y=e}getCookieLine(){return this.#y}matchesSecurityOrigin(e){const t=new URL(e).hostname;return F.isDomainMatch(this.domain(),t)}static isDomainMatch(e,t){return t===e||!(!e||"."!==e[0])&&(e.substr(1)===t||t.length>e.length&&t.endsWith(e))}}var B,D;!function(e){e[e.Request=0]="Request",e[e.Response=1]="Response"}(B||(B={})),function(e){e.Name="name",e.Value="value",e.Size="size",e.Domain="domain",e.Path="path",e.Expires="expires",e.HttpOnly="httpOnly",e.Secure="secure",e.SameSite="sameSite",e.SourceScheme="sourceScheme",e.SourcePort="sourcePort",e.Priority="priority",e.PartitionKey="partitionKey"}(D||(D={}));var U=Object.freeze({__proto__:null,Cookie:F,get Type(){return B},get Attributes(){return D}});class H{#v;#I;#k;#S;#w;#C;#T;constructor(e){e&&(this.#v=e.toLowerCase().replace(/^\./,"")),this.#I=[],this.#S=0}static parseSetCookie(e,t){return new H(t).parseSetCookie(e)}cookies(){return this.#I}parseSetCookie(e){if(!this.initialize(e))return null;for(let e=this.extractKeyValue();e;e=this.extractKeyValue())this.#w?this.#w.addAttribute(e.key,e.value):this.addCookie(e,B.Response),this.advanceAndCheckCookieDelimiter()&&this.flushCookie();return this.flushCookie(),this.#I}initialize(e){return this.#k=e,"string"==typeof e&&(this.#I=[],this.#w=null,this.#C="",this.#S=this.#k.length,!0)}flushCookie(){this.#w&&(this.#w.setSize(this.#S-this.#k.length-this.#T),this.#w.setCookieLine(this.#C.replace("\n",""))),this.#w=null,this.#C=""}extractKeyValue(){if(!this.#k||!this.#k.length)return null;const e=/^[ \t]*([^=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this.#k);if(!e)return console.error("Failed parsing cookie header before: "+this.#k),null;const t=new q(e[1]&&e[1].trim(),e[2]&&e[2].trim(),this.#S-this.#k.length);return this.#C+=e[0],this.#k=this.#k.slice(e[0].length),t}advanceAndCheckCookieDelimiter(){if(!this.#k)return!1;const e=/^\s*[\n;]\s*/.exec(this.#k);return!!e&&(this.#C+=e[0],this.#k=this.#k.slice(e[0].length),null!==e[0].match("\n"))}addCookie(e,t){this.#w&&this.#w.setSize(e.position-this.#T),this.#w="string"==typeof e.value?new F(e.key,e.value,t):new F("",e.key,t),this.#v&&this.#w.addAttribute("domain",this.#v),this.#T=e.position,this.#I.push(this.#w)}}class q{key;value;position;constructor(e,t,n){this.key=e,this.value=t,this.position=n}}var _,z,j=Object.freeze({__proto__:null,CookieParser:H});class W extends a.InspectorBackend.TargetBase{#R;#u;#x;#M;#P;#p;#L;#E;#A;#O;#N;#F;constructor(e,n,r,s,i,a,o,l,d){switch(super(s===_.Node,i,a,l),this.#R=e,this.#u=r,this.#x=t.DevToolsPath.EmptyUrlString,this.#M="",this.#P=0,s){case _.Frame:this.#P=z.Browser|z.Storage|z.DOM|z.JS|z.Log|z.Network|z.Target|z.Tracing|z.Emulation|z.Input|z.Inspector|z.Audits|z.WebAuthn|z.IO|z.Media,i?.type()!==_.Frame&&(this.#P|=z.DeviceEmulation|z.ScreenCapture|z.Security|z.ServiceWorker,d?.url.startsWith("chrome-extension://")&&(this.#P&=~z.Security));break;case _.ServiceWorker:this.#P=z.JS|z.Log|z.Network|z.Target|z.Inspector|z.IO,i?.type()!==_.Frame&&(this.#P|=z.Browser);break;case _.SharedWorker:this.#P=z.JS|z.Log|z.Network|z.Target|z.IO|z.Media|z.Inspector;break;case _.Worker:this.#P=z.JS|z.Log|z.Network|z.Target|z.IO|z.Media|z.Emulation;break;case _.Node:this.#P=z.JS;break;case _.AuctionWorklet:this.#P=z.JS|z.EventBreakpoints;break;case _.Browser:this.#P=z.Target|z.IO;break;case _.Tab:this.#P=z.Target}this.#p=s,this.#L=i,this.#E=n,this.#A=new Map,this.#O=o,this.#N=d}createModels(e){this.#F=!0;const t=Array.from(c.registeredModels.entries());for(const[e,n]of t)n.early&&this.model(e);for(const[n,r]of t)(r.autostart||e.has(n))&&this.model(n);this.#F=!1}id(){return this.#E}name(){return this.#u||this.#M}setName(e){this.#u!==e&&(this.#u=e,this.#R.onNameChange(this))}type(){return this.#p}markAsNodeJSForTest(){super.markAsNodeJSForTest(),this.#p=_.Node}targetManager(){return this.#R}hasAllCapabilities(e){return(this.#P&e)===e}decorateLabel(e){return this.#p===_.Worker||this.#p===_.ServiceWorker?"⚙ "+e:e}parentTarget(){return this.#L}outermostTarget(){let e=null,t=this;do{t.type()!==_.Tab&&t.type()!==_.Browser&&(e=t),t=t.parentTarget()}while(t);return e}dispose(e){super.dispose(e),this.#R.removeTarget(this);for(const e of this.#A.values())e.dispose()}model(e){if(!this.#A.get(e)){const t=c.registeredModels.get(e);if(void 0===t)throw"Model class is not registered @"+(new Error).stack;if((this.#P&t.capabilities)===t.capabilities){const t=new e(this);this.#A.set(e,t),this.#F||this.#R.modelAdded(this,e,t,this.#R.isInScope(this))}}return this.#A.get(e)||null}models(){return this.#A}inspectedURL(){return this.#x}setInspectedURL(n){this.#x=n;const r=e.ParsedURL.ParsedURL.fromString(n);this.#M=r?r.lastPathComponentWithFragment():"#"+this.#E,this.parentTarget()?.type()!==_.Frame&&i.InspectorFrontendHost.InspectorFrontendHostInstance.inspectedURLChanged(n||t.DevToolsPath.EmptyUrlString),this.#R.onInspectedURLChange(this),this.#u||this.#R.onNameChange(this)}async suspend(e){this.#O||(this.#O=!0,await Promise.all(Array.from(this.models().values(),(t=>t.preSuspendModel(e)))),await Promise.all(Array.from(this.models().values(),(t=>t.suspendModel(e)))))}async resume(){this.#O&&(this.#O=!1,await Promise.all(Array.from(this.models().values(),(e=>e.resumeModel()))),await Promise.all(Array.from(this.models().values(),(e=>e.postResumeModel()))))}suspended(){return this.#O}updateTargetInfo(e){this.#N=e}targetInfo(){return this.#N}}!function(e){e.Frame="frame",e.ServiceWorker="service-worker",e.Worker="worker",e.SharedWorker="shared-worker",e.Node="node",e.Browser="browser",e.AuctionWorklet="auction-worklet",e.Tab="tab"}(_||(_={})),function(e){e[e.Browser=1]="Browser",e[e.DOM=2]="DOM",e[e.JS=4]="JS",e[e.Log=8]="Log",e[e.Network=16]="Network",e[e.Target=32]="Target",e[e.ScreenCapture=64]="ScreenCapture",e[e.Tracing=128]="Tracing",e[e.Emulation=256]="Emulation",e[e.Security=512]="Security",e[e.Input=1024]="Input",e[e.Inspector=2048]="Inspector",e[e.DeviceEmulation=4096]="DeviceEmulation",e[e.Storage=8192]="Storage",e[e.ServiceWorker=16384]="ServiceWorker",e[e.Audits=32768]="Audits",e[e.WebAuthn=65536]="WebAuthn",e[e.IO=131072]="IO",e[e.Media=262144]="Media",e[e.EventBreakpoints=524288]="EventBreakpoints",e[e.None=0]="None"}(z||(z={}));var V=Object.freeze({__proto__:null,Target:W,get Type(){return _},get Capability(){return z}});let G;class K extends e.ObjectWrapper.ObjectWrapper{#B;#D;#U;#H;#q;#O;#_;#z;#j;#W;constructor(){super(),this.#B=new Set,this.#D=new Set,this.#U=new t.MapUtilities.Multimap,this.#H=new t.MapUtilities.Multimap,this.#O=!1,this.#_=null,this.#z=null,this.#q=new WeakSet,this.#j=!1,this.#W=new Set}static instance({forceNew:e}={forceNew:!1}){return G&&!e||(G=new K),G}static removeInstance(){G=void 0}onInspectedURLChange(e){this.dispatchEventToListeners($.InspectedURLChanged,e)}onNameChange(e){this.dispatchEventToListeners($.NameChanged,e)}async suspendAllTargets(e){if(this.#O)return;this.#O=!0,this.dispatchEventToListeners($.SuspendStateChanged);const t=Array.from(this.#B.values(),(t=>t.suspend(e)));await Promise.all(t)}async resumeAllTargets(){if(!this.#O)return;this.#O=!1,this.dispatchEventToListeners($.SuspendStateChanged);const e=Array.from(this.#B.values(),(e=>e.resume()));await Promise.all(e)}allTargetsSuspended(){return this.#O}models(e,t){const n=[];for(const r of this.#B){if(t?.scoped&&!this.isInScope(r))continue;const s=r.model(e);s&&n.push(s)}return n}inspectedURL(){const e=this.primaryPageTarget();return e?e.inspectedURL():""}observeModels(e,t,n){const r=this.models(e,n);this.#H.set(e,t),n?.scoped&&this.#q.add(t);for(const e of r)t.modelAdded(e)}unobserveModels(e,t){this.#H.delete(e,t),this.#q.delete(t)}modelAdded(e,t,n,r){for(const e of this.#H.get(t).values())this.#q.has(e)&&!r||e.modelAdded(n)}modelRemoved(e,t,n,r){for(const e of this.#H.get(t).values())this.#q.has(e)&&!r||e.modelRemoved(n)}addModelListener(e,t,n,r,s){const i=e=>{s?.scoped&&!this.isInScope(e)||n.call(r,e)};for(const n of this.models(e))n.addEventListener(t,i);this.#U.set(t,{modelClass:e,thisObject:r,listener:n,wrappedListener:i})}removeModelListener(e,t,n,r){if(!this.#U.has(t))return;let s=null;for(const i of this.#U.get(t))i.modelClass===e&&i.listener===n&&i.thisObject===r&&(s=i.wrappedListener,this.#U.delete(t,i));if(s)for(const n of this.models(e))n.removeEventListener(t,s)}observeTargets(e,t){if(this.#D.has(e))throw new Error("Observer can only be registered once");t?.scoped&&this.#q.add(e);for(const n of this.#B)t?.scoped&&!this.isInScope(n)||e.targetAdded(n);this.#D.add(e)}unobserveTargets(e){this.#D.delete(e),this.#q.delete(e)}createTarget(e,t,n,r,s,i,a,o){const l=new W(this,e,t,n,r,s||"",this.#O,a||null,o);i&&l.pageAgent().invoke_waitForDebugger(),l.createModels(new Set(this.#H.keysArray())),this.#B.add(l);const d=this.isInScope(l);for(const e of[...this.#D])this.#q.has(e)&&!d||e.targetAdded(l);for(const[e,t]of l.models().entries())this.modelAdded(l,e,t,d);for(const e of this.#U.keysArray())for(const t of this.#U.get(e)){const n=l.model(t.modelClass);n&&n.addEventListener(e,t.wrappedListener)}return l!==l.outermostTarget()||l.type()===_.Frame&&l!==this.primaryPageTarget()||this.#j||this.setScopeTarget(l),l}removeTarget(e){if(!this.#B.has(e))return;const t=this.isInScope(e);this.#B.delete(e);for(const r of e.models().keys()){const s=e.models().get(r);n(s),this.modelRemoved(e,r,s,t)}for(const n of[...this.#D])this.#q.has(n)&&!t||n.targetRemoved(e);for(const t of this.#U.keysArray())for(const n of this.#U.get(t)){const r=e.model(n.modelClass);r&&r.removeEventListener(t,n.wrappedListener)}}targets(){return[...this.#B]}targetById(e){return this.targets().find((t=>t.id()===e))||null}rootTarget(){return this.#B.size?this.#B.values().next().value:null}primaryPageTarget(){let e=this.rootTarget();return e?.type()===_.Tab&&(e=this.targets().find((t=>t.parentTarget()===e&&t.type()===_.Frame&&!t.targetInfo()?.subtype?.length))||null),e}browserTarget(){return this.#_}async maybeAttachInitialTarget(){if(!Boolean(o.Runtime.Runtime.queryParam("browserConnection")))return!1;this.#_||(this.#_=new W(this,"main","browser",_.Browser,null,"",!1,null,void 0),this.#_.createModels(new Set(this.#H.keysArray())));const e=await i.InspectorFrontendHost.InspectorFrontendHostInstance.initialTargetId();return this.#_.targetAgent().invoke_autoAttachRelated({targetId:e,waitForDebuggerOnStart:!0}),!0}clearAllTargetsForTest(){this.#B.clear()}isInScope(e){if(!e)return!1;for(function(e){return"source"in e&&e.source instanceof c}(e)&&(e=e.source),e instanceof c&&(e=e.target());e&&e!==this.#z;)e=e.parentTarget();return Boolean(e)&&e===this.#z}setScopeTarget(e){if(e!==this.#z){for(const e of this.targets())if(this.isInScope(e)){for(const t of this.#H.keysArray()){const n=e.models().get(t);if(n)for(const e of[...this.#H.get(t)].filter((e=>this.#q.has(e))))e.modelRemoved(n)}for(const t of[...this.#D].filter((e=>this.#q.has(e))))t.targetRemoved(e)}this.#z=e;for(const e of this.targets())if(this.isInScope(e)){for(const t of[...this.#D].filter((e=>this.#q.has(e))))t.targetAdded(e);for(const[t,n]of e.models().entries())for(const e of[...this.#H.get(t)].filter((e=>this.#q.has(e))))e.modelAdded(n)}for(const e of this.#W)e()}}addScopeChangeListener(e){this.#W.add(e)}removeScopeChangeListener(e){this.#W.delete(e)}scopeTarget(){return this.#z}}var $;!function(e){e.AvailableTargetsChanged="AvailableTargetsChanged",e.InspectedURLChanged="InspectedURLChanged",e.NameChanged="NameChanged",e.SuspendStateChanged="SuspendStateChanged"}($||($={}));var Q=Object.freeze({__proto__:null,TargetManager:K,get Events(){return $},Observer:class{targetAdded(e){}targetRemoved(e){}},SDKModelObserver:class{modelAdded(e){}modelRemoved(e){}}});const X={noContentForWebSocket:"Content for WebSockets is currently not supported",noContentForRedirect:"No content available because this request was redirected",noContentForPreflight:"No content available for preflight request",noThrottling:"No throttling",offline:"Offline",slowG:"Slow 3G",fastG:"Fast 3G",requestWasBlockedByDevtoolsS:'Request was blocked by DevTools: "{PH1}"',crossoriginReadBlockingCorb:"Cross-Origin Read Blocking (CORB) blocked cross-origin response {PH1} with MIME type {PH2}. See https://www.chromestatus.com/feature/5629709824032768 for more details.",sFailedLoadingSS:'{PH1} failed loading: {PH2} "{PH3}".',sFinishedLoadingSS:'{PH1} finished loading: {PH2} "{PH3}".'},J=s.i18n.registerUIStrings("core/sdk/NetworkManager.ts",X),Y=s.i18n.getLocalizedString.bind(void 0,J),Z=s.i18n.getLazilyComputedLocalizedString.bind(void 0,J),ee=new WeakMap,te=new Map([["2g","cellular2g"],["3g","cellular3g"],["4g","cellular4g"],["bluetooth","bluetooth"],["wifi","wifi"],["wimax","wimax"]]);class ne extends c{dispatcher;fetchDispatcher;#V;#G;constructor(t){super(t),this.dispatcher=new ce(this),this.fetchDispatcher=new de(t.fetchAgent(),this),this.#V=t.networkAgent(),t.registerNetworkDispatcher(this.dispatcher),t.registerFetchDispatcher(this.fetchDispatcher),e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()&&this.#V.invoke_setCacheDisabled({cacheDisabled:!0}),this.#V.invoke_enable({maxPostDataSize:le}),this.#V.invoke_setAttachDebugStack({enabled:!0}),this.#G=e.Settings.Settings.instance().createSetting("bypassServiceWorker",!1),this.#G.get()&&this.bypassServiceWorkerChanged(),this.#G.addChangeListener(this.bypassServiceWorkerChanged,this),e.Settings.Settings.instance().moduleSetting("cacheDisabled").addChangeListener(this.cacheDisabledSettingChanged,this)}static forRequest(e){return ee.get(e)||null}static canReplayRequest(t){return Boolean(ee.get(t))&&Boolean(t.backendRequestId())&&!t.isRedirect()&&t.resourceType()===e.ResourceType.resourceTypes.XHR}static replayRequest(e){const t=ee.get(e),n=e.backendRequestId();t&&n&&!e.isRedirect()&&t.#V.invoke_replayXHR({requestId:n})}static async searchInRequest(e,t,n,r){const s=ne.forRequest(e),i=e.backendRequestId();if(!s||!i||e.isRedirect())return[];return(await s.#V.invoke_searchInResponseBody({requestId:i,query:t,caseSensitive:n,isRegex:r})).result||[]}static async requestContentData(t){if(t.resourceType()===e.ResourceType.resourceTypes.WebSocket)return{error:Y(X.noContentForWebSocket),content:null,encoded:!1};if(t.finished||await t.once(Te.FinishedLoading),t.isRedirect())return{error:Y(X.noContentForRedirect),content:null,encoded:!1};if(t.isPreflightRequest())return{error:Y(X.noContentForPreflight),content:null,encoded:!1};const n=ne.forRequest(t);if(!n)return{error:"No network manager for request",content:null,encoded:!1};const r=t.backendRequestId();if(!r)return{error:"No backend request id for request",content:null,encoded:!1};const s=await n.#V.invoke_getResponseBody({requestId:r}),i=s.getError()||null;return{error:i,content:i?null:s.body,encoded:s.base64Encoded}}static async requestPostData(e){const t=ne.forRequest(e);if(!t)return console.error("No network manager for request"),null;const n=e.backendRequestId();if(!n)return console.error("No backend request id for request"),null;try{const{postData:e}=await t.#V.invoke_getRequestPostData({requestId:n});return e}catch(e){return e.message}}static connectionType(e){if(!e.download&&!e.upload)return"none";const t="function"==typeof e.title?e.title().toLowerCase():e.title.toLowerCase();for(const[e,n]of te)if(t.includes(e))return n;return"other"}static lowercaseHeaders(e){const t={};for(const n in e)t[n.toLowerCase()]=e[n];return t}requestForURL(e){return this.dispatcher.requestForURL(e)}requestForId(e){return this.dispatcher.requestForId(e)}requestForLoaderId(e){return this.dispatcher.requestForLoaderId(e)}cacheDisabledSettingChanged({data:e}){this.#V.invoke_setCacheDisabled({cacheDisabled:e})}dispose(){e.Settings.Settings.instance().moduleSetting("cacheDisabled").removeChangeListener(this.cacheDisabledSettingChanged,this)}bypassServiceWorkerChanged(){this.#V.invoke_setBypassServiceWorker({bypass:this.#G.get()})}async getSecurityIsolationStatus(e){const t=await this.#V.invoke_getSecurityIsolationStatus({frameId:e??void 0});return t.getError()?null:t.status}async enableReportingApi(e=!0){return this.#V.invoke_enableReportingApi({enable:e})}async loadNetworkResource(e,t,n){const r=await this.#V.invoke_loadNetworkResource({frameId:e??void 0,url:t,options:n});if(r.getError())throw new Error(r.getError());return r.resource}clearRequests(){this.dispatcher.clearRequests()}}var re;!function(e){e.RequestStarted="RequestStarted",e.RequestUpdated="RequestUpdated",e.RequestFinished="RequestFinished",e.RequestUpdateDropped="RequestUpdateDropped",e.ResponseReceived="ResponseReceived",e.MessageGenerated="MessageGenerated",e.RequestRedirected="RequestRedirected",e.LoadingFinished="LoadingFinished",e.ReportingApiReportAdded="ReportingApiReportAdded",e.ReportingApiReportUpdated="ReportingApiReportUpdated",e.ReportingApiEndpointsChangedForOrigin="ReportingApiEndpointsChangedForOrigin"}(re||(re={}));const se={title:Z(X.noThrottling),i18nTitleKey:X.noThrottling,download:-1,upload:-1,latency:0},ie={title:Z(X.offline),i18nTitleKey:X.offline,download:0,upload:0,latency:0},ae={title:Z(X.slowG),i18nTitleKey:X.slowG,download:5e4,upload:5e4,latency:2e3},oe={title:Z(X.fastG),i18nTitleKey:X.fastG,download:18e4,upload:84375,latency:562.5},le=65536;class de{#K;#$;constructor(e,t){this.#K=e,this.#$=t}requestPaused({requestId:e,request:t,resourceType:n,responseStatusCode:r,responseHeaders:s,networkId:i}){const a=i?this.#$.requestForId(i):null;0===a?.originalResponseHeaders.length&&s&&(a.originalResponseHeaders=s),ue.instance().requestIntercepted(new ge(this.#K,t,n,e,a,r,s))}authRequired({}){}}class ce{#$;#Q;#X;#J;#Y;#Z;constructor(e){this.#$=e,this.#Q=new Map,this.#X=new Map,this.#J=new Map,this.#Y=new Map,this.#Z=new Map,ue.instance().addEventListener(ue.Events.RequestIntercepted,this.#ee.bind(this))}#ee(e){const t=this.requestForId(e.data);t&&t.setWasIntercepted(!0)}headersMapToHeadersArray(e){const t=[];for(const n in e){const r=e[n].split("\n");for(let e=0;e=0&&t.setTransferSize(n.encodedDataLength),n.requestHeaders&&!t.hasExtraRequestInfo()&&(t.setRequestHeaders(this.headersMapToHeadersArray(n.requestHeaders)),t.setRequestHeadersText(n.requestHeadersText||"")),t.connectionReused=n.connectionReused,t.connectionId=String(n.connectionId),n.remoteIPAddress&&t.setRemoteAddress(n.remoteIPAddress,n.remotePort||-1),n.fromServiceWorker&&(t.fetchedViaServiceWorker=!0),n.fromDiskCache&&t.setFromDiskCache(),n.fromPrefetchCache&&t.setFromPrefetchCache(),n.cacheStorageCacheName&&t.setResponseCacheStorageCacheName(n.cacheStorageCacheName),n.responseTime&&t.setResponseRetrievalTime(new Date(n.responseTime)),t.timing=n.timing,t.protocol=n.protocol||"",t.alternateProtocolUsage=n.alternateProtocolUsage,n.serviceWorkerResponseSource&&t.setServiceWorkerResponseSource(n.serviceWorkerResponseSource),t.setSecurityState(n.securityState),n.securityDetails&&t.setSecurityDetails(n.securityDetails);const r=e.ResourceType.ResourceType.fromMimeTypeOverride(t.mimeType);r&&t.setResourceType(r)}requestForId(e){return this.#Q.get(e)||null}requestForURL(e){return this.#X.get(e)||null}requestForLoaderId(e){return this.#J.get(e)||null}resourceChangedPriority({requestId:e,newPriority:t}){const n=this.#Q.get(e);n&&n.setPriority(t)}signedExchangeReceived({requestId:t,info:n}){let r=this.#Q.get(t);(r||(r=this.#X.get(n.outerResponse.url),r))&&(r.setSignedExchangeInfo(n),r.setResourceType(e.ResourceType.resourceTypes.SignedExchange),this.updateNetworkRequestWithResponse(r,n.outerResponse),this.updateNetworkRequest(r),this.#$.dispatchEventToListeners(re.ResponseReceived,{request:r,response:n.outerResponse}))}requestWillBeSent({requestId:t,loaderId:n,documentURL:r,request:s,timestamp:i,wallTime:a,initiator:o,redirectResponse:l,type:d,frameId:c,hasUserGesture:h}){let u=this.#Q.get(t);if(u){if(!l)return;u.signedExchangeInfo()||this.responseReceived({requestId:t,loaderId:n,timestamp:i,type:d||"Other",response:l,hasExtraInfo:!1,frameId:c}),u=this.appendRedirect(t,i,s.url),this.#$.dispatchEventToListeners(re.RequestRedirected,u)}else u=Me.create(t,s.url,r,c??null,n,o,h),ee.set(u,this.#$);u.hasNetworkData=!0,this.updateNetworkRequestWithRequest(u,s),u.setIssueTime(i,a),u.setResourceType(d?e.ResourceType.resourceTypes[d]:e.ResourceType.resourceTypes.Other),s.trustTokenParams&&u.setTrustTokenParams(s.trustTokenParams);const g=this.#Z.get(t);g&&(u.setTrustTokenOperationDoneEvent(g),this.#Z.delete(t)),this.getExtraInfoBuilder(t).addRequest(u),this.startNetworkRequest(u,s)}requestServedFromCache({requestId:e}){const t=this.#Q.get(e);t&&t.setFromMemoryCache()}responseReceived({requestId:t,loaderId:n,timestamp:r,type:s,response:i,frameId:a}){const o=this.#Q.get(t),l=ne.lowercaseHeaders(i.headers);if(o)o.responseReceivedTime=r,o.setResourceType(e.ResourceType.resourceTypes[s]),this.updateNetworkRequestWithResponse(o,i),this.updateNetworkRequest(o),this.#$.dispatchEventToListeners(re.ResponseReceived,{request:o,response:i});else{const e=l["last-modified"],t={url:i.url,frameId:a??null,loaderId:n,resourceType:s,mimeType:i.mimeType,lastModified:e?new Date(e):null};this.#$.dispatchEventToListeners(re.RequestUpdateDropped,t)}}dataReceived({requestId:e,timestamp:t,dataLength:n,encodedDataLength:r}){let s=this.#Q.get(e);s||(s=this.maybeAdoptMainResourceRequest(e)),s&&(s.resourceSize+=n,-1!==r&&s.increaseTransferSize(r),s.endTime=t,this.updateNetworkRequest(s))}loadingFinished({requestId:e,timestamp:t,encodedDataLength:n,shouldReportCorbBlocking:r}){let s=this.#Q.get(e);s||(s=this.maybeAdoptMainResourceRequest(e)),s&&(this.getExtraInfoBuilder(e).finished(),this.finishNetworkRequest(s,t,n,r),this.#$.dispatchEventToListeners(re.LoadingFinished,s))}loadingFailed({requestId:t,timestamp:n,type:r,errorText:s,canceled:i,blockedReason:a,corsErrorStatus:o}){const l=this.#Q.get(t);if(l){if(l.failed=!0,l.setResourceType(e.ResourceType.resourceTypes[r]),l.canceled=Boolean(i),a&&(l.setBlockedReason(a),"inspector"===a)){const e=Y(X.requestWasBlockedByDevtoolsS,{PH1:l.url()});this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t,warning:!0})}o&&l.setCorsErrorStatus(o),l.localizedFailDescription=s,this.getExtraInfoBuilder(t).finished(),this.finishNetworkRequest(l,n,-1)}}webSocketCreated({requestId:t,url:n,initiator:r}){const s=Me.createForWebSocket(t,n,r);ee.set(s,this.#$),s.setResourceType(e.ResourceType.resourceTypes.WebSocket),this.startNetworkRequest(s,null)}webSocketWillSendHandshakeRequest({requestId:e,timestamp:t,wallTime:n,request:r}){const s=this.#Q.get(e);s&&(s.requestMethod="GET",s.setRequestHeaders(this.headersMapToHeadersArray(r.headers)),s.setIssueTime(t,n),this.updateNetworkRequest(s))}webSocketHandshakeResponseReceived({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.statusCode=n.status,r.statusText=n.statusText,r.responseHeaders=this.headersMapToHeadersArray(n.headers),r.responseHeadersText=n.headersText||"",n.requestHeaders&&r.setRequestHeaders(this.headersMapToHeadersArray(n.requestHeaders)),n.requestHeadersText&&r.setRequestHeadersText(n.requestHeadersText),r.responseReceivedTime=t,r.protocol="websocket",this.updateNetworkRequest(r))}webSocketFrameReceived({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrame(n,t,!1),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketFrameSent({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrame(n,t,!0),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketFrameError({requestId:e,timestamp:t,errorMessage:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrameError(n,t),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketClosed({requestId:e,timestamp:t}){const n=this.#Q.get(e);n&&this.finishNetworkRequest(n,t,-1)}eventSourceMessageReceived({requestId:e,timestamp:t,eventName:n,eventId:r,data:s}){const i=this.#Q.get(e);i&&i.addEventSourceMessage(t,n,r,s)}requestIntercepted({}){}requestWillBeSentExtraInfo({requestId:e,associatedCookies:t,headers:n,clientSecurityState:r,connectTiming:s,siteHasCookieInOtherPartition:i}){const a=[],o=[];for(const{blockedReasons:e,cookie:n}of t)0===e.length?o.push(F.fromProtocolCookie(n)):a.push({blockedReasons:e,cookie:F.fromProtocolCookie(n)});const l={blockedRequestCookies:a,includedRequestCookies:o,requestHeaders:this.headersMapToHeadersArray(n),clientSecurityState:r,connectTiming:s,siteHasCookieInOtherPartition:i};this.getExtraInfoBuilder(e).addRequestExtraInfo(l)}responseReceivedExtraInfo({requestId:e,blockedCookies:t,headers:n,headersText:r,resourceIPAddressSpace:s,statusCode:i,cookiePartitionKey:a,cookiePartitionKeyOpaque:o}){const l={blockedResponseCookies:t.map((e=>({blockedReasons:e.blockedReasons,cookieLine:e.cookieLine,cookie:e.cookie?F.fromProtocolCookie(e.cookie):null}))),responseHeaders:this.headersMapToHeadersArray(n),responseHeadersText:r,resourceIPAddressSpace:s,statusCode:i,cookiePartitionKey:a,cookiePartitionKeyOpaque:o};this.getExtraInfoBuilder(e).addResponseExtraInfo(l)}getExtraInfoBuilder(e){let t;return this.#Y.has(e)?t=this.#Y.get(e):(t=new pe,this.#Y.set(e,t)),t}appendRedirect(e,t,n){const r=this.#Q.get(e);if(!r)throw new Error(`Could not find original network request for ${e}`);let s=0;for(let e=r.redirectSource();e;e=e.redirectSource())s++;r.markAsRedirect(s),this.finishNetworkRequest(r,t,-1);const i=Me.create(e,n,r.documentURL,r.frameId,r.loaderId,r.initiator(),r.hasUserGesture()??void 0);return ee.set(i,this.#$),i.setRedirectSource(r),r.setRedirectDestination(i),i}maybeAdoptMainResourceRequest(e){const t=ue.instance().inflightMainResourceRequests.get(e);if(!t)return null;const n=ne.forRequest(t).dispatcher;n.#Q.delete(e),n.#X.delete(t.url());const r=t.loaderId;r&&n.#J.delete(r);const s=n.#Y.get(e);return n.#Y.delete(e),this.#Q.set(e,t),this.#X.set(t.url(),t),r&&this.#J.set(r,t),s&&this.#Y.set(e,s),ee.set(t,this.#$),t}startNetworkRequest(e,t){this.#Q.set(e.requestId(),e),this.#X.set(e.url(),e);const n=e.loaderId;n&&this.#J.set(n,e),e.loaderId===e.requestId()&&ue.instance().inflightMainResourceRequests.set(e.requestId(),e),this.#$.dispatchEventToListeners(re.RequestStarted,{request:e,originalRequest:t})}updateNetworkRequest(e){this.#$.dispatchEventToListeners(re.RequestUpdated,e)}finishNetworkRequest(t,n,r,s){if(t.endTime=n,t.finished=!0,r>=0){const e=t.redirectSource();e&&e.signedExchangeInfo()?(t.setTransferSize(0),e.setTransferSize(r),this.updateNetworkRequest(e)):t.setTransferSize(r)}if(this.#$.dispatchEventToListeners(re.RequestFinished,t),ue.instance().inflightMainResourceRequests.delete(t.requestId()),s){const e=Y(X.crossoriginReadBlockingCorb,{PH1:t.url(),PH2:t.mimeType});this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t.requestId(),warning:!0})}if(e.Settings.Settings.instance().moduleSetting("monitoringXHREnabled").get()&&t.resourceType().category()===e.ResourceType.resourceCategories.XHR){let e;const n=t.failed||t.hasErrorStatusCode();e=Y(n?X.sFailedLoadingSS:X.sFinishedLoadingSS,{PH1:t.resourceType().title(),PH2:t.requestMethod,PH3:t.url()}),this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t.requestId(),warning:!1})}}clearRequests(){for(const[e,t]of this.#Q)t.finished&&this.#Q.delete(e);for(const[e,t]of this.#X)t.finished&&this.#X.delete(e);for(const[e,t]of this.#J)t.finished&&this.#J.delete(e);for(const[e,t]of this.#Y)t.isFinished()&&this.#Y.delete(e)}webTransportCreated({transportId:t,url:n,timestamp:r,initiator:s}){const i=Me.createForWebSocket(t,n,s);i.hasNetworkData=!0,ee.set(i,this.#$),i.setResourceType(e.ResourceType.resourceTypes.WebTransport),i.setIssueTime(r,0),this.startNetworkRequest(i,null)}webTransportConnectionEstablished({transportId:e,timestamp:t}){const n=this.#Q.get(e);n&&(n.responseReceivedTime=t,n.endTime=t+.001,this.updateNetworkRequest(n))}webTransportClosed({transportId:e,timestamp:t}){const n=this.#Q.get(e);n&&(n.endTime=t,this.finishNetworkRequest(n,t,0))}trustTokenOperationDone(e){const t=this.#Q.get(e.requestId);t?t.setTrustTokenOperationDoneEvent(e):this.#Z.set(e.requestId,e)}subresourceWebBundleMetadataReceived({requestId:e,urls:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInfo({resourceUrls:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleMetadataError({requestId:e,errorMessage:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInfo({errorMessage:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleInnerResponseParsed({innerRequestId:e,bundleRequestId:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInnerRequestInfo({bundleRequestId:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleInnerResponseError({innerRequestId:e,errorMessage:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInnerRequestInfo({errorMessage:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}reportingApiReportAdded(e){this.#$.dispatchEventToListeners(re.ReportingApiReportAdded,e.report)}reportingApiReportUpdated(e){this.#$.dispatchEventToListeners(re.ReportingApiReportUpdated,e.report)}reportingApiEndpointsChangedForOrigin(e){this.#$.dispatchEventToListeners(re.ReportingApiEndpointsChangedForOrigin,e)}createNetworkRequest(e,t,n,r,s,i){const a=Me.create(e,r,s,t,n,i);return ee.set(a,this.#$),a}}let he;class ue extends e.ObjectWrapper.ObjectWrapper{#te;#ne;#re;#se;#ie;inflightMainResourceRequests;#ae;#oe;#le;#de;#ce;#he;#ue;#ge;constructor(){super(),this.#te="",this.#ne=null,this.#re=null,this.#se=new Set,this.#ie=new Set,this.inflightMainResourceRequests=new Map,this.#ae=se,this.#oe=null,this.#le=e.Settings.Settings.instance().moduleSetting("requestBlockingEnabled"),this.#de=e.Settings.Settings.instance().createSetting("networkBlockedPatterns",[]),this.#ce=[],this.updateBlockedPatterns(),this.#he=new t.MapUtilities.Multimap,K.instance().observeModels(ne,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return he&&!t||(he=new ue),he}static dispose(){he=null}static getChromeVersion(){const e=navigator.userAgent.match(/(?:^|\W)(?:Chrome|HeadlessChrome)\/(\S+)/);return e&&e.length>1?e[1]:""}static patchUserAgentWithChromeVersion(e){const n=ue.getChromeVersion();if(n.length>0){const r=n.split(".",1)[0]+".0.100.0";return t.StringUtilities.sprintf(e,n,r)}return e}static patchUserAgentMetadataWithChromeVersion(e){if(!e.brands)return;const n=ue.getChromeVersion();if(0===n.length)return;const r=n.split(".",1)[0];for(const n of e.brands)n.version.includes("%s")&&(n.version=t.StringUtilities.sprintf(n.version,r));e.fullVersion&&e.fullVersion.includes("%s")&&(e.fullVersion=t.StringUtilities.sprintf(e.fullVersion,n))}modelAdded(e){const t=e.target().networkAgent(),n=e.target().fetchAgent();this.#ue&&t.invoke_setExtraHTTPHeaders({headers:this.#ue}),this.currentUserAgent()&&t.invoke_setUserAgentOverride({userAgent:this.currentUserAgent(),userAgentMetadata:this.#ne||void 0}),this.#ce.length&&t.invoke_setBlockedURLs({urls:this.#ce}),this.isIntercepting()&&n.invoke_enable({patterns:this.#he.valuesArray()}),null===this.#re?t.invoke_clearAcceptedEncodingsOverride():t.invoke_setAcceptedEncodings({encodings:this.#re}),this.#se.add(t),this.#ie.add(n),this.isThrottling()&&this.updateNetworkConditions(t)}modelRemoved(e){for(const t of this.inflightMainResourceRequests){ne.forRequest(t[1])===e&&this.inflightMainResourceRequests.delete(t[0])}this.#se.delete(e.target().networkAgent()),this.#ie.delete(e.target().fetchAgent())}isThrottling(){return this.#ae.download>=0||this.#ae.upload>=0||this.#ae.latency>0}isOffline(){return!this.#ae.download&&!this.#ae.upload}setNetworkConditions(e){this.#ae=e;for(const e of this.#se)this.updateNetworkConditions(e);this.dispatchEventToListeners(ue.Events.ConditionsChanged)}networkConditions(){return this.#ae}updateNetworkConditions(e){const t=this.#ae;this.isThrottling()?e.invoke_emulateNetworkConditions({offline:this.isOffline(),latency:t.latency,downloadThroughput:t.download<0?0:t.download,uploadThroughput:t.upload<0?0:t.upload,connectionType:ne.connectionType(t)}):e.invoke_emulateNetworkConditions({offline:!1,latency:0,downloadThroughput:0,uploadThroughput:0})}setExtraHTTPHeaders(e){this.#ue=e;for(const e of this.#se)e.invoke_setExtraHTTPHeaders({headers:this.#ue})}currentUserAgent(){return this.#ge?this.#ge:this.#te}updateUserAgentOverride(){const e=this.currentUserAgent();for(const t of this.#se)t.invoke_setUserAgentOverride({userAgent:e,userAgentMetadata:this.#ne||void 0})}setUserAgentOverride(e,t){const n=this.#te!==e;this.#te=e,this.#ge?this.#ne=null:(this.#ne=t,this.updateUserAgentOverride()),n&&this.dispatchEventToListeners(ue.Events.UserAgentChanged)}userAgentOverride(){return this.#te}setCustomUserAgentOverride(e,t=null){this.#ge=e,this.#ne=t,this.updateUserAgentOverride()}setCustomAcceptedEncodingsOverride(e){this.#re=e,this.updateAcceptedEncodingsOverride(),this.dispatchEventToListeners(ue.Events.AcceptedEncodingsChanged)}clearCustomAcceptedEncodingsOverride(){this.#re=null,this.updateAcceptedEncodingsOverride(),this.dispatchEventToListeners(ue.Events.AcceptedEncodingsChanged)}isAcceptedEncodingOverrideSet(){return null!==this.#re}updateAcceptedEncodingsOverride(){const e=this.#re;for(const t of this.#se)null===e?t.invoke_clearAcceptedEncodingsOverride():t.invoke_setAcceptedEncodings({encodings:e})}blockedPatterns(){return this.#de.get().slice()}blockingEnabled(){return this.#le.get()}isBlocking(){return Boolean(this.#ce.length)}setBlockedPatterns(e){this.#de.set(e),this.updateBlockedPatterns(),this.dispatchEventToListeners(ue.Events.BlockedPatternsChanged)}setBlockingEnabled(e){this.#le.get()!==e&&(this.#le.set(e),this.updateBlockedPatterns(),this.dispatchEventToListeners(ue.Events.BlockedPatternsChanged))}updateBlockedPatterns(){const e=[];if(this.#le.get())for(const t of this.#de.get())t.enabled&&e.push(t.url);if(e.length||this.#ce.length){this.#ce=e;for(const e of this.#se)e.invoke_setBlockedURLs({urls:this.#ce})}}isIntercepting(){return Boolean(this.#he.size)}setInterceptionHandlerForPatterns(e,t){this.#he.deleteAll(t);for(const n of e)this.#he.set(t,n);return this.updateInterceptionPatternsOnNextTick()}updateInterceptionPatternsOnNextTick(){return this.#oe||(this.#oe=Promise.resolve().then(this.updateInterceptionPatterns.bind(this))),this.#oe}async updateInterceptionPatterns(){e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()||e.Settings.Settings.instance().moduleSetting("cacheDisabled").set(!0),this.#oe=null;const t=[];for(const e of this.#ie)t.push(e.invoke_enable({patterns:this.#he.valuesArray()}));this.dispatchEventToListeners(ue.Events.InterceptorsChanged),await Promise.all(t)}async requestIntercepted(e){for(const t of this.#he.keysArray())if(await t(e),e.hasResponded()&&e.networkRequest)return void this.dispatchEventToListeners(ue.Events.RequestIntercepted,e.networkRequest.requestId());e.hasResponded()||e.continueRequestWithoutChange()}clearBrowserCache(){for(const e of this.#se)e.invoke_clearBrowserCache()}clearBrowserCookies(){for(const e of this.#se)e.invoke_clearBrowserCookies()}async getCertificate(e){const t=K.instance().primaryPageTarget();if(!t)return[];const n=await t.networkAgent().invoke_getCertificate({origin:e});return n?n.tableNames:[]}async loadResource(t){const n={},r=this.currentUserAgent();r&&(n["User-Agent"]=r),e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()&&(n["Cache-Control"]="no-cache");const s=e.Settings.Settings.instance().moduleSetting("network.enable-remote-file-loading").get();return new Promise((e=>i.ResourceLoader.load(t,n,((t,n,r,s)=>{e({success:t,content:r,errorDescription:s})}),s)))}}!function(e){let t;!function(e){e.BlockedPatternsChanged="BlockedPatternsChanged",e.ConditionsChanged="ConditionsChanged",e.UserAgentChanged="UserAgentChanged",e.InterceptorsChanged="InterceptorsChanged",e.AcceptedEncodingsChanged="AcceptedEncodingsChanged",e.RequestIntercepted="RequestIntercepted",e.RequestFulfilled="RequestFulfilled"}(t=e.Events||(e.Events={}))}(ue||(ue={}));class ge{#K;#pe;request;resourceType;responseStatusCode;responseHeaders;requestId;networkRequest;constructor(e,t,n,r,s,i,a){this.#K=e,this.#pe=!1,this.request=t,this.resourceType=n,this.responseStatusCode=i,this.responseHeaders=a,this.requestId=r,this.networkRequest=s}hasResponded(){return this.#pe}static mergeSetCookieHeaders(e,t){const n=e=>{const t=new Map;for(const n of e){const e=n.value.match(/^([a-zA-Z0-9!#$%&'*+.^_`|~-]+=)(.*)$/);e?t.has(e[1])?t.get(e[1])?.push(n.value):t.set(e[1],[n.value]):t.has(n.value)?t.get(n.value)?.push(n.value):t.set(n.value,[n.value])}return t},r=n(e),s=n(t),i=[];for(const[e,t]of r)if(s.has(e))for(const t of s.get(e)||[])i.push({name:"set-cookie",value:t});else for(const e of t)i.push({name:"set-cookie",value:e});for(const[e,t]of s)if(!r.has(e))for(const e of t)i.push({name:"set-cookie",value:e});return i}async continueRequestWithContent(e,t,n,r){this.#pe=!0;const s=t?await e.text():await async function(e){const t=new FileReader,n=new Promise((e=>{t.onloadend=e}));if(t.readAsDataURL(e),await n,t.error)return console.error("Could not convert blob to base64.",t.error),"";const r=t.result;if(null==r||"string"!=typeof r)return console.error("Could not convert blob to base64."),"";return r.substring(r.indexOf(",")+1)}(e),i=r?200:this.responseStatusCode||200;if(this.networkRequest){const e=this.networkRequest?.originalResponseHeaders.filter((e=>"set-cookie"===e.name))||[],t=n.filter((e=>"set-cookie"===e.name));this.networkRequest.setCookieHeaders=ge.mergeSetCookieHeaders(e,t)}this.#K.invoke_fulfillRequest({requestId:this.requestId,responseCode:i,body:s,responseHeaders:n}),ue.instance().dispatchEventToListeners(ue.Events.RequestFulfilled,this.request.url)}continueRequestWithoutChange(){console.assert(!this.#pe),this.#pe=!0,this.#K.invoke_continueRequest({requestId:this.requestId})}continueRequestWithError(e){console.assert(!this.#pe),this.#pe=!0,this.#K.invoke_failRequest({requestId:this.requestId,errorReason:e})}async responseBody(){const e=await this.#K.invoke_getResponseBody({requestId:this.requestId}),t=e.getError()||null;return{error:t,content:t?null:e.body,encoded:e.base64Encoded}}isRedirect(){return void 0!==this.responseStatusCode&&this.responseStatusCode>=300&&this.responseStatusCode<400}}class pe{#me;#fe;#be;#ye;#ve;#Ie;constructor(){this.#me=[],this.#fe=[],this.#be=[],this.#ye=!1,this.#ve=null,this.#Ie=null}addRequest(e){this.#me.push(e),this.sync(this.#me.length-1)}addRequestExtraInfo(e){this.#fe.push(e),this.sync(this.#fe.length-1)}addResponseExtraInfo(e){this.#be.push(e),this.sync(this.#be.length-1)}setWebBundleInfo(e){this.#ve=e,this.updateFinalRequest()}setWebBundleInnerRequestInfo(e){this.#Ie=e,this.updateFinalRequest()}finished(){this.#ye=!0,this.updateFinalRequest()}isFinished(){return this.#ye}sync(e){const t=this.#me[e];if(!t)return;const n=this.#fe[e];n&&(t.addExtraRequestInfo(n),this.#fe[e]=null);const r=this.#be[e];r&&(t.addExtraResponseInfo(r),this.#be[e]=null)}finalRequest(){return this.#ye&&this.#me[this.#me.length-1]||null}updateFinalRequest(){if(!this.#ye)return;const e=this.finalRequest();e?.setWebBundleInfo(this.#ve),e?.setWebBundleInnerRequestInfo(this.#Ie)}}c.register(ne,{capabilities:z.Network,autostart:!0});var me=Object.freeze({__proto__:null,NetworkManager:ne,get Events(){return re},NoThrottlingConditions:se,OfflineConditions:ie,Slow3GConditions:ae,Fast3GConditions:oe,FetchDispatcher:de,NetworkDispatcher:ce,get MultitargetNetworkManager(){return ue},InterceptedRequest:ge,ConditionsSerializer:class{stringify(e){const t=e;return JSON.stringify({...t,title:"function"==typeof t.title?t.title():t.title})}parse(e){const t=JSON.parse(e);return{...t,title:t.i18nTitleKey?Z(t.i18nTitleKey):t.title}}},networkConditionsEqual:function(e,t){const n="function"==typeof e.title?e.title():e.title,r="function"==typeof t.title?t.title():t.title;return t.download===e.download&&t.upload===e.upload&&t.latency===e.latency&&r===n}});const fe={deprecatedSyntaxFoundPleaseUse:"Deprecated syntax found. Please use: ;dur=;desc=",duplicateParameterSIgnored:'Duplicate parameter "{PH1}" ignored.',noValueFoundForParameterS:'No value found for parameter "{PH1}".',unrecognizedParameterS:'Unrecognized parameter "{PH1}".',extraneousTrailingCharacters:"Extraneous trailing characters.",unableToParseSValueS:'Unable to parse "{PH1}" value "{PH2}".'},be=s.i18n.registerUIStrings("core/sdk/ServerTiming.ts",fe),ye=s.i18n.getLocalizedString.bind(void 0,be);class ve{metric;value;description;constructor(e,t,n){this.metric=e,this.value=t,this.description=n}static parseHeaders(e){const n=e.filter((e=>"server-timing"===e.name.toLowerCase()));if(!n.length)return null;const r=n.reduce(((e,t)=>{const n=this.createFromHeaderValue(t.value);return e.push(...n.map((function(e){return new ve(e.name,e.hasOwnProperty("dur")?e.dur:null,e.hasOwnProperty("desc")?e.desc:"")}))),e}),[]);return r.sort(((e,n)=>t.StringUtilities.compare(e.metric.toLowerCase(),n.metric.toLowerCase()))),r}static createFromHeaderValue(e){function t(){e=e.replace(/^\s*/,"")}function n(n){return console.assert(1===n.length),t(),e.charAt(0)===n&&(e=e.substring(1),!0)}function r(){const t=/^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(e);return t?(e=t[2],t[1]):null}function s(){return t(),'"'===e.charAt(0)?function(){console.assert('"'===e.charAt(0)),e=e.substring(1);let t="";for(;e.length;){const n=/^([^"\\]*)(.*)/.exec(e);if(!n)return null;if(t+=n[1],'"'===n[2].charAt(0))return e=n[2].substring(1),t;console.assert("\\"===n[2].charAt(0)),t+=n[2].charAt(1),e=n[2].substring(2)}return null}():r()}function i(){const t=/([,;].*)/.exec(e);t&&(e=t[1])}const a=[];let o;for(;null!==(o=r());){const t={name:o};for("="===e.charAt(0)&&this.showWarning(ye(fe.deprecatedSyntaxFoundPleaseUse));n(";");){let e;if(null===(e=r()))continue;e=e.toLowerCase();const a=this.getParserForParameter(e);let o=null;if(n("=")&&(o=s(),i()),a){if(t.hasOwnProperty(e)){this.showWarning(ye(fe.duplicateParameterSIgnored,{PH1:e}));continue}null===o&&this.showWarning(ye(fe.noValueFoundForParameterS,{PH1:e})),a.call(this,t,o)}else this.showWarning(ye(fe.unrecognizedParameterS,{PH1:e}))}if(a.push(t),!n(","))break}return e.length&&this.showWarning(ye(fe.extraneousTrailingCharacters)),a}static getParserForParameter(e){switch(e){case"dur":{function t(t,n){if(t.dur=0,null!==n){const r=parseFloat(n);if(isNaN(r))return void ve.showWarning(ye(fe.unableToParseSValueS,{PH1:e,PH2:n}));t.dur=r}}return t}case"desc":{function e(e,t){e.desc=t||""}return e}default:return null}}static showWarning(t){e.Console.Console.instance().warn(`ServerTiming: ${t}`)}}var Ie=Object.freeze({__proto__:null,ServerTiming:ve});const ke={binary:"(binary)",secureOnly:'This cookie was blocked because it had the "`Secure`" attribute and the connection was not secure.',notOnPath:"This cookie was blocked because its path was not an exact match for or a superdirectory of the request url's path.",domainMismatch:"This cookie was blocked because neither did the request URL's domain exactly match the cookie's domain, nor was the request URL's domain a subdomain of the cookie's Domain attribute value.",sameSiteStrict:'This cookie was blocked because it had the "`SameSite=Strict`" attribute and the request was made from a different site. This includes top-level navigation requests initiated by other sites.',sameSiteLax:'This cookie was blocked because it had the "`SameSite=Lax`" attribute and the request was made from a different site and was not initiated by a top-level navigation.',sameSiteUnspecifiedTreatedAsLax:'This cookie didn\'t specify a "`SameSite`" attribute when it was stored and was defaulted to "SameSite=Lax," and was blocked because the request was made from a different site and was not initiated by a top-level navigation. The cookie had to have been set with "`SameSite=None`" to enable cross-site usage.',sameSiteNoneInsecure:'This cookie was blocked because it had the "`SameSite=None`" attribute but was not marked "Secure". Cookies without SameSite restrictions must be marked "Secure" and sent over a secure connection.',userPreferences:"This cookie was blocked due to user preferences.",unknownError:"An unknown error was encountered when trying to send this cookie.",schemefulSameSiteStrict:'This cookie was blocked because it had the "`SameSite=Strict`" attribute but the request was cross-site. This includes top-level navigation requests initiated by other sites. This request is considered cross-site because the URL has a different scheme than the current site.',schemefulSameSiteLax:'This cookie was blocked because it had the "`SameSite=Lax`" attribute but the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',schemefulSameSiteUnspecifiedTreatedAsLax:'This cookie didn\'t specify a "`SameSite`" attribute when it was stored, was defaulted to "`SameSite=Lax"`, and was blocked because the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',samePartyFromCrossPartyContext:"This cookie was blocked because it had the \"`SameParty`\" attribute but the request was cross-party. The request was considered cross-party because the domain of the resource's URL and the domains of the resource's enclosing frames/documents are neither owners nor members in the same First-Party Set.",nameValuePairExceedsMaxSize:"This cookie was blocked because it was too large. The combined size of the name and value must be less than or equal to 4096 characters.",thisSetcookieWasBlockedDueToUser:"This attempt to set a cookie via a `Set-Cookie` header was blocked due to user preferences.",thisSetcookieHadInvalidSyntax:"This `Set-Cookie` header had invalid syntax.",theSchemeOfThisConnectionIsNot:"The scheme of this connection is not allowed to store cookies.",anUnknownErrorWasEncounteredWhenTrying:"An unknown error was encountered when trying to store this cookie.",thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',thisSetcookieDidntSpecifyASamesite:'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute, was defaulted to "`SameSite=Lax"`, and was blocked because it came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',thisSetcookieWasBlockedBecauseItHadTheSameparty:"This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the \"`SameParty`\" attribute but the request was cross-party. The request was considered cross-party because the domain of the resource's URL and the domains of the resource's enclosing frames/documents are neither owners nor members in the same First-Party Set.",thisSetcookieWasBlockedBecauseItHadTheSamepartyAttribute:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "`SameParty`" attribute but also had other conflicting attributes. Chrome requires cookies that use the "`SameParty`" attribute to also have the "Secure" attribute, and to not be restricted to "`SameSite=Strict`".',blockedReasonSecureOnly:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "Secure" attribute but was not received over a secure connection.',blockedReasonSameSiteStrictLax:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation.',blockedReasonSameSiteUnspecifiedTreatedAsLax:'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute and was defaulted to "`SameSite=Lax,`" and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The `Set-Cookie` had to have been set with "`SameSite=None`" to enable cross-site usage.',blockedReasonSameSiteNoneInsecure:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "`SameSite=None`" attribute but did not have the "Secure" attribute, which is required in order to use "`SameSite=None`".',blockedReasonOverwriteSecure:"This attempt to set a cookie via a `Set-Cookie` header was blocked because it was not sent over a secure connection and would have overwritten a cookie with the Secure attribute.",blockedReasonInvalidDomain:"This attempt to set a cookie via a `Set-Cookie` header was blocked because its Domain attribute was invalid with regards to the current host url.",blockedReasonInvalidPrefix:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it used the "`__Secure-`" or "`__Host-`" prefix in its name and broke the additional rules applied to cookies with these prefixes as defined in `https://tools.ietf.org/html/draft-west-cookie-prefixes-05`.',thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize:"This attempt to set a cookie via a `Set-Cookie` header was blocked because the cookie was too large. The combined size of the name and value must be less than or equal to 4096 characters.",setcookieHeaderIsIgnoredIn:"Set-Cookie header is ignored in response from url: {PH1}. The combined size of the name and value must be less than or equal to 4096 characters."},Se=s.i18n.registerUIStrings("core/sdk/NetworkRequest.ts",ke),we=s.i18n.getLocalizedString.bind(void 0,Se);var Ce,Te,Re,xe;!function(e){e.HTML="text/html",e.XML="text/xml",e.PLAIN="text/plain",e.XHTML="application/xhtml+xml",e.SVG="image/svg+xml",e.CSS="text/css",e.XSL="text/xsl",e.VTT="text/vtt",e.PDF="application/pdf",e.EVENTSTREAM="text/event-stream"}(Ce||(Ce={}));class Me extends e.ObjectWrapper.ObjectWrapper{#ke;#Se;#we;#Ce;#Te;#Re;#xe;#Me;#Pe;#Le;#Ee;#Ae;#Oe;#Ne;#Fe;#Be;#De;statusCode;statusText;requestMethod;requestTime;protocol;alternateProtocolUsage;mixedContentType;#Ue;#He;#qe;#_e;#ze;#je;#We;#Ve;#Ge;#Ke;#$e;#Qe;#Xe;#Je;#Ye;#Ze;#et;#tt;#nt;#rt;#st;connectionId;connectionReused;hasNetworkData;#it;#at;#ot;#lt;#dt;#ct;#ht;#ut;#gt;#pt;localizedFailDescription;#mt;#ft;#bt;#ye;#yt;#vt;#It;#kt;#St;#u;#wt;#Ct;#Tt;#Rt;#xt;#Mt;#Pt;#Lt;#Et;#At;#Ot;#Nt;#Ft;#Bt;#Dt;#Ut;#Ht;#qt;#_t;#zt;#jt;#Wt;#Vt;#Gt;#Kt=new Map;constructor(t,n,r,s,i,a,o,l){super(),this.#ke=t,this.#Se=n,this.setUrl(r),this.#we=s,this.#Ce=i,this.#Te=a,this.#Re=o,this.#xe=l,this.#Me=null,this.#Pe=null,this.#Le=null,this.#Ee=!1,this.#Ae=null,this.#Oe=-1,this.#Ne=-1,this.#Fe=-1,this.#Be=void 0,this.#De=void 0,this.statusCode=0,this.statusText="",this.requestMethod="",this.requestTime=0,this.protocol="",this.alternateProtocolUsage=void 0,this.mixedContentType="none",this.#Ue=null,this.#He=null,this.#qe=null,this.#_e=null,this.#ze=null,this.#je=e.ResourceType.resourceTypes.Other,this.#We=null,this.#Ve=[],this.#Ge=[],this.#Ke={},this.#$e="",this.#Qe=[],this.#Je=[],this.#Ye=[],this.#Ze={},this.#et="",this.#tt="Unknown",this.#nt=null,this.#rt="unknown",this.#st=null,this.connectionId="0",this.connectionReused=!1,this.hasNetworkData=!1,this.#it=null,this.#at=Promise.resolve(null),this.#ot=!1,this.#lt=!1,this.#dt=[],this.#ct=[],this.#ht=[],this.#pt=!1,this.#ut=null,this.#gt=null,this.localizedFailDescription=null,this.#Vt=null,this.#Gt=!1}static create(e,t,n,r,s,i,a){return new Me(e,e,t,n,r,s,i,a)}static createForWebSocket(e,n,r){return new Me(e,e,n,t.DevToolsPath.EmptyUrlString,null,null,r||null)}static createWithoutBackendRequest(e,t,n,r){return new Me(e,void 0,t,n,null,null,r)}identityCompare(e){const t=this.requestId(),n=e.requestId();return t>n?1:te&&(this.#ft=e)),this.dispatchEventToListeners(Te.TimingChanged,this)}get duration(){return-1===this.#Fe||-1===this.#Ne?-1:this.#Fe-this.#Ne}get latency(){return-1===this.#ft||-1===this.#Ne?-1:this.#ft-this.#Ne}get resourceSize(){return this.#Et||0}set resourceSize(e){this.#Et=e}get transferSize(){return this.#bt||0}increaseTransferSize(e){this.#bt=(this.#bt||0)+e}setTransferSize(e){this.#bt=e}get finished(){return this.#ye}set finished(e){this.#ye!==e&&(this.#ye=e,e&&this.dispatchEventToListeners(Te.FinishedLoading,this))}get failed(){return this.#yt}set failed(e){this.#yt=e}get canceled(){return this.#vt}set canceled(e){this.#vt=e}get preserved(){return this.#It}set preserved(e){this.#It=e}blockedReason(){return this.#Be}setBlockedReason(e){this.#Be=e}corsErrorStatus(){return this.#De}setCorsErrorStatus(e){this.#De=e}wasBlocked(){return Boolean(this.#Be)}cached(){return(Boolean(this.#At)||Boolean(this.#Ot))&&!this.#bt}cachedInMemory(){return Boolean(this.#At)&&!this.#bt}fromPrefetchCache(){return Boolean(this.#Nt)}setFromMemoryCache(){this.#At=!0,this.#Bt=void 0}get fromDiskCache(){return this.#Ot}setFromDiskCache(){this.#Ot=!0}setFromPrefetchCache(){this.#Nt=!0}get fetchedViaServiceWorker(){return Boolean(this.#Ft)}set fetchedViaServiceWorker(e){this.#Ft=e}initiatedByServiceWorker(){const e=ne.forRequest(this);return!!e&&e.target().type()===_.ServiceWorker}get timing(){return this.#Bt}set timing(e){if(!e||this.#At)return;this.#Ne=e.requestTime;const t=e.requestTime+e.receiveHeadersEnd/1e3;((this.#ft||-1)<0||this.#ft>t)&&(this.#ft=t),this.#Ne>this.#ft&&(this.#ft=this.#Ne),this.#Bt=e,this.dispatchEventToListeners(Te.TimingChanged,this)}setConnectTimingFromExtraInfo(e){this.#Ne=e.requestTime,this.dispatchEventToListeners(Te.TimingChanged,this)}get mimeType(){return this.#kt}set mimeType(e){this.#kt=e}get displayName(){return this.#St.displayName}name(){return this.#u||this.parseNameAndPathFromURL(),this.#u}path(){return this.#wt||this.parseNameAndPathFromURL(),this.#wt}parseNameAndPathFromURL(){if(this.#St.isDataURL())this.#u=this.#St.dataURLDisplayName(),this.#wt="";else if(this.#St.isBlobURL())this.#u=this.#St.url,this.#wt="";else if(this.#St.isAboutBlank())this.#u=this.#St.url,this.#wt="";else{this.#wt=this.#St.host+this.#St.folderPathComponents;const n=ne.forRequest(this),r=n?e.ParsedURL.ParsedURL.fromString(n.target().inspectedURL()):null;this.#wt=t.StringUtilities.trimURL(this.#wt,r?r.host:""),this.#St.lastPathComponent||this.#St.queryParams?this.#u=this.#St.lastPathComponent+(this.#St.queryParams?"?"+this.#St.queryParams:""):this.#St.folderPathComponents?(this.#u=this.#St.folderPathComponents.substring(this.#St.folderPathComponents.lastIndexOf("/")+1)+"/",this.#wt=this.#wt.substring(0,this.#wt.lastIndexOf("/"))):(this.#u=this.#St.host,this.#wt="")}}get folder(){let e=this.#St.path;const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const n=e.lastIndexOf("/");return-1!==n?e.substring(0,n):""}get pathname(){return this.#St.path}resourceType(){return this.#je}setResourceType(e){this.#je=e}get domain(){return this.#St.host}get scheme(){return this.#St.scheme}redirectSource(){return this.#Me}setRedirectSource(e){this.#Me=e}preflightRequest(){return this.#Pe}setPreflightRequest(e){this.#Pe=e}preflightInitiatorRequest(){return this.#Le}setPreflightInitiatorRequest(e){this.#Le=e}isPreflightRequest(){return null!==this.#Re&&void 0!==this.#Re&&"preflight"===this.#Re.type}redirectDestination(){return this.#Ae}setRedirectDestination(e){this.#Ae=e}requestHeaders(){return this.#Ye}setRequestHeaders(e){this.#Ye=e,this.dispatchEventToListeners(Te.RequestHeadersChanged)}requestHeadersText(){return this.#Dt}setRequestHeadersText(e){this.#Dt=e,this.dispatchEventToListeners(Te.RequestHeadersChanged)}requestHeaderValue(e){return this.#Ze[e]||(this.#Ze[e]=this.computeHeaderValue(this.requestHeaders(),e)),this.#Ze[e]}requestFormData(){return this.#at||(this.#at=ne.requestPostData(this)),this.#at}setRequestFormData(e,t){this.#at=e&&null===t?null:Promise.resolve(t),this.#it=null}filteredProtocolName(){const e=this.protocol.toLowerCase();return"h2"===e?"http/2.0":e.replace(/^http\/2(\.0)?\+/,"http/2.0+")}requestHttpVersion(){const e=this.requestHeadersText();if(!e){const e=this.requestHeaderValue("version")||this.requestHeaderValue(":version");return e||this.filteredProtocolName()}const t=e.split(/\r\n/)[0].match(/(HTTP\/\d+\.\d+)$/);return t?t[1]:"HTTP/0.9"}get responseHeaders(){return this.#Ut||[]}set responseHeaders(e){this.#Ut=e,this.#Ht=void 0,this.#_t=void 0,this.#qt=void 0,this.#Ke={},this.dispatchEventToListeners(Te.ResponseHeadersChanged)}get originalResponseHeaders(){return this.#Qe}set originalResponseHeaders(e){this.#Qe=e,this.#Xe=void 0}get setCookieHeaders(){return this.#Je}set setCookieHeaders(e){this.#Je=e}get responseHeadersText(){return this.#$e}set responseHeadersText(e){this.#$e=e,this.dispatchEventToListeners(Te.ResponseHeadersChanged)}get sortedResponseHeaders(){return void 0!==this.#Ht?this.#Ht:(this.#Ht=this.responseHeaders.slice(),this.#Ht.sort((function(e,n){return t.StringUtilities.compare(e.name.toLowerCase(),n.name.toLowerCase())||t.StringUtilities.compare(e.value,n.value)})))}get sortedOriginalResponseHeaders(){return void 0!==this.#Xe?this.#Xe:(this.#Xe=this.originalResponseHeaders.slice(),this.#Xe.sort((function(e,n){return t.StringUtilities.compare(e.name.toLowerCase(),n.name.toLowerCase())||t.StringUtilities.compare(e.value,n.value)})))}hasOverriddenHeaders(){if(!this.#Qe.length)return!1;const e=this.sortedResponseHeaders,t=this.sortedOriginalResponseHeaders;if(t.length!==e.length)return!0;for(let n=0;ne.cookie)),...this.blockedResponseCookies().map((e=>e.cookie))].filter((e=>Boolean(e)))}get serverTimings(){return void 0===this.#_t&&(this.#_t=ve.parseHeaders(this.responseHeaders)),this.#_t}queryString(){if(void 0!==this.#zt)return this.#zt;let e=null;const t=this.url(),n=t.indexOf("?");if(-1!==n){e=t.substring(n+1);const r=e.indexOf("#");-1!==r&&(e=e.substring(0,r))}return this.#zt=e,this.#zt}get queryParameters(){if(this.#jt)return this.#jt;const e=this.queryString();return e?(this.#jt=this.parseParameters(e),this.#jt):null}async parseFormParameters(){const e=this.requestContentType();if(!e)return null;if(e.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){const e=await this.requestFormData();return e?this.parseParameters(e):null}const t=e.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/);if(!t)return null;const n=t[1];if(!n)return null;const r=await this.requestFormData();return r?this.parseMultipartFormDataParameters(r,n):null}formParameters(){return this.#it||(this.#it=this.parseFormParameters()),this.#it}responseHttpVersion(){const e=this.#$e;if(!e){const e=this.responseHeaderValue("version")||this.responseHeaderValue(":version");return e||this.filteredProtocolName()}const t=e.split(/\r\n/)[0].match(/^(HTTP\/\d+\.\d+)/);return t?t[1]:"HTTP/0.9"}parseParameters(e){return e.split("&").map((function(e){const t=e.indexOf("=");return-1===t?{name:e,value:""}:{name:e.substring(0,t),value:e.substring(t+1)}}))}parseMultipartFormDataParameters(e,n){const r=t.StringUtilities.escapeForRegExp(n),s=new RegExp('^\\r\\ncontent-disposition\\s*:\\s*form-data\\s*;\\s*name="([^"]*)"(?:\\s*;\\s*filename="([^"]*)")?(?:\\r\\ncontent-type\\s*:\\s*([^\\r\\n]*))?\\r\\n\\r\\n(.*)\\r\\n$',"is");return e.split(new RegExp(`--${r}(?:--s*$)?`,"g")).reduce((function(e,t){const[n,r,i,a,o]=t.match(s)||[];if(!n)return e;const l=i||a?we(ke.binary):o;return e.push({name:r,value:l}),e}),[])}computeHeaderValue(e,t){t=t.toLowerCase();const n=[];for(let r=0;r=400}setInitialPriority(e){this.#Ue=e}initialPriority(){return this.#Ue}setPriority(e){this.#He=e}priority(){return this.#He||this.#Ue||null}setSignedExchangeInfo(e){this.#qe=e}signedExchangeInfo(){return this.#qe}setWebBundleInfo(e){this.#_e=e}webBundleInfo(){return this.#_e}setWebBundleInnerRequestInfo(e){this.#ze=e}webBundleInnerRequestInfo(){return this.#ze}async populateImageSource(e){const{content:t,encoded:n}=await this.contentData();let s=r.ContentProvider.contentAsDataURL(t,this.#kt,n);if(null===s&&!this.#yt){(this.responseHeaderValue("cache-control")||"").includes("no-cache")||(s=this.#mt)}null!==s&&(e.src=s)}initiator(){return this.#Re||null}hasUserGesture(){return this.#xe??null}frames(){return this.#Ve}addProtocolFrameError(e,t){this.addFrame({type:xe.Error,text:e,time:this.pseudoWallTime(t),opCode:-1,mask:!1})}addProtocolFrame(e,t,n){const r=n?xe.Send:xe.Receive;this.addFrame({type:r,text:e.payloadData,time:this.pseudoWallTime(t),opCode:e.opcode,mask:e.mask})}addFrame(e){this.#Ve.push(e),this.dispatchEventToListeners(Te.WebsocketFrameAdded,e)}eventSourceMessages(){return this.#Ge}addEventSourceMessage(e,t,n,r){const s={time:this.pseudoWallTime(e),eventName:t,eventId:n,data:r};this.#Ge.push(s),this.dispatchEventToListeners(Te.EventSourceMessageAdded,s)}markAsRedirect(e){this.#Ee=!0,this.#ke=`${this.#Se}:redirected.${e}`}isRedirect(){return this.#Ee}setRequestIdForTest(e){this.#Se=e,this.#ke=e}charset(){const e=this.responseHeaderValue("content-type");if(!e)return null;const t=e.replace(/ /g,"").split(";").filter((e=>e.toLowerCase().startsWith("charset="))).map((e=>e.slice("charset=".length)));return t.length?t[0]:null}addExtraRequestInfo(e){this.#dt=e.blockedRequestCookies,this.#ct=e.includedRequestCookies,this.setRequestHeaders(e.requestHeaders),this.#ot=!0,this.setRequestHeadersText(""),this.#Ct=e.clientSecurityState,this.setConnectTimingFromExtraInfo(e.connectTiming),this.#pt=e.siteHasCookieInOtherPartition??!1}hasExtraRequestInfo(){return this.#ot}blockedRequestCookies(){return this.#dt}includedRequestCookies(){return this.#ct}hasRequestCookies(){return this.#ct.length>0||this.#dt.length>0}siteHasCookieInOtherPartition(){return this.#pt}static parseStatusTextFromResponseHeadersText(e){return e.split("\r")[0].split(" ").slice(2).join(" ")}addExtraResponseInfo(e){if(this.#ht=e.blockedResponseCookies,this.#ut=e.cookiePartitionKey||null,this.#gt=e.cookiePartitionKeyOpaque||null,this.responseHeaders=e.responseHeaders,this.originalResponseHeaders=e.responseHeaders.map((e=>({...e}))),e.responseHeadersText){if(this.responseHeadersText=e.responseHeadersText,!this.requestHeadersText()){let e=`${this.requestMethod} ${this.parsedURL.path}`;this.parsedURL.queryParams&&(e+=`?${this.parsedURL.queryParams}`),e+=" HTTP/1.1\r\n";for(const{name:t,value:n}of this.requestHeaders())e+=`${t}: ${n}\r\n`;this.setRequestHeadersText(e)}this.statusText=Me.parseStatusTextFromResponseHeadersText(e.responseHeadersText)}this.#tt=e.resourceIPAddressSpace,e.statusCode&&(this.statusCode=e.statusCode),this.#lt=!0;const t=ne.forRequest(this);if(t)for(const e of this.#ht)if(e.blockedReasons.includes("NameValuePairExceedsMaxSize")){const e=we(ke.setcookieHeaderIsIgnoredIn,{PH1:this.url()});t.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:this.#ke,warning:!0})}}hasExtraResponseInfo(){return this.#lt}blockedResponseCookies(){return this.#ht}responseCookiesPartitionKey(){return this.#ut}responseCookiesPartitionKeyOpaque(){return this.#gt}redirectSourceSignedExchangeInfoHasNoErrors(){return null!==this.#Me&&null!==this.#Me.#qe&&!this.#Me.#qe.errors}clientSecurityState(){return this.#Ct}setTrustTokenParams(e){this.#Tt=e}trustTokenParams(){return this.#Tt}setTrustTokenOperationDoneEvent(e){this.#Rt=e,this.dispatchEventToListeners(Te.TrustTokenResultAdded)}trustTokenOperationDoneEvent(){return this.#Rt}setIsSameSite(e){this.#Vt=e}isSameSite(){return this.#Vt}getAssociatedData(e){return this.#Kt.get(e)||null}setAssociatedData(e,t){this.#Kt.set(e,t)}deleteAssociatedData(e){this.#Kt.delete(e)}}!function(e){e.FinishedLoading="FinishedLoading",e.TimingChanged="TimingChanged",e.RemoteAddressChanged="RemoteAddressChanged",e.RequestHeadersChanged="RequestHeadersChanged",e.ResponseHeadersChanged="ResponseHeadersChanged",e.WebsocketFrameAdded="WebsocketFrameAdded",e.EventSourceMessageAdded="EventSourceMessageAdded",e.TrustTokenResultAdded="TrustTokenResultAdded"}(Te||(Te={})),function(e){e.Other="other",e.Parser="parser",e.Redirect="redirect",e.Script="script",e.Preload="preload",e.SignedExchange="signedExchange",e.Preflight="preflight"}(Re||(Re={})),function(e){e.Send="send",e.Receive="receive",e.Error="error"}(xe||(xe={}));var Pe=Object.freeze({__proto__:null,get MIME_TYPE(){return Ce},NetworkRequest:Me,get Events(){return Te},get InitiatorType(){return Re},get WebSocketFrameType(){return xe},cookieBlockedReasonToUiString:function(e){switch(e){case"SecureOnly":return we(ke.secureOnly);case"NotOnPath":return we(ke.notOnPath);case"DomainMismatch":return we(ke.domainMismatch);case"SameSiteStrict":return we(ke.sameSiteStrict);case"SameSiteLax":return we(ke.sameSiteLax);case"SameSiteUnspecifiedTreatedAsLax":return we(ke.sameSiteUnspecifiedTreatedAsLax);case"SameSiteNoneInsecure":return we(ke.sameSiteNoneInsecure);case"UserPreferences":return we(ke.userPreferences);case"UnknownError":return we(ke.unknownError);case"SchemefulSameSiteStrict":return we(ke.schemefulSameSiteStrict);case"SchemefulSameSiteLax":return we(ke.schemefulSameSiteLax);case"SchemefulSameSiteUnspecifiedTreatedAsLax":return we(ke.schemefulSameSiteUnspecifiedTreatedAsLax);case"SamePartyFromCrossPartyContext":return we(ke.samePartyFromCrossPartyContext);case"NameValuePairExceedsMaxSize":return we(ke.nameValuePairExceedsMaxSize)}return""},setCookieBlockedReasonToUiString:function(e){switch(e){case"SecureOnly":return we(ke.blockedReasonSecureOnly);case"SameSiteStrict":return we(ke.blockedReasonSameSiteStrictLax,{PH1:"SameSite=Strict"});case"SameSiteLax":return we(ke.blockedReasonSameSiteStrictLax,{PH1:"SameSite=Lax"});case"SameSiteUnspecifiedTreatedAsLax":return we(ke.blockedReasonSameSiteUnspecifiedTreatedAsLax);case"SameSiteNoneInsecure":return we(ke.blockedReasonSameSiteNoneInsecure);case"UserPreferences":return we(ke.thisSetcookieWasBlockedDueToUser);case"SyntaxError":return we(ke.thisSetcookieHadInvalidSyntax);case"SchemeNotSupported":return we(ke.theSchemeOfThisConnectionIsNot);case"OverwriteSecure":return we(ke.blockedReasonOverwriteSecure);case"InvalidDomain":return we(ke.blockedReasonInvalidDomain);case"InvalidPrefix":return we(ke.blockedReasonInvalidPrefix);case"UnknownError":return we(ke.anUnknownErrorWasEncounteredWhenTrying);case"SchemefulSameSiteStrict":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax,{PH1:"SameSite=Strict"});case"SchemefulSameSiteLax":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax,{PH1:"SameSite=Lax"});case"SchemefulSameSiteUnspecifiedTreatedAsLax":return we(ke.thisSetcookieDidntSpecifyASamesite);case"SamePartyFromCrossPartyContext":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSameparty);case"SamePartyConflictsWithOtherAttributes":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamepartyAttribute);case"NameValuePairExceedsMaxSize":return we(ke.thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize)}return""},cookieBlockedReasonToAttribute:function(e){switch(e){case"SecureOnly":return D.Secure;case"NotOnPath":return D.Path;case"DomainMismatch":return D.Domain;case"SameSiteStrict":case"SameSiteLax":case"SameSiteUnspecifiedTreatedAsLax":case"SameSiteNoneInsecure":case"SchemefulSameSiteStrict":case"SchemefulSameSiteLax":case"SchemefulSameSiteUnspecifiedTreatedAsLax":return D.SameSite;case"SamePartyFromCrossPartyContext":case"NameValuePairExceedsMaxSize":case"UserPreferences":case"UnknownError":return null}return null},setCookieBlockedReasonToAttribute:function(e){switch(e){case"SecureOnly":case"OverwriteSecure":return D.Secure;case"SameSiteStrict":case"SameSiteLax":case"SameSiteUnspecifiedTreatedAsLax":case"SameSiteNoneInsecure":case"SchemefulSameSiteStrict":case"SchemefulSameSiteLax":case"SchemefulSameSiteUnspecifiedTreatedAsLax":return D.SameSite;case"InvalidDomain":return D.Domain;case"InvalidPrefix":return D.Name;case"SamePartyConflictsWithOtherAttributes":case"SamePartyFromCrossPartyContext":case"NameValuePairExceedsMaxSize":case"UserPreferences":case"SyntaxError":case"SchemeNotSupported":case"UnknownError":return null}return null}});class Le{static fromLocalObject(e){return new Fe(e)}static type(e){if(null===e)return"null";const t=typeof e;return"object"!==t&&"function"!==t?t:e.type}static isNullOrUndefined(e){if(void 0===e)return!0;switch(e.type){case"object":return"null"===e.subtype;case"undefined":return!0;default:return!1}}static arrayNameFromDescription(e){return e.replace(Ue,"").replace(He,"")}static arrayLength(e){if("array"!==e.subtype&&"typedarray"!==e.subtype)return 0;const t=e.description&&e.description.match(Ue),n=e.description&&e.description.match(He);return t?parseInt(t[1],10):n?parseInt(n[1],10):0}static arrayBufferByteLength(e){if("arraybuffer"!==e.subtype)return 0;const t=e.description&&e.description.match(Ue);return t?parseInt(t[1],10):0}static unserializableDescription(e){const t=typeof e;if("number"===t){const t=String(e);if(0===e&&1/e<0)return"-0";if("NaN"===t||"Infinity"===t||"-Infinity"===t)return t}return"bigint"===t?e+"n":null}static toCallArgument(e){const t=typeof e;if("undefined"===t)return{};const n=Le.unserializableDescription(e);if("number"===t)return null!==n?{unserializableValue:n}:{value:e};if("bigint"===t)return{unserializableValue:n};if("string"===t||"boolean"===t)return{value:e};if(!e)return{value:null};const r=e;if(e instanceof Le){const t=e.unserializableValue();if(void 0!==t)return{unserializableValue:t}}else if(void 0!==r.unserializableValue)return{unserializableValue:r.unserializableValue};return void 0!==r.objectId?{objectId:r.objectId}:{value:r.value}}static async loadFromObjectPerProto(e,t,n=!1){const r=await Promise.all([e.getAllProperties(!0,t,n),e.getOwnProperties(t,n)]),s=r[0].properties,i=r[1].properties,a=r[1].internalProperties;if(!i||!s)return{properties:null,internalProperties:null};const o=new Map,l=[];for(let e=0;e100){r+=",…";break}e&&(r+=", "),r+=t}return r+=t,r}get type(){return typeof this.valueInternal}get subtype(){return null===this.valueInternal?"null":Array.isArray(this.valueInternal)?"array":this.valueInternal instanceof Date?"date":void 0}get hasChildren(){return"object"==typeof this.valueInternal&&null!==this.valueInternal&&Boolean(Object.keys(this.valueInternal).length)}async getOwnProperties(e,t=!1){let n=this.children();return t&&(n=n.filter((e=>!function(e){const t=Number(e)>>>0;return String(t)===e}(e.name)))),{properties:n,internalProperties:null}}async getAllProperties(e,t,n=!1){return e?{properties:[],internalProperties:null}:await this.getOwnProperties(t,n)}children(){if(!this.hasChildren)return[];const e=this.valueInternal;return this.#in||(this.#in=Object.keys(e).map((function(t){let n=e[t];return n instanceof Le||(n=Le.fromLocalObject(n)),new Ne(t,n)}))),this.#in}arrayLength(){return Array.isArray(this.valueInternal)?this.valueInternal.length:0}async callFunction(e,t){const n=this.valueInternal,r=t?t.map((e=>e.value)):[];let s,i=!1;try{s=e.apply(n,r)}catch(e){i=!0}return{object:Le.fromLocalObject(s),wasThrown:i}}async callFunctionJSON(e,t){const n=this.valueInternal,r=t?t.map((e=>e.value)):[];let s;try{s=e.apply(n,r)}catch(e){s=null}return s}}class Be{#an;constructor(e){this.#an=e}static objectAsArray(e){if(!e||"object"!==e.type||"array"!==e.subtype&&"typedarray"!==e.subtype)throw new Error("Object is empty or not an array");return new Be(e)}static createFromRemoteObjects(e){if(!e.length)throw new Error("Input array is empty");const t=[];for(let n=0;n1)return new Array(arguments);return[arguments[0]]}),t).then((function(e){if(e.wasThrown||!e.object)throw new Error("Call function throws exceptions or returns empty value");return Be.objectAsArray(e.object)}))}at(e){if(e<0||e>this.#an.arrayLength())throw new Error("Out of range");return this.#an.callFunction((function(e){return this[e]}),[Le.toCallArgument(e)]).then((function(e){if(e.wasThrown||!e.object)throw new Error("Exception in callFunction or result value is empty");return e.object}))}length(){return this.#an.arrayLength()}map(e){const t=[];for(let n=0;n=this.byteLength())throw new RangeError("start is out of range");if(tthis.byteLength())throw new RangeError("end is out of range");return await this.#an.callFunctionJSON((function(e,t){return[...new Uint8Array(this,e,t)]}),[{value:e},{value:t-e}])}object(){return this.#an}},RemoteArray:Be,RemoteFunction:De});class _e{#on;#ln;#dn;#cn;#hn;constructor(e){this.#on=e.fontFamily,this.#ln=e.fontVariationAxes||[],this.#dn=new Map,this.#cn=e.src,this.#hn=e.fontDisplay;for(const e of this.#ln)this.#dn.set(e.tag,e)}getFontFamily(){return this.#on}getSrc(){return this.#cn}getFontDisplay(){return this.#hn}getVariationAxisByTag(e){return this.#dn.get(e)}}var ze=Object.freeze({__proto__:null,CSSFontFace:_e});class je{text="";range;styleSheetId;cssModel;constructor(e){this.cssModel=e}rebase(e){this.styleSheetId===e.styleSheetId&&this.range&&(e.oldRange.equal(this.range)?this.reinitialize(e.payload):this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}equal(e){return!!(this.styleSheetId&&this.range&&e.range)&&(this.styleSheetId===e.styleSheetId&&this.range.equal(e.range))}lineNumberInSource(){if(this.range)return this.header()?.lineNumberInSource(this.range.startLine)}columnNumberInSource(){if(this.range)return this.header()?.columnNumberInSource(this.range.startLine,this.range.startColumn)}header(){return this.styleSheetId?this.cssModel.styleSheetHeaderForId(this.styleSheetId):null}rawLocation(){const e=this.header();if(!e||void 0===this.lineNumberInSource())return null;const t=Number(this.lineNumberInSource());return new rn(e,t,this.columnNumberInSource())}}var We=Object.freeze({__proto__:null,CSSQuery:je});class Ve extends je{name;physicalAxes;logicalAxes;static parseContainerQueriesPayload(e,t){return t.map((t=>new Ve(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.name=e.name,this.physicalAxes=e.physicalAxes,this.logicalAxes=e.logicalAxes}active(){return!0}async getContainerForNode(e){const t=await this.cssModel.domModel().getContainerForNode(e,this.name,this.physicalAxes,this.logicalAxes);if(t)return new Ge(t)}}class Ge{containerNode;constructor(e){this.containerNode=e}async getContainerSizeDetails(){const e=await this.containerNode.domModel().cssModel().getComputedStyle(this.containerNode.id);if(!e)return;const t=e.get("container-type"),n=e.get("contain"),r=e.get("writing-mode");if(!t||!n||!r)return;const s=Ke(`${t} ${n}`),i=$e(s,r);let a,o;return"Both"!==i&&"Horizontal"!==i||(a=e.get("width")),"Both"!==i&&"Vertical"!==i||(o=e.get("height")),{queryAxis:s,physicalAxis:i,width:a,height:o}}}const Ke=e=>{const t=e.split(" ");let n=!1,r=!1;for(const e of t){if("size"===e)return"size";n=n||"inline-size"===e,r=r||"block-size"===e}return n&&r?"size":n?"inline-size":r?"block-size":""},$e=(e,t)=>{const n=t.startsWith("vertical");switch(e){case"":return"";case"size":return"Both";case"inline-size":return n?"Vertical":"Horizontal";case"block-size":return n?"Horizontal":"Vertical"}};var Qe=Object.freeze({__proto__:null,CSSContainerQuery:Ve,CSSContainerQueryContainer:Ge,getQueryAxis:Ke,getPhysicalAxisFromQueryAxis:$e});class Xe extends je{static parseLayerPayload(e,t){return t.map((t=>new Xe(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId}active(){return!0}}var Je=Object.freeze({__proto__:null,CSSLayer:Xe});class Ye{#un;#gn;constructor(e){this.#un=e.active,this.#gn=[];for(let t=0;tnew et(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){if(this.text=e.text,this.source=e.source,this.sourceURL=e.sourceURL||"",this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.mediaList=null,e.mediaList){this.mediaList=[];for(let t=0;tnew nt(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId}active(){return!0}}var rt=Object.freeze({__proto__:null,CSSScope:nt});class st extends je{static parseSupportsPayload(e,t){return t.map((t=>new st(e,t)))}#yn=!0;constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.#yn=e.active}active(){return this.#yn}}var it=Object.freeze({__proto__:null,CSSSupports:st});class at{ownerStyle;index;name;value;important;disabled;parsedOk;implicit;text;range;#yn;#vn;#fn;#In;#kn=[];constructor(e,t,n,s,i,a,o,l,d,c,h){if(this.ownerStyle=e,this.index=t,this.name=n,this.value=s,this.important=i,this.disabled=a,this.parsedOk=o,this.implicit=l,this.text=d,this.range=c?r.TextRange.TextRange.fromObject(c):null,this.#yn=!0,this.#vn=null,this.#fn=null,h&&h.length>0)for(const n of h)this.#kn.push(new at(e,++t,n.name,n.value,i,a,o,!0));else{const r=v().getLonghands(n);for(const n of r||[])this.#kn.push(new at(e,++t,n,"",i,a,o,!0))}}static parsePayload(e,t,n){return new at(e,t,n.name,n.value,n.important||!1,n.disabled||!1,!("parsedOk"in n)||Boolean(n.parsedOk),Boolean(n.implicit),n.text,n.range,n.longhandProperties)}ensureRanges(){if(this.#vn&&this.#fn)return;const e=this.range,t=this.text?new r.Text.Text(this.text):null;if(!e||!t)return;const n=t.value().indexOf(this.name),s=t.value().lastIndexOf(this.value);if(-1===n||-1===s||n>s)return;const i=new r.TextRange.SourceRange(n,this.name.length),a=new r.TextRange.SourceRange(s,this.value.length);function o(e,t,n){return 0===e.startLine&&(e.startColumn+=n,e.endColumn+=n),e.startLine+=t,e.endLine+=t,e}this.#vn=o(t.toTextRange(i),e.startLine,e.startColumn),this.#fn=o(t.toTextRange(a),e.startLine,e.startColumn)}nameRange(){return this.ensureRanges(),this.#vn}valueRange(){return this.ensureRanges(),this.#fn}rebase(e){this.ownerStyle.styleSheetId===e.styleSheetId&&this.range&&(this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}setActive(e){this.#yn=e}get propertyText(){return void 0!==this.text?this.text:""===this.name?"":this.name+": "+this.value+(this.important?" !important":"")+";"}activeInStyle(){return this.#yn}trimmedValueWithoutImportant(){const e="!important";return this.value.endsWith(e)?this.value.slice(0,-e.length).trim():this.value.trim()}async setText(n,s,a){if(!this.ownerStyle)throw new Error("No ownerStyle for property");if(!this.ownerStyle.styleSheetId)throw new Error("No owner style id");if(!this.range||!this.ownerStyle.range)throw new Error("Style not editable");if(s&&(i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited),this.name.startsWith("--")&&i.userMetrics.actionTaken(i.UserMetrics.Action.CustomPropertyEdited)),a&&n===this.propertyText)return this.ownerStyle.cssModel().domModel().markUndoableState(!s),!0;const o=this.range.relativeTo(this.ownerStyle.range.startLine,this.ownerStyle.range.startColumn),l=this.ownerStyle.cssText?this.detectIndentation(this.ownerStyle.cssText):e.Settings.Settings.instance().moduleSetting("textEditorIndent").get(),d=this.ownerStyle.cssText?l.substring(0,this.ownerStyle.range.endColumn):"",c=new r.Text.Text(this.ownerStyle.cssText||"").replaceRange(o,t.StringUtilities.sprintf(";%s;",n)),h=await at.formatStyle(c,l,d);return this.ownerStyle.setText(h,s)}static async formatStyle(e,t,n){const s=t.substring(n.length)+t;t&&(t="\n"+t);let i="",a="",o="",l=!1,d=!1;const c=r.CodeMirrorUtils.createCssTokenizer();return await c("*{"+e+"}",(function(e,n){if(!l){const r=n?.includes("comment")&&function(e){const t=e.indexOf(":");if(-1===t)return!1;const n=e.substring(2,t).trim();return v().isCSSPropertyName(n)}(e),s=n?.includes("string")||n?.includes("meta")||n?.includes("property")||n?.includes("variableName")&&"variableName.function"!==n;return r?i=i.trimEnd()+t+e:s?(l=!0,o=e):(";"!==e||d)&&(i+=e,e.trim()&&!n?.includes("comment")&&(d=";"!==e)),void("{"!==e||n||(d=!1))}if("}"===e||";"===e){const n=o.trim();return i=i.trimEnd()+t+n+(n.endsWith(":")?" ":"")+e,d=!1,l=!1,void(a="")}if(v().isGridAreaDefiningProperty(a)){const t=b.exec(e);t&&0===t.index&&!o.trimEnd().endsWith("]")&&(o=o.trimEnd()+"\n"+s)}a||":"!==e||(a=o);o+=e})),l&&(i+=o),i=i.substring(2,i.length-1).trimEnd(),i+(t?"\n"+n:"")}detectIndentation(e){const t=e.split("\n");return t.length<2?"":r.TextUtils.Utils.lineIndent(t[1])}setValue(e,t,n,r){const s=this.name+": "+e+(this.important?" !important":"")+";";this.setText(s,t,n).then(r)}async setDisabled(e){if(!this.ownerStyle)return!1;if(e===this.disabled)return!0;if(!this.text)return!0;const t=this.text.trim(),n=e=>e+(e.endsWith(";")?"":";");let r;return r=e?"/* "+n(t)+" */":n(this.text.substring(2,t.length-2).trim()),this.setText(r,!0,!0)}setDisplayedStringForInvalidProperty(e){this.#In=e}getInvalidStringForInvalidProperty(){return this.#In}getLonghandProperties(){return this.#kn}}var ot,lt=Object.freeze({__proto__:null,CSSProperty:at});class dt{#Sn;parentRule;#wn;styleSheetId;range;cssText;#Cn;#Tn;#Rn;#xn;type;constructor(e,t,n,r){this.#Sn=e,this.parentRule=t,this.#Mn(n),this.type=r}rebase(e){if(this.styleSheetId===e.styleSheetId&&this.range)if(e.oldRange.equal(this.range))this.#Mn(e.payload);else{this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange);for(let t=0;t0||!l.validContent)continue;let s=0;for(const i of l.validContent.split(";")){const a=i.trim();if(a){let o,l;const d=a.indexOf(":");-1===d?(o=a,l=""):(o=a.substring(0,d).trim(),l=a.substring(d+1).trim());const c=new r.TextRange.TextRange(e,s,e,s+i.length);this.#wn.push(new at(this,this.#wn.length,o,l,!1,!1,!1,!1,i,c.relativeFrom(t,n)))}s+=i.length+1}}function d(e,t){t.validContent="";for(let n=0;n=0;--e)if(this.allProperties()[e].range)return e+1;return 0}#On(e){const t=this.propertyAt(e);if(t&&t.range)return t.range.collapseToStart();if(!this.range)throw new Error("CSSStyleDeclaration.range is null");return this.range.collapseToEnd()}newBlankProperty(e){e=void 0===e?this.pastLastSourcePropertyIndex():e;return new at(this,e,"","",!1,!1,!0,!1,"",this.#On(e))}setText(e,t){return this.range&&this.styleSheetId?this.#Sn.setStyleText(this.styleSheetId,this.range,e,t):Promise.resolve(!1)}insertPropertyAt(e,t,n,r){this.newBlankProperty(e).setText(t+": "+n+";",!1,!0).then(r)}appendProperty(e,t,n){this.insertPropertyAt(this.allProperties().length,e,t,n)}}!function(e){e.Regular="Regular",e.Inline="Inline",e.Attributes="Attributes"}(ot||(ot={}));var ct=Object.freeze({__proto__:null,CSSStyleDeclaration:dt,get Type(){return ot}});class ht{cssModelInternal;styleSheetId;sourceURL;origin;style;constructor(e,t){if(this.cssModelInternal=e,this.styleSheetId=t.styleSheetId,this.styleSheetId){const e=this.getStyleSheetHeader(this.styleSheetId);this.sourceURL=e.sourceURL}this.origin=t.origin,this.style=new dt(this.cssModelInternal,this,t.style,ot.Regular)}rebase(e){this.styleSheetId===e.styleSheetId&&this.style.rebase(e)}resourceURL(){if(!this.styleSheetId)return t.DevToolsPath.EmptyUrlString;return this.getStyleSheetHeader(this.styleSheetId).resourceURL()}isUserAgent(){return"user-agent"===this.origin}isInjected(){return"injected"===this.origin}isViaInspector(){return"inspector"===this.origin}isRegular(){return"regular"===this.origin}cssModel(){return this.cssModelInternal}getStyleSheetHeader(e){const t=this.cssModelInternal.styleSheetHeaderForId(e);return console.assert(null!==t),t}}class ut{text;range;specificity;constructor(e){this.text=e.text,e.range&&(this.range=r.TextRange.TextRange.fromObject(e.range)),e.specificity&&(this.specificity=e.specificity)}rebase(e){this.range&&(this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}}class gt extends ht{selectors;nestingSelectors;media;containerQueries;supports;scopes;layers;wasUsed;constructor(e,t,n){super(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId}),this.reinitializeSelectors(t.selectorList),this.nestingSelectors=t.nestingSelectors,this.media=t.media?et.parseMediaArrayPayload(e,t.media):[],this.containerQueries=t.containerQueries?Ve.parseContainerQueriesPayload(e,t.containerQueries):[],this.scopes=t.scopes?nt.parseScopesPayload(e,t.scopes):[],this.supports=t.supports?st.parseSupportsPayload(e,t.supports):[],this.layers=t.layers?Xe.parseLayerPayload(e,t.layers):[],this.wasUsed=n||!1}static createDummyRule(e,t){const n={selectorList:{text:"",selectors:[{text:t,value:void 0}]},style:{styleSheetId:"0",range:new r.TextRange.TextRange(0,0,0,0),shorthandEntries:[],cssProperties:[]},origin:"inspector"};return new gt(e,n)}reinitializeSelectors(e){this.selectors=[];for(let t=0;te.text)).join(", ")}selectorRange(){const e=this.selectors[0].range,t=this.selectors[this.selectors.length-1].range;return e&&t?new r.TextRange.TextRange(e.startLine,e.startColumn,t.endLine,t.endColumn):null}lineNumberInSource(e){const t=this.selectors[e];if(!t||!t.range||!this.styleSheetId)return 0;return this.getStyleSheetHeader(this.styleSheetId).lineNumberInSource(t.range.startLine)}columnNumberInSource(e){const t=this.selectors[e];if(!t||!t.range||!this.styleSheetId)return;return this.getStyleSheetHeader(this.styleSheetId).columnNumberInSource(t.range.startLine,t.range.startColumn)}rebase(e){if(this.styleSheetId!==e.styleSheetId)return;const t=this.selectorRange();if(t&&t.equal(e.oldRange))this.reinitializeSelectors(e.payload);else for(let t=0;tt.rebase(e))),this.containerQueries.forEach((t=>t.rebase(e))),this.scopes.forEach((t=>t.rebase(e))),this.supports.forEach((t=>t.rebase(e))),super.rebase(e)}}class pt{#Nn;#Fn;constructor(e,t){this.#Nn=new ut(t.animationName),this.#Fn=t.keyframes.map((t=>new mt(e,t)))}name(){return this.#Nn}keyframes(){return this.#Fn}}class mt extends ht{#Bn;constructor(e,t){super(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId}),this.reinitializeKey(t.keyText)}key(){return this.#Bn}reinitializeKey(e){this.#Bn=new ut(e)}rebase(e){this.styleSheetId===e.styleSheetId&&this.#Bn.range&&(e.oldRange.equal(this.#Bn.range)?this.reinitializeKey(e.payload):this.#Bn.rebase(e),super.rebase(e))}setKeyText(e){const t=this.styleSheetId;if(!t)throw"No rule stylesheet id";const n=this.#Bn.range;if(!n)throw"Keyframe key is not editable";return this.cssModelInternal.setKeyframeKey(t,n,e)}}class ft{#Dn;#Un;constructor(e,t){this.#Dn=new ut(t.name),this.#Un=t.tryRules.map((t=>new ht(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId})))}name(){return this.#Dn}tryRules(){return this.#Un}}var bt,yt=Object.freeze({__proto__:null,CSSRule:ht,CSSStyleRule:gt,CSSKeyframesRule:pt,CSSKeyframeRule:mt,CSSPositionFallbackRule:ft});function vt(e){const t=e.match(/var\(\s*(--(?:[\s\w\P{ASCII}-]|\\.)+),?\s*(.*)\s*\)/u);return{variableName:t&&t[1].trim(),fallback:t&&t[2]}}class It{#Sn;#Hn;#qn;#_n;#Fn;#zn;#jn;#Wn;#Vn;#Gn;#Kn;#$n;#Qn;constructor({cssModel:e,node:t,inlinePayload:n,attributesPayload:r,matchedPayload:s,pseudoPayload:i,inheritedPayload:a,inheritedPseudoPayload:o,animationsPayload:l,parentLayoutNodeId:d,positionFallbackRules:c}){this.#Sn=e,this.#Hn=t,this.#qn=new Map,this.#_n=new Map,this.#Fn=[],l&&(this.#Fn=l.map((t=>new pt(e,t)))),this.#Qn=c.map((t=>new ft(e,t))),this.#$n=d,this.#zn=new Map,this.#jn=new Set,s=h(s);for(const e of a)e.matchedCSSRules=h(e.matchedCSSRules);this.#Wn=this.buildMainCascade(n,r,s,a),[this.#Vn,this.#Gn]=this.buildPseudoCascades(i,o),this.#Kn=new Map;for(const e of Array.from(this.#Gn.values()).concat(Array.from(this.#Vn.values())).concat(this.#Wn))for(const t of e.styles())this.#Kn.set(t,e);function h(e){for(const t of e)s(t);const t=[];for(const s of e){const e=t[t.length-1];e&&"user-agent"===s.rule.origin&&"user-agent"===e.rule.origin&&s.rule.selectorList.text===e.rule.selectorList.text&&r(s)===r(e)?n(s,e):t.push(s)}return t;function n(e,t){const n=new Map,r=new Map;for(const e of t.rule.style.shorthandEntries)n.set(e.name,e.value);for(const e of t.rule.style.cssProperties)r.set(e.name,e.value);for(const t of e.rule.style.shorthandEntries)n.set(t.name,t.value);for(const t of e.rule.style.cssProperties)r.set(t.name,t.value);t.rule.style.shorthandEntries=[...n.entries()].map((([e,t])=>({name:e,value:t}))),t.rule.style.cssProperties=[...r.entries()].map((([e,t])=>({name:e,value:t})))}function r(e){return e.rule.media?e.rule.media.map((e=>e.text)).join(", "):null}function s(e){const{matchingSelectors:t,rule:n}=e;"user-agent"===n.origin&&t.length&&(n.selectorList.selectors=n.selectorList.selectors.filter(((e,n)=>t.includes(n))),n.selectorList.text=n.selectorList.selectors.map((e=>e.text)).join(", "),e.matchingSelectors=t.map(((e,t)=>t)))}}}buildMainCascade(e,t,n,r){const s=[],i=[];function a(){if(!t)return;const e=new dt(this.#Sn,null,t,ot.Attributes);this.#zn.set(e,this.#Hn),i.push(e)}if(e&&this.#Hn.nodeType()===Node.ELEMENT_NODE){const t=new dt(this.#Sn,null,e,ot.Inline);this.#zn.set(t,this.#Hn),i.push(t)}let o;for(let e=n.length-1;e>=0;--e){const t=new gt(this.#Sn,n[e].rule);!t.isInjected()&&!t.isUserAgent()||o||(o=!0,a.call(this)),this.#zn.set(t.style,this.#Hn),i.push(t.style),this.addMatchingSelectors(this.#Hn,t,n[e].matchingSelectors)}o||a.call(this),s.push(new kt(this,i,!1));let l=this.#Hn.parentNode;for(let e=0;l&&r&&e=0;--e){const n=new gt(this.#Sn,o[e].rule);this.addMatchingSelectors(l,n,o[e].matchingSelectors),this.containsInherited(n.style)&&(d(i,n.style)||d(this.#jn,n.style)||(this.#zn.set(n.style,l),t.push(n.style),this.#jn.add(n.style)))}l=l.parentNode,s.push(new kt(this,t,!0))}return new St(s);function d(e,t){if(!t.styleSheetId||!t.range)return!1;for(const n of e)if(t.styleSheetId===n.styleSheetId&&n.range&&t.range.equal(n.range))return!0;return!1}}buildSplitCustomHighlightCascades(e,t,n,r){const s=new Map;for(let r=e.length-1;r>=0;--r){const i=this.customHighlightNamesToMatchingSelectorIndices(e[r]);for(const[a,o]of i){const i=new gt(this.#Sn,e[r].rule);this.#zn.set(i.style,t),n&&this.#jn.add(i.style),this.addMatchingSelectors(t,i,o);const l=s.get(a);l?l.push(i.style):s.set(a,[i.style])}}for(const[e,t]of s){const s=new kt(this,t,n,!0),i=r.get(e);i?i.push(s):r.set(e,[s])}}customHighlightNamesToMatchingSelectorIndices(e){const t=new Map;for(let n=0;n=0;--e){const t=new gt(this.#Sn,o[e].rule);a.push(t.style);const s=v().isHighlightPseudoType(n.pseudoType)?this.#Hn:r;this.#zn.set(t.style,s),s&&this.addMatchingSelectors(s,t,o[e].matchingSelectors)}const e=v().isHighlightPseudoType(n.pseudoType),t=new kt(this,a,!1,e);s.set(n.pseudoType,[t])}}if(t){let e=this.#Hn.parentNode;for(let n=0;e&&n=0;--n){const r=new gt(this.#Sn,a[n].rule);t.push(r.style),this.#zn.set(r.style,e),this.#jn.add(r.style),this.addMatchingSelectors(e,r,a[n].matchingSelectors)}const r=v().isHighlightPseudoType(n.pseudoType),i=new kt(this,t,!0,r),o=s.get(n.pseudoType);o?o.push(i):s.set(n.pseudoType,[i])}}e=e.parentNode}}for(const[e,t]of s.entries())n.set(e,new St(t));for(const[e,t]of i.entries())r.set(e,new St(t));return[n,r]}addMatchingSelectors(e,t,n){for(const r of n){const n=t.selectors[r];n&&this.setSelectorMatches(e,n.text,!0)}}node(){return this.#Hn}cssModel(){return this.#Sn}hasMatchingSelectors(e){return this.getMatchingSelectors(e).length>0&&this.queryMatches(e.style)}getParentLayoutNodeId(){return this.#$n}getMatchingSelectors(e){const t=this.nodeForStyle(e.style);if(!t||"number"!=typeof t.id)return[];const n=this.#_n.get(t.id);if(!n)return[];const r=[];for(let t=0;t=0;e--){const t=this.styles[e],n=t.parentRule;if((!n||n instanceof gt)&&(!n||this.#Xn.hasMatchingSelectors(n)))for(const e of t.allProperties()){const n=v();if(this.#Jn&&!this.#Yn&&!n.isPropertyInherited(e.name))continue;if(t.range&&!e.range)continue;if(!e.activeInStyle()){this.propertiesState.set(e,bt.Overloaded);continue}const r=n.canonicalPropertyName(e.name);this.updatePropertyState(e,r);for(const t of e.getLonghandProperties())n.isCSSPropertyName(t.name)&&this.updatePropertyState(t,t.name)}}}updatePropertyState(e,t){const n=this.activeProperties.get(t);!n?.important||e.important?(n&&this.propertiesState.set(n,bt.Overloaded),this.propertiesState.set(e,bt.Active),this.activeProperties.set(t,e)):this.propertiesState.set(e,bt.Overloaded)}}class St{#Zn;#er;#tr;#nr;#rr;#sr;constructor(e){this.#Zn=e,this.#er=new Map,this.#tr=new Map,this.#nr=new Map,this.#rr=!1,this.#sr=new Map;for(const t of e)for(const e of t.styles)this.#sr.set(e,t)}findAvailableCSSVariables(e){const t=this.#sr.get(e);if(!t)return[];this.ensureInitialized();const n=this.#tr.get(t);return n?Array.from(n.keys()):[]}computeCSSVariable(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);return r&&s?this.innerComputeCSSVariable(r,s,t):null}computeValue(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);return r&&s?this.innerComputeValue(r,s,t):null}computeSingleVariableValue(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);if(!r||!s)return null;const i=this.innerComputeValue(r,s,t),{variableName:a}=vt(t);return{computedValue:i,fromFallback:null!==a&&!r.has(a)}}innerComputeCSSVariable(e,t,n){if(!e.has(n))return null;if(t.has(n))return t.get(n)||null;t.set(n,null);const r=e.get(n);if(null==r)return null;const s=this.innerComputeValue(e,t,r);return t.set(n,s),s}innerComputeValue(e,t,n){const s=r.TextUtils.Utils.splitStringByRegexes(n,[f]),i=[];for(const n of s){if(-1===n.regexIndex){i.push(n.value);continue}const{variableName:r,fallback:s}=vt(n.value);if(!r)return null;const a=this.innerComputeCSSVariable(e,t,r);if(null===a&&!s)return null;null===a?i.push(s):i.push(a)}return i.map((e=>e?e.trim():"")).join(" ")}styles(){return Array.from(this.#sr.keys())}propertyState(e){return this.ensureInitialized(),this.#er.get(e)||null}reset(){this.#rr=!1,this.#er.clear(),this.#tr.clear(),this.#nr.clear()}ensureInitialized(){if(this.#rr)return;this.#rr=!0;const e=new Map;for(const t of this.#Zn){t.computeActiveProperties();for(const[n,r]of t.propertiesState){if(r===bt.Overloaded){this.#er.set(n,bt.Overloaded);continue}const t=v().canonicalPropertyName(n.name);e.has(t)?this.#er.set(n,bt.Overloaded):(e.set(t,n),this.#er.set(n,bt.Active))}}for(const[t,n]of e){const r=n.ownerStyle,s=n.getLonghandProperties();if(!s.length)continue;let i=!1;for(const t of s){const n=v().canonicalPropertyName(t.name),s=e.get(n);if(s&&s.ownerStyle===r){i=!0;break}}i||(e.delete(t),this.#er.set(n,bt.Overloaded))}const t=new Map;for(let e=this.#Zn.length-1;e>=0;--e){const n=this.#Zn[e],r=[];for(const e of n.activeProperties.entries()){const n=e[0],s=e[1];n.startsWith("--")&&(t.set(n,s.value),r.push(n))}const s=new Map(t),i=new Map;this.#tr.set(n,s),this.#nr.set(n,i);for(const e of r)t.delete(e),t.set(e,this.innerComputeCSSVariable(s,i,e))}}}!function(e){e.Active="Active",e.Overloaded="Overloaded"}(bt||(bt={}));var wt=Object.freeze({__proto__:null,parseCSSVariableNameAndFallback:vt,CSSMatchedStyles:It,get PropertyState(){return bt}});const Ct={couldNotFindTheOriginalStyle:"Could not find the original style sheet.",thereWasAnErrorRetrievingThe:"There was an error retrieving the source styles."},Tt=s.i18n.registerUIStrings("core/sdk/CSSStyleSheetHeader.ts",Ct),Rt=s.i18n.getLocalizedString.bind(void 0,Tt);class xt{#Sn;id;frameId;sourceURL;hasSourceURL;origin;title;disabled;isInline;isMutable;isConstructed;startLine;startColumn;endLine;endColumn;contentLength;ownerNode;sourceMapURL;loadingFailed;#ir;constructor(e,t){this.#Sn=e,this.id=t.styleSheetId,this.frameId=t.frameId,this.sourceURL=t.sourceURL,this.hasSourceURL=Boolean(t.hasSourceURL),this.origin=t.origin,this.title=t.title,this.disabled=t.disabled,this.isInline=t.isInline,this.isMutable=t.isMutable,this.isConstructed=t.isConstructed,this.startLine=t.startLine,this.startColumn=t.startColumn,this.endLine=t.endLine,this.endColumn=t.endColumn,this.contentLength=t.length,t.ownerNode&&(this.ownerNode=new Rn(e.target(),t.ownerNode)),this.sourceMapURL=t.sourceMapURL,this.loadingFailed=t.loadingFailed??!1,this.#ir=null}originalContentProvider(){if(!this.#ir){const e=async()=>{const e=await this.#Sn.originalStyleSheetText(this);return null===e?{content:null,error:Rt(Ct.couldNotFindTheOriginalStyle),isEncoded:!1}:{content:e,isEncoded:!1}};this.#ir=new r.StaticContentProvider.StaticContentProvider(this.contentURL(),this.contentType(),e)}return this.#ir}setSourceMapURL(e){this.sourceMapURL=e}cssModel(){return this.#Sn}isAnonymousInlineStyleSheet(){return!this.resourceURL()&&!this.#Sn.sourceMapManager().sourceMapForClient(this)}isConstructedByNew(){return this.isConstructed&&0===this.sourceURL.length}resourceURL(){const e=this.isViaInspector()?this.viaInspectorResourceURL():this.sourceURL;return!e&&o.Runtime.experiments.isEnabled(o.Runtime.ExperimentName.STYLES_PANE_CSS_CHANGES)?this.dynamicStyleURL():e}getFrameURLPath(){const t=this.#Sn.target().model(jn);if(console.assert(Boolean(t)),!t)return"";const n=t.frameForId(this.frameId);if(!n)return"";console.assert(Boolean(n));const r=new e.ParsedURL.ParsedURL(n.url);let s=r.host+r.folderPathComponents;return s.endsWith("/")||(s+="/"),s}viaInspectorResourceURL(){return`inspector://${this.getFrameURLPath()}inspector-stylesheet`}dynamicStyleURL(){return`stylesheet://${this.getFrameURLPath()}style#${this.id}`}lineNumberInSource(e){return this.startLine+e}columnNumberInSource(e,t){return(e?0:this.startColumn)+t}containsLocation(e,t){const n=e===this.startLine&&t>=this.startColumn||e>this.startLine,r=ee.isOutermostFrame()));this.#dr=e.length>0?e[0]:null}getFrame(e){const t=this.#or.get(e);return t?t.frame:null}getAllFrames(){return Array.from(this.#or.values(),(e=>e.frame))}getOutermostFrame(){return this.#dr}async getOrWaitForFrame(e,t){const n=this.getFrame(e);return!n||t&&t===n.resourceTreeModel().target()?new Promise((n=>{const r=this.#hr.get(e);r?r.push({notInTarget:t,resolve:n}):this.#hr.set(e,[{notInTarget:t,resolve:n}])})):n}resolveAwaitedFrame(e){const t=this.#hr.get(e.id);if(!t)return;const n=t.filter((({notInTarget:t,resolve:n})=>!(!t||t!==e.resourceTreeModel().target())||(n(e),!1)));n.length>0?this.#hr.set(e.id,n):this.#hr.delete(e.id)}}var Et;!function(e){e.FrameAddedToTarget="FrameAddedToTarget",e.FrameNavigated="FrameNavigated",e.FrameRemoved="FrameRemoved",e.ResourceAdded="ResourceAdded",e.OutermostFrameNavigated="OutermostFrameNavigated"}(Et||(Et={}));var At=Object.freeze({__proto__:null,FrameManager:Lt,get Events(){return Et}});class Ot extends c{constructor(e){super(e)}async read(t,n,r){const s=await this.target().ioAgent().invoke_read({handle:t,offset:r,size:n});if(s.getError())throw new Error(s.getError());return s.eof?null:s.base64Encoded?e.Base64.decode(s.data):s.data}async close(e){(await this.target().ioAgent().invoke_close({handle:e})).getError()&&console.error("Could not close stream.")}async resolveBlob(e){const t=e instanceof Le?e.objectId:e;if(!t)throw new Error("Remote object has undefined objectId");const n=await this.target().ioAgent().invoke_resolveBlob({objectId:t});if(n.getError())throw new Error(n.getError());return`blob:${n.uuid}`}async readToString(e){const t=[],n=new TextDecoder;for(;;){const r=await this.read(e,1048576);if(null===r){t.push(n.decode());break}r instanceof ArrayBuffer?t.push(n.decode(r,{stream:!0})):t.push(r)}return t.join("")}}c.register(Ot,{capabilities:z.IO,autostart:!0});var Nt=Object.freeze({__proto__:null,IOModel:Ot});const Ft={loadCanceledDueToReloadOf:"Load canceled due to reload of inspected page"},Bt=s.i18n.registerUIStrings("core/sdk/PageResourceLoader.ts",Ft),Dt=s.i18n.getLocalizedString.bind(void 0,Bt);let Ut=null;class Ht extends e.ObjectWrapper.ObjectWrapper{#ur;#gr;#pr;#mr;#fr;constructor(e,t){super(),this.#ur=0,this.#gr=t,this.#pr=new Map,this.#mr=[],K.instance().addModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),this.#fr=e}static instance({forceNew:e,loadOverride:t,maxConcurrentLoads:n}={forceNew:!1,loadOverride:null,maxConcurrentLoads:500}){return Ut&&!e||(Ut=new Ht(t,n)),Ut}static removeInstance(){Ut=null}onPrimaryPageChanged(e){if(e.data.frame.isOutermostFrame()){for(const{reject:e}of this.#mr)e(new Error(Dt(Ft.loadCanceledDueToReloadOf)));this.#mr=[],this.#pr.clear(),this.dispatchEventToListeners(_t.Update)}}getResourcesLoaded(){return this.#pr}getNumberOfResources(){return{loading:this.#ur,queued:this.#mr.length,resources:this.#pr.size}}async acquireLoadSlot(){if(this.#ur++,this.#ur>this.#gr){const e={resolve:()=>{},reject:()=>{}},t=new Promise(((t,n)=>{e.resolve=t,e.reject=n}));this.#mr.push(e),await t}}releaseLoadSlot(){this.#ur--;const e=this.#mr.shift();e&&e.resolve()}static makeKey(e,t){if(t.frameId)return`${e}-${t.frameId}`;if(t.target)return`${e}-${t.target.id()}`;throw new Error("Invalid initiator")}async loadResource(e,t){const n=Ht.makeKey(e,t),r={success:null,size:null,errorMessage:void 0,url:e,initiator:t};this.#pr.set(n,r),this.dispatchEventToListeners(_t.Update);try{await this.acquireLoadSlot();const n=this.dispatchLoad(e,t),s=await n;if(r.errorMessage=s.errorDescription.message,r.success=s.success,s.success)return r.size=s.content.length,{content:s.content};throw new Error(s.errorDescription.message)}catch(e){throw void 0===r.errorMessage&&(r.errorMessage=e.message),null===r.success&&(r.success=!1),e}finally{this.releaseLoadSlot(),this.dispatchEventToListeners(_t.Update)}}async dispatchLoad(t,n){let r=null;if(this.#fr)return this.#fr(t);const s=new e.ParsedURL.ParsedURL(t),a=qt().get()&&s&&"file"!==s.scheme&&"data"!==s.scheme&&"devtools"!==s.scheme;if(i.userMetrics.developerResourceScheme(this.getDeveloperResourceScheme(s)),a){try{if(n.target){i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageViaTarget);return await this.loadFromTarget(n.target,n.frameId,t)}const e=Lt.instance().getFrame(n.frameId);if(e){i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageViaFrame);return await this.loadFromTarget(e.resourceTreeModel().target(),n.frameId,t)}}catch(e){e instanceof Error&&(i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageFailure),r=e.message)}i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageFallback),console.warn("Fallback triggered",t,n)}else{const e=qt().get()?i.UserMetrics.DeveloperResourceLoaded.FallbackPerProtocol:i.UserMetrics.DeveloperResourceLoaded.FallbackPerOverride;i.userMetrics.developerResourceLoaded(e)}const o=await ue.instance().loadResource(t);return a&&!o.success&&i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.FallbackFailure),r&&(o.errorDescription.message=`Fetch through target failed: ${r}; Fallback: ${o.errorDescription.message}`),o}getDeveloperResourceScheme(e){if(!e||""===e.scheme)return i.UserMetrics.DeveloperResourceScheme.SchemeUnknown;const t="localhost"===e.host||e.host.endsWith(".localhost");switch(e.scheme){case"file":return i.UserMetrics.DeveloperResourceScheme.SchemeFile;case"data":return i.UserMetrics.DeveloperResourceScheme.SchemeData;case"blob":return i.UserMetrics.DeveloperResourceScheme.SchemeBlob;case"http":return t?i.UserMetrics.DeveloperResourceScheme.SchemeHttpLocalhost:i.UserMetrics.DeveloperResourceScheme.SchemeHttp;case"https":return t?i.UserMetrics.DeveloperResourceScheme.SchemeHttpsLocalhost:i.UserMetrics.DeveloperResourceScheme.SchemeHttps}return i.UserMetrics.DeveloperResourceScheme.SchemeOther}async loadFromTarget(t,n,r){const s=t.model(ne),a=t.model(Ot),o=e.Settings.Settings.instance().moduleSetting("cacheDisabled").get(),l=await s.loadNetworkResource(n,r,{disableCache:o,includeCredentials:!0});try{const e=l.stream?await a.readToString(l.stream):"";return{success:l.success,content:e,errorDescription:{statusCode:l.httpStatusCode||0,netError:l.netError,netErrorName:l.netErrorName,message:i.ResourceLoader.netErrorToMessage(l.netError,l.httpStatusCode,l.netErrorName)||"",urlValid:void 0}}}finally{l.stream&&a.close(l.stream)}}}function qt(){return e.Settings.Settings.instance().createSetting("loadThroughTarget",!0)}var _t;(_t||(_t={})).Update="Update";var zt=Object.freeze({__proto__:null,PageResourceLoader:Ht,getLoadThroughTargetSetting:qt,get Events(){return _t}});function jt(e){return e.startsWith(")]}")&&(e=e.substring(e.indexOf("\n"))),65279===e.charCodeAt(0)&&(e=e.slice(1)),JSON.parse(e)}class Wt{lineNumber;columnNumber;sourceURL;sourceLineNumber;sourceColumnNumber;name;constructor(e,t,n,r,s,i){this.lineNumber=e,this.columnNumber=t,this.sourceURL=n,this.sourceLineNumber=r,this.sourceColumnNumber=s,this.name=i}static compare(e,t){return e.lineNumber!==t.lineNumber?e.lineNumber-t.lineNumber:e.columnNumber-t.columnNumber}}const Vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Gt=new Map;for(let e=0;e"url"in e))&&e.Console.Console.instance().warn(`SourceMap "${n}" contains unsupported "URL" field in one of its sections.`),this.eachSection(this.parseSources.bind(this))}compiledURL(){return this.#yr}url(){return this.#vr}sourceURLs(){return[...this.#Sr.keys()]}embeddedContentByURL(e){const t=this.#Sr.get(e);return t?t.content:null}findEntry(e,n){const r=this.mappings(),s=t.ArrayUtilities.upperBound(r,void 0,((t,r)=>e-r.lineNumber||n-r.columnNumber));return s?r[s-1]:null}findEntryRanges(e,n){const s=this.mappings(),i=t.ArrayUtilities.upperBound(s,void 0,((t,r)=>e-r.lineNumber||n-r.columnNumber));if(!i)return null;const a=i-1,o=s[a].sourceURL;if(!o)return null;const l=iu-s[t].sourceLineNumber||g-s[t].sourceColumnNumber));if(!p)return null;const m=p=i.length||s[i[a]].sourceLineNumber!==n)return null;const l=i.slice(a,o);if(!l.length)return null;const d=t.ArrayUtilities.lowerBound(l,r,((e,t)=>e-s[t].sourceColumnNumber));return d>=l.length?s[l[l.length-1]]:s[l[d]];function c(e,t){return e-s[t].sourceLineNumber}}findReverseIndices(e,n,r){const s=this.mappings(),i=this.reversedMappings(e),a=t.ArrayUtilities.upperBound(i,void 0,((e,t)=>n-s[t].sourceLineNumber||r-s[t].sourceColumnNumber));let o=a;for(;o>0&&s[i[o-1]].sourceLineNumber===s[i[a-1]].sourceLineNumber&&s[i[o-1]].sourceColumnNumber===s[i[a-1]].sourceColumnNumber;)--o;return i.slice(o,a)}findReverseEntries(e,t,n){const r=this.mappings();return this.findReverseIndices(e,t,n).map((e=>r[e]))}findReverseRanges(e,t,n){const s=this.mappings(),i=this.findReverseIndices(e,t,n),a=[];for(let e=0;e>=1,s?-t:t}reverseMapTextRanges(e,n){const s=this.reversedMappings(e),i=this.mappings();if(0===s.length)return[];let a=t.ArrayUtilities.lowerBound(s,n,(({startLine:e,startColumn:t},n)=>{const{sourceLineNumber:r,sourceColumnNumber:s}=i[n];return e-r||t-s}));for(;a===s.length||a>0&&(i[s[a]].sourceLineNumber>n.startLine||i[s[a]].sourceColumnNumber>n.startColumn);)a--;let o=a+1;for(;o0){const t=e[0];return 0===t?.lineNumber||0===t.columnNumber}return!1}hasIgnoreListHint(e){return this.#Sr.get(e)?.ignoreListHint??!1}findRanges(e,t){const n=this.mappings(),s=[];if(!n.length)return[];let i=null;0===n[0].lineNumber&&0===n[0].columnNumber||!t?.isStartMatching||(i=r.TextRange.TextRange.createUnboundedFromLocation(0,0),s.push(i));for(const{sourceURL:t,lineNumber:a,columnNumber:o}of n){const n=t&&e(t);i||!n?i&&!n&&(i.endLine=a,i.endColumn=o,i=null):(i=r.TextRange.TextRange.createUnboundedFromLocation(a,o),s.push(i))}return s}compatibleForURL(e,t){return this.embeddedContentByURL(e)===t.embeddedContentByURL(e)&&this.hasIgnoreListHint(e)===t.hasIgnoreListHint(e)}}!function(e){e._VLQ_BASE_SHIFT=5,e._VLQ_BASE_MASK=31,e._VLQ_CONTINUATION_MASK=32;e.StringCharIterator=class{string;position;constructor(e){this.string=e,this.position=0}next(){return this.string.charAt(this.position++)}peek(){return this.string.charAt(this.position)}hasNext(){return this.position{const n=new $t(i,a,e);return this.#Rr.get(t)===s&&(s.sourceMap=n,this.#xr.set(n,t),this.dispatchEventToListeners(Qt.SourceMapAttached,{client:t,sourceMap:n})),n}),(n=>{e.Console.Console.instance().warn(`DevTools failed to load source map: ${n.message}`),this.#Rr.get(t)===s&&this.dispatchEventToListeners(Qt.SourceMapFailedToAttach,{client:t})}))}}this.#Rr.set(t,s)}detachSourceMap(e){const t=this.#Rr.get(e);if(!t)return;if(this.#Rr.delete(e),!this.#Tr)return;const{sourceMap:n}=t;n?(this.#xr.delete(n),this.dispatchEventToListeners(Qt.SourceMapDetached,{client:e,sourceMap:n})):this.dispatchEventToListeners(Qt.SourceMapFailedToAttach,{client:e})}dispose(){K.instance().removeEventListener($.InspectedURLChanged,this.inspectedURLChanged,this)}}!function(e){e.SourceMapWillAttach="SourceMapWillAttach",e.SourceMapFailedToAttach="SourceMapFailedToAttach",e.SourceMapAttached="SourceMapAttached",e.SourceMapDetached="SourceMapDetached"}(Qt||(Qt={}));var Yt,Zt=Object.freeze({__proto__:null,SourceMapManager:Jt,get Events(){return Qt}});class en extends c{agent;#Mr;#Pr;#Lr;#Er;#Ar;#Or;#Nr;#Fr;#Br;#Dr;#Ur;#Hr;#qr;#Tr;#_r;#zr;constructor(t){super(t),this.#Tr=!1,this.#Dr=null,this.#Ur=null,this.#Mr=t.model(Pn),this.#Ar=new Jt(t),this.agent=t.cssAgent(),this.#Or=new an(this),this.#Er=t.model(jn),this.#Er&&this.#Er.addEventListener(_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),t.registerCSSDispatcher(new sn(this)),t.suspended()||this.enable(),this.#Br=new Map,this.#Fr=new Map,this.#Lr=new Map,this.#_r=!1,this.#Pr=new Map,this.#Hr=null,this.#qr=!1,this.#zr=!1,this.#Nr=new e.Throttler.Throttler(dn),this.#Ar.setEnabled(e.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").get()),e.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").addChangeListener((e=>this.#Ar.setEnabled(e.data)))}headersForSourceURL(e){const t=[];for(const n of this.getStyleSheetIdsForURL(e)){const e=this.styleSheetHeaderForId(n);e&&t.push(e)}return t}createRawLocationsByURL(e,n,r=0){const s=this.headersForSourceURL(e);s.sort((function(e,t){return e.startLine-t.startLine||e.startColumn-t.startColumn||e.id.localeCompare(t.id)}));const i=t.ArrayUtilities.upperBound(s,void 0,((e,t)=>n-t.startLine||r-t.startColumn));if(!i)return[];const a=[],o=s[i-1];for(let e=i-1;e>=0&&s[e].startLine===o.startLine&&s[e].startColumn===o.startColumn;--e)s[e].containsLocation(n,r)&&a.push(new rn(s[e],n,r));return a}sourceMapManager(){return this.#Ar}static readableLayerName(e){return e||""}static trimSourceURL(e){let t=e.lastIndexOf("/*# sourceURL=");if(-1===t&&(t=e.lastIndexOf("/*@ sourceURL="),-1===t))return e;const n=e.lastIndexOf("\n",t);if(-1===n)return e;const r=e.substr(n+1).split("\n",1)[0];return-1===r.search(/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/)?e:e.substr(0,n)+e.substr(n+r.length+1)}domModel(){return this.#Mr}async setStyleText(e,t,n,r){try{await this.ensureOriginalStyleSheetText(e);const{styles:s}=await this.agent.invoke_setStyleTexts({edits:[{styleSheetId:e,range:t.serializeToObject(),text:n}]});if(!s||1!==s.length)return!1;this.#Mr.markUndoableState(!r);const i=new nn(e,t,n,s[0]);return this.fireStyleSheetChanged(e,i),!0}catch(e){return!1}}async setSelectorText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{selectorList:r}=await this.agent.invoke_setRuleSelector({styleSheetId:e,range:t,selector:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setKeyframeKey(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{keyText:r}=await this.agent.invoke_setKeyframeKey({styleSheetId:e,range:t,keyText:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}startCoverage(){return this.#_r=!0,this.agent.invoke_startRuleUsageTracking()}async takeCoverageDelta(){const e=await this.agent.invoke_takeCoverageDelta();return{timestamp:e&&e.timestamp||0,coverage:e&&e.coverage||[]}}setLocalFontsEnabled(e){return this.agent.invoke_setLocalFontsEnabled({enabled:e})}async stopCoverage(){this.#_r=!1,await this.agent.invoke_stopRuleUsageTracking()}async getMediaQueries(){const{medias:e}=await this.agent.invoke_getMediaQueries();return e?et.parseMediaArrayPayload(this,e):[]}async getRootLayer(e){const{rootLayer:t}=await this.agent.invoke_getLayersForNode({nodeId:e});return t}isEnabled(){return this.#Tr}async enable(){await this.agent.invoke_enable(),this.#Tr=!0,this.#_r&&await this.startCoverage(),this.dispatchEventToListeners(Yt.ModelWasEnabled)}async getMatchedStyles(e){const t=await this.agent.invoke_getMatchedStylesForNode({nodeId:e});if(t.getError())return null;const n=this.#Mr.nodeForId(e);return n?new It({cssModel:this,node:n,inlinePayload:t.inlineStyle||null,attributesPayload:t.attributesStyle||null,matchedPayload:t.matchedCSSRules||[],pseudoPayload:t.pseudoElements||[],inheritedPayload:t.inherited||[],inheritedPseudoPayload:t.inheritedPseudoElements||[],animationsPayload:t.cssKeyframesRules||[],parentLayoutNodeId:t.parentLayoutNodeId,positionFallbackRules:t.cssPositionFallbackRules||[]}):null}async getClassNames(e){const{classNames:t}=await this.agent.invoke_collectClassNames({styleSheetId:e});return t||[]}async getComputedStyle(e){return this.isEnabled()||await this.enable(),this.#Or.computedStylePromise(e)}async getBackgroundColors(e){const t=await this.agent.invoke_getBackgroundColors({nodeId:e});return t.getError()?null:{backgroundColors:t.backgroundColors||null,computedFontSize:t.computedFontSize||"",computedFontWeight:t.computedFontWeight||""}}async getPlatformFonts(e){const{fonts:t}=await this.agent.invoke_getPlatformFontsForNode({nodeId:e});return t}allStyleSheets(){const e=[...this.#Br.values()];return e.sort((function(e,t){return e.sourceURLt.sourceURL?1:e.startLine-t.startLine||e.startColumn-t.startColumn})),e}async getInlineStyles(e){const t=await this.agent.invoke_getInlineStylesForNode({nodeId:e});if(t.getError()||!t.inlineStyle)return null;const n=new dt(this,null,t.inlineStyle,ot.Inline),r=t.attributesStyle?new dt(this,null,t.attributesStyle,ot.Attributes):null;return new on(n,r)}forcePseudoState(e,n,r){const s=e.marker(tn)||[],i=s.includes(n);if(r){if(i)return!1;s.push(n),e.setMarker(tn,s)}else{if(!i)return!1;t.ArrayUtilities.removeElement(s,n),s.length?e.setMarker(tn,s):e.setMarker(tn,null)}return void 0!==e.id&&(this.agent.invoke_forcePseudoState({nodeId:e.id,forcedPseudoClasses:s}),this.dispatchEventToListeners(Yt.PseudoStateForced,{node:e,pseudoClass:n,enable:r}),!0)}pseudoState(e){return e.marker(tn)||[]}async setMediaText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{media:r}=await this.agent.invoke_setMediaText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setContainerQueryText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{containerQuery:r}=await this.agent.invoke_setContainerQueryText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setSupportsText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{supports:r}=await this.agent.invoke_setSupportsText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setScopeText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{scope:r}=await this.agent.invoke_setScopeText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return console.error(e),!1}}async addRule(e,t,n){try{await this.ensureOriginalStyleSheetText(e);const{rule:r}=await this.agent.invoke_addRule({styleSheetId:e,ruleText:t,location:n});if(!r)return null;this.#Mr.markUndoableState();const s=new nn(e,n,t,r);return this.fireStyleSheetChanged(e,s),new gt(this,r)}catch(e){return null}}async requestViaInspectorStylesheet(e){const t=e.frameId()||(this.#Er&&this.#Er.mainFrame?this.#Er.mainFrame.id:null),n=[...this.#Br.values()].find((e=>e.frameId===t&&e.isViaInspector()));if(n)return n;if(!t)return null;try{const{styleSheetId:e}=await this.agent.invoke_createStyleSheet({frameId:t});return e&&this.#Br.get(e)||null}catch(e){return null}}mediaQueryResultChanged(){this.dispatchEventToListeners(Yt.MediaQueryResultChanged)}fontsUpdated(e){e&&this.#Pr.set(e.src,new _e(e)),this.dispatchEventToListeners(Yt.FontsUpdated)}fontFaces(){return[...this.#Pr.values()]}fontFaceForSource(e){return this.#Pr.get(e)}styleSheetHeaderForId(e){return this.#Br.get(e)||null}styleSheetHeaders(){return[...this.#Br.values()]}fireStyleSheetChanged(e,t){this.dispatchEventToListeners(Yt.StyleSheetChanged,{styleSheetId:e,edit:t})}ensureOriginalStyleSheetText(e){const t=this.styleSheetHeaderForId(e);if(!t)return Promise.resolve(null);let n=this.#Lr.get(t);return n||(n=this.getStyleSheetText(t.id),this.#Lr.set(t,n),this.originalContentRequestedForTest(t)),n}originalContentRequestedForTest(e){}originalStyleSheetText(e){return this.ensureOriginalStyleSheetText(e.id)}getAllStyleSheetHeaders(){return this.#Br.values()}styleSheetAdded(e){console.assert(!this.#Br.get(e.styleSheetId)),e.loadingFailed&&(e.hasSourceURL=!1,e.isConstructed=!0,e.isInline=!1,e.isMutable=!1,e.sourceURL="",e.sourceMapURL=void 0);const t=new xt(this,e);this.#Br.set(e.styleSheetId,t);const n=t.resourceURL();let r=this.#Fr.get(n);if(r||(r=new Map,this.#Fr.set(n,r)),r){let e=r.get(t.frameId);e||(e=new Set,r.set(t.frameId,e)),e.add(t.id)}this.#Ar.attachSourceMap(t,t.sourceURL,t.sourceMapURL),this.dispatchEventToListeners(Yt.StyleSheetAdded,t)}styleSheetRemoved(e){const t=this.#Br.get(e);if(console.assert(Boolean(t)),!t)return;this.#Br.delete(e);const n=t.resourceURL(),r=this.#Fr.get(n);if(console.assert(Boolean(r),"No frameId to styleSheetId map is available for given style sheet URL."),r){const s=r.get(t.frameId);s&&(s.delete(e),s.size||(r.delete(t.frameId),r.size||this.#Fr.delete(n)))}this.#Lr.delete(t),this.#Ar.detachSourceMap(t),this.dispatchEventToListeners(Yt.StyleSheetRemoved,t)}getStyleSheetIdsForURL(e){const t=this.#Fr.get(e);if(!t)return[];const n=[];for(const e of t.values())n.push(...e);return n}async setStyleSheetText(e,t,n){const r=this.#Br.get(e);if(!r)return"Unknown stylesheet in CSS.setStyleSheetText";t=en.trimSourceURL(t),r.hasSourceURL&&(t+="\n/*# sourceURL="+r.sourceURL+" */"),await this.ensureOriginalStyleSheetText(e);const s=(await this.agent.invoke_setStyleSheetText({styleSheetId:r.id,text:t})).sourceMapURL;return this.#Ar.detachSourceMap(r),r.setSourceMapURL(s),this.#Ar.attachSourceMap(r,r.sourceURL,r.sourceMapURL),null===s?"Error in CSS.setStyleSheetText":(this.#Mr.markUndoableState(!n),this.fireStyleSheetChanged(e),null)}async getStyleSheetText(e){try{const{text:t}=await this.agent.invoke_getStyleSheetText({styleSheetId:e});return t&&en.trimSourceURL(t)}catch(e){return null}}async onPrimaryPageChanged(e){e.data.frame.backForwardCacheDetails.restoredFromCache?(await this.suspendModel(),await this.resumeModel()):(this.resetStyleSheets(),this.resetFontFaces())}resetStyleSheets(){const e=[...this.#Br.values()];this.#Fr.clear(),this.#Br.clear();for(const t of e)this.#Ar.detachSourceMap(t),this.dispatchEventToListeners(Yt.StyleSheetRemoved,t)}resetFontFaces(){this.#Pr.clear()}async suspendModel(){this.#Tr=!1,await this.agent.invoke_disable(),this.resetStyleSheets(),this.resetFontFaces()}async resumeModel(){return this.enable()}setEffectivePropertyValueForNode(e,t,n){this.agent.invoke_setEffectivePropertyValueForNode({nodeId:e,propertyName:t,value:n})}cachedMatchedCascadeForNode(e){if(this.#Dr!==e&&this.discardCachedMatchedCascade(),this.#Dr=e,!this.#Ur){if(!e.id)return Promise.resolve(null);this.#Ur=this.getMatchedStyles(e.id)}return this.#Ur}discardCachedMatchedCascade(){this.#Dr=null,this.#Ur=null}createCSSPropertyTracker(e){return new ln(this,e)}enableCSSPropertyTracker(e){const t=e.getTrackedProperties();0!==t.length&&(this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:t}),this.#qr=!0,this.#Hr=e,this.pollComputedStyleUpdates())}disableCSSPropertyTracker(){this.#qr=!1,this.#Hr=null,this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:[]})}async pollComputedStyleUpdates(){if(!this.#zr){if(this.#qr){this.#zr=!0;const e=await this.agent.invoke_takeComputedStyleUpdates();if(this.#zr=!1,e.getError()||!e.nodeIds||!this.#qr)return;this.#Hr&&this.#Hr.dispatchEventToListeners(cn.TrackedCSSPropertiesUpdated,e.nodeIds.map((e=>this.#Mr.nodeForId(e))))}this.#qr&&this.#Nr.schedule(this.pollComputedStyleUpdates.bind(this))}}dispose(){this.disableCSSPropertyTracker(),super.dispose(),this.#Ar.dispose()}getAgent(){return this.agent}}!function(e){e.FontsUpdated="FontsUpdated",e.MediaQueryResultChanged="MediaQueryResultChanged",e.ModelWasEnabled="ModelWasEnabled",e.PseudoStateForced="PseudoStateForced",e.StyleSheetAdded="StyleSheetAdded",e.StyleSheetChanged="StyleSheetChanged",e.StyleSheetRemoved="StyleSheetRemoved"}(Yt||(Yt={}));const tn="pseudo-state-marker";class nn{styleSheetId;oldRange;newRange;newText;payload;constructor(e,t,n,s){this.styleSheetId=e,this.oldRange=t,this.newRange=r.TextRange.TextRange.fromEdit(t,n),this.newText=n,this.payload=s}}class rn{#Sn;styleSheetId;url;lineNumber;columnNumber;constructor(e,t,n){this.#Sn=e.cssModel(),this.styleSheetId=e.id,this.url=e.resourceURL(),this.lineNumber=t,this.columnNumber=n||0}cssModel(){return this.#Sn}header(){return this.#Sn.styleSheetHeaderForId(this.styleSheetId)}}class sn{#jr;constructor(e){this.#jr=e}mediaQueryResultChanged(){this.#jr.mediaQueryResultChanged()}fontsUpdated({font:e}){this.#jr.fontsUpdated(e)}styleSheetChanged({styleSheetId:e}){this.#jr.fireStyleSheetChanged(e)}styleSheetAdded({header:e}){this.#jr.styleSheetAdded(e)}styleSheetRemoved({styleSheetId:e}){this.#jr.styleSheetRemoved(e)}}class an{#jr;#Wr;constructor(e){this.#jr=e,this.#Wr=new Map}computedStylePromise(e){let t=this.#Wr.get(e);return t||(t=this.#jr.getAgent().invoke_getComputedStyleForNode({nodeId:e}).then((({computedStyle:t})=>{if(this.#Wr.delete(e),!t||!t.length)return null;const n=new Map;for(const e of t)n.set(e.name,e.value);return n})),this.#Wr.set(e,t),t)}}class on{inlineStyle;attributesStyle;constructor(e,t){this.inlineStyle=e,this.attributesStyle=t}}class ln extends e.ObjectWrapper.ObjectWrapper{#jr;#Vr;constructor(e,t){super(),this.#jr=e,this.#Vr=t}start(){this.#jr.enableCSSPropertyTracker(this)}stop(){this.#jr.disableCSSPropertyTracker()}getTrackedProperties(){return this.#Vr}}const dn=1e3;var cn;!function(e){e.TrackedCSSPropertiesUpdated="TrackedCSSPropertiesUpdated"}(cn||(cn={})),c.register(en,{capabilities:z.DOM,autostart:!0});var hn=Object.freeze({__proto__:null,CSSModel:en,get Events(){return Yt},Edit:nn,CSSLocation:rn,InlineStyleResult:on,CSSPropertyTracker:ln,get CSSPropertyTrackerEvents(){return cn}});class un{#Gr;#Kr;constructor(){const t="rgba";this.#Gr=[new e.Color.Legacy([.9607843137254902,.592156862745098,.5803921568627451,1],t),new e.Color.Legacy([.9411764705882353,.7490196078431373,.2980392156862745,1],t),new e.Color.Legacy([.8313725490196079,.9294117647058824,.19215686274509805,1],t),new e.Color.Legacy([.6196078431372549,.9215686274509803,.2784313725490196,1],t),new e.Color.Legacy([.3568627450980392,.8196078431372549,.8431372549019608,1],t),new e.Color.Legacy([.7372549019607844,.807843137254902,.984313725490196,1],t),new e.Color.Legacy([.7764705882352941,.7450980392156863,.9333333333333333,1],t),new e.Color.Legacy([.8156862745098039,.5803921568627451,.9176470588235294,1],t),new e.Color.Legacy([.9215686274509803,.5803921568627451,.8117647058823529,1],t)],this.#Kr=0}next(){const e=this.#Gr[this.#Kr];return this.#Kr++,this.#Kr>=this.#Gr.length&&(this.#Kr=0),e}}var gn=Object.freeze({__proto__:null,OverlayColorGenerator:un});class pn{#$r;#Qr;#Xr;#Jr;#Yr;#Zr;#Gr;#es;#ts;#ns;#rs;#ss;#is;#as;constructor(t,n=!0){this.#$r=t,this.#Qr=new Map,this.#Xr=new Map,this.#Jr=new Map,this.#Yr=new Map,this.#Zr=new Map,this.#Gr=new Map,this.#es=new un,this.#ts=new un,this.#ns=n,this.#rs=e.Settings.Settings.instance().moduleSetting("showGridLineLabels"),this.#rs.addChangeListener(this.onSettingChange,this),this.#ss=e.Settings.Settings.instance().moduleSetting("extendGridLines"),this.#ss.addChangeListener(this.onSettingChange,this),this.#is=e.Settings.Settings.instance().moduleSetting("showGridAreas"),this.#is.addChangeListener(this.onSettingChange,this),this.#as=e.Settings.Settings.instance().moduleSetting("showGridTrackSizes"),this.#as.addChangeListener(this.onSettingChange,this)}onSettingChange(){this.resetOverlay()}buildGridHighlightConfig(e){const t=this.colorOfGrid(e).asLegacyColor(),n=t.setAlpha(.1).asLegacyColor(),r=t.setAlpha(.3).asLegacyColor(),s=t.setAlpha(.8).asLegacyColor(),i=this.#ss.get(),a="lineNumbers"===this.#rs.get(),o=a,l="lineNames"===this.#rs.get();return{rowGapColor:r.toProtocolRGBA(),rowHatchColor:s.toProtocolRGBA(),columnGapColor:r.toProtocolRGBA(),columnHatchColor:s.toProtocolRGBA(),gridBorderColor:t.toProtocolRGBA(),gridBorderDash:!1,rowLineColor:t.toProtocolRGBA(),columnLineColor:t.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0,showGridExtensionLines:i,showPositiveLineNumbers:a,showNegativeLineNumbers:o,showLineNames:l,showAreaNames:this.#is.get(),showTrackSizes:this.#as.get(),areaBorderColor:t.toProtocolRGBA(),gridBackgroundColor:n.toProtocolRGBA()}}buildFlexContainerHighlightConfig(e){const t=this.colorOfFlex(e).asLegacyColor();return{containerBorder:{color:t.toProtocolRGBA(),pattern:"dashed"},itemSeparator:{color:t.toProtocolRGBA(),pattern:"dotted"},lineSeparator:{color:t.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:t.toProtocolRGBA()},crossDistributedSpace:{hatchColor:t.toProtocolRGBA()}}}buildScrollSnapContainerHighlightConfig(t){return{snapAreaBorder:{color:e.Color.PageHighlight.GridBorder.toProtocolRGBA(),pattern:"dashed"},snapportBorder:{color:e.Color.PageHighlight.GridBorder.toProtocolRGBA()},scrollMarginColor:e.Color.PageHighlight.Margin.toProtocolRGBA(),scrollPaddingColor:e.Color.PageHighlight.Padding.toProtocolRGBA()}}highlightGridInOverlay(e){this.#Qr.set(e,this.buildGridHighlightConfig(e)),this.updateHighlightsInOverlay()}isGridHighlighted(e){return this.#Qr.has(e)}colorOfGrid(e){let t=this.#Gr.get(e);return t||(t=this.#es.next(),this.#Gr.set(e,t)),t}setColorOfGrid(e,t){this.#Gr.set(e,t)}hideGridInOverlay(e){this.#Qr.has(e)&&(this.#Qr.delete(e),this.updateHighlightsInOverlay())}highlightScrollSnapInOverlay(e){this.#Xr.set(e,this.buildScrollSnapContainerHighlightConfig(e)),this.updateHighlightsInOverlay()}isScrollSnapHighlighted(e){return this.#Xr.has(e)}hideScrollSnapInOverlay(e){this.#Xr.has(e)&&(this.#Xr.delete(e),this.updateHighlightsInOverlay())}highlightFlexInOverlay(e){this.#Jr.set(e,this.buildFlexContainerHighlightConfig(e)),this.updateHighlightsInOverlay()}isFlexHighlighted(e){return this.#Jr.has(e)}colorOfFlex(e){let t=this.#Gr.get(e);return t||(t=this.#ts.next(),this.#Gr.set(e,t)),t}setColorOfFlex(e,t){this.#Gr.set(e,t)}hideFlexInOverlay(e){this.#Jr.has(e)&&(this.#Jr.delete(e),this.updateHighlightsInOverlay())}highlightContainerQueryInOverlay(e){this.#Yr.set(e,this.buildContainerQueryContainerHighlightConfig()),this.updateHighlightsInOverlay()}hideContainerQueryInOverlay(e){this.#Yr.has(e)&&(this.#Yr.delete(e),this.updateHighlightsInOverlay())}isContainerQueryHighlighted(e){return this.#Yr.has(e)}buildContainerQueryContainerHighlightConfig(){return{containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},descendantBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}}}highlightIsolatedElementInOverlay(e){this.#Zr.set(e,this.buildIsolationModeHighlightConfig()),this.updateHighlightsInOverlay()}hideIsolatedElementInOverlay(e){this.#Zr.has(e)&&(this.#Zr.delete(e),this.updateHighlightsInOverlay())}isIsolatedElementHighlighted(e){return this.#Zr.has(e)}buildIsolationModeHighlightConfig(){return{resizerColor:e.Color.IsolationModeHighlight.Resizer.toProtocolRGBA(),resizerHandleColor:e.Color.IsolationModeHighlight.ResizerHandle.toProtocolRGBA(),maskColor:e.Color.IsolationModeHighlight.Mask.toProtocolRGBA()}}hideAllInOverlay(){this.#Jr.clear(),this.#Qr.clear(),this.#Xr.clear(),this.#Yr.clear(),this.#Zr.clear(),this.updateHighlightsInOverlay()}refreshHighlights(){const e=this.updateHighlightsForDeletedNodes(this.#Qr),t=this.updateHighlightsForDeletedNodes(this.#Jr),n=this.updateHighlightsForDeletedNodes(this.#Xr),r=this.updateHighlightsForDeletedNodes(this.#Yr),s=this.updateHighlightsForDeletedNodes(this.#Zr);(t||e||n||r||s)&&this.updateHighlightsInOverlay()}updateHighlightsForDeletedNodes(e){let t=!1;for(const n of e.keys())null===this.#$r.getDOMModel().nodeForId(n)&&(e.delete(n),t=!0);return t}resetOverlay(){for(const e of this.#Qr.keys())this.#Qr.set(e,this.buildGridHighlightConfig(e));for(const e of this.#Jr.keys())this.#Jr.set(e,this.buildFlexContainerHighlightConfig(e));for(const e of this.#Xr.keys())this.#Xr.set(e,this.buildScrollSnapContainerHighlightConfig(e));for(const e of this.#Yr.keys())this.#Yr.set(e,this.buildContainerQueryContainerHighlightConfig());for(const e of this.#Zr.keys())this.#Zr.set(e,this.buildIsolationModeHighlightConfig());this.updateHighlightsInOverlay()}updateHighlightsInOverlay(){const e=this.#Qr.size>0||this.#Jr.size>0||this.#Yr.size>0||this.#Zr.size>0;this.#$r.setShowViewportSizeOnResize(!e),this.updateGridHighlightsInOverlay(),this.updateFlexHighlightsInOverlay(),this.updateScrollSnapHighlightsInOverlay(),this.updateContainerQueryHighlightsInOverlay(),this.updateIsolatedElementHighlightsInOverlay()}updateGridHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Qr.entries())t.push({nodeId:e,gridHighlightConfig:n});e.target().overlayAgent().invoke_setShowGridOverlays({gridNodeHighlightConfigs:t})}updateFlexHighlightsInOverlay(){if(!this.#ns)return;const e=this.#$r,t=[];for(const[e,n]of this.#Jr.entries())t.push({nodeId:e,flexContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowFlexOverlays({flexNodeHighlightConfigs:t})}updateScrollSnapHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Xr.entries())t.push({nodeId:e,scrollSnapContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowScrollSnapOverlays({scrollSnapHighlightConfigs:t})}updateContainerQueryHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Yr.entries())t.push({nodeId:e,containerQueryContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowContainerQueryOverlays({containerQueryHighlightConfigs:t})}updateIsolatedElementHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Zr.entries())t.push({nodeId:e,isolationModeHighlightConfig:n});e.target().overlayAgent().invoke_setShowIsolatedElements({isolatedElementHighlightConfigs:t})}}var mn=Object.freeze({__proto__:null,OverlayPersistentHighlighter:pn});const fn={pausedInDebugger:"Paused in debugger"},bn=s.i18n.registerUIStrings("core/sdk/OverlayModel.ts",fn),yn=s.i18n.getLocalizedString.bind(void 0,bn);class vn extends c{#Mr;overlayAgent;#os;#ls;#ds;#cs;#hs;#us;#gs;#ps;#ms;#fs;#bs;#ys;#vs;#Is;#ks;#Ss;#ws;constructor(t){super(t),this.#Mr=t.model(Pn),t.registerOverlayDispatcher(this),this.overlayAgent=t.overlayAgent(),this.#os=t.model(or),this.#os&&(e.Settings.Settings.instance().moduleSetting("disablePausedStateOverlay").addChangeListener(this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.DebuggerPaused,this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.DebuggerResumed,this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.GlobalObjectCleared,this.updatePausedInDebuggerMessage,this)),this.#ls=!1,this.#ds=null,this.#cs=new kn(this),this.#hs=this.#cs,this.#us=e.Settings.Settings.instance().moduleSetting("showPaintRects"),this.#gs=e.Settings.Settings.instance().moduleSetting("showLayoutShiftRegions"),this.#ps=e.Settings.Settings.instance().moduleSetting("showAdHighlights"),this.#ms=e.Settings.Settings.instance().moduleSetting("showDebugBorders"),this.#fs=e.Settings.Settings.instance().moduleSetting("showFPSCounter"),this.#bs=e.Settings.Settings.instance().moduleSetting("showScrollBottleneckRects"),this.#ys=e.Settings.Settings.instance().moduleSetting("showWebVitals"),this.#vs=[],this.#Is=!0,t.suspended()||(this.overlayAgent.invoke_enable(),this.wireAgentToSettings()),this.#ks=new pn(this),this.#Mr.addEventListener(wn.NodeRemoved,(()=>{this.#ks&&this.#ks.refreshHighlights()})),this.#Mr.addEventListener(wn.DocumentUpdated,(()=>{this.#ks&&this.#ks.hideAllInOverlay()})),this.#Ss=new Sn(this),this.#ws=!1}static highlightObjectAsDOMNode(e){const t=e.runtimeModel().target().model(Pn);t&&t.overlayModel().highlightInOverlay({object:e,selectorList:void 0})}static hideDOMNodeHighlight(){for(const e of K.instance().models(vn))e.delayedHideHighlight(0)}static async muteHighlight(){return Promise.all(K.instance().models(vn).map((e=>e.suspendModel())))}static async unmuteHighlight(){return Promise.all(K.instance().models(vn).map((e=>e.resumeModel())))}static highlightRect(e){for(const t of K.instance().models(vn))t.highlightRect(e)}static clearHighlight(){for(const e of K.instance().models(vn))e.clearHighlight()}getDOMModel(){return this.#Mr}highlightRect({x:e,y:t,width:n,height:r,color:s,outlineColor:i}){const a=s||{r:255,g:0,b:255,a:.3},o=i||{r:255,g:0,b:255,a:.5};return this.overlayAgent.invoke_highlightRect({x:e,y:t,width:n,height:r,color:a,outlineColor:o})}clearHighlight(){return this.overlayAgent.invoke_hideHighlight()}async wireAgentToSettings(){this.#vs=[this.#us.addChangeListener((()=>this.overlayAgent.invoke_setShowPaintRects({result:this.#us.get()}))),this.#gs.addChangeListener((()=>this.overlayAgent.invoke_setShowLayoutShiftRegions({result:this.#gs.get()}))),this.#ps.addChangeListener((()=>this.overlayAgent.invoke_setShowAdHighlights({show:this.#ps.get()}))),this.#ms.addChangeListener((()=>this.overlayAgent.invoke_setShowDebugBorders({show:this.#ms.get()}))),this.#fs.addChangeListener((()=>this.overlayAgent.invoke_setShowFPSCounter({show:this.#fs.get()}))),this.#bs.addChangeListener((()=>this.overlayAgent.invoke_setShowScrollBottleneckRects({show:this.#bs.get()}))),this.#ys.addChangeListener((()=>this.overlayAgent.invoke_setShowWebVitals({show:this.#ys.get()})))],this.#us.get()&&this.overlayAgent.invoke_setShowPaintRects({result:!0}),this.#gs.get()&&this.overlayAgent.invoke_setShowLayoutShiftRegions({result:!0}),this.#ps.get()&&this.overlayAgent.invoke_setShowAdHighlights({show:!0}),this.#ms.get()&&this.overlayAgent.invoke_setShowDebugBorders({show:!0}),this.#fs.get()&&this.overlayAgent.invoke_setShowFPSCounter({show:!0}),this.#bs.get()&&this.overlayAgent.invoke_setShowScrollBottleneckRects({show:!0}),this.#ys.get()&&this.overlayAgent.invoke_setShowWebVitals({show:!0}),this.#os&&this.#os.isPaused()&&this.updatePausedInDebuggerMessage(),await this.overlayAgent.invoke_setShowViewportSizeOnResize({show:this.#Is})}async suspendModel(){e.EventTarget.removeEventListeners(this.#vs),await this.overlayAgent.invoke_disable()}async resumeModel(){await Promise.all([this.overlayAgent.invoke_enable(),this.wireAgentToSettings()])}setShowViewportSizeOnResize(e){this.#Is!==e&&(this.#Is=e,this.target().suspended()||this.overlayAgent.invoke_setShowViewportSizeOnResize({show:e}))}updatePausedInDebuggerMessage(){if(this.target().suspended())return;const t=this.#os&&this.#os.isPaused()&&!e.Settings.Settings.instance().moduleSetting("disablePausedStateOverlay").get()?yn(fn.pausedInDebugger):void 0;this.overlayAgent.invoke_setPausedInDebuggerMessage({message:t})}setHighlighter(e){this.#hs=e||this.#cs}async setInspectMode(e,t=!0){await this.#Mr.requestDocument(),this.#ls="none"!==e,this.dispatchEventToListeners(In.InspectModeWillBeToggled,this),this.#hs.setInspectMode(e,this.buildHighlightConfig("all",t))}inspectModeEnabled(){return this.#ls}highlightInOverlay(e,t,n){if(this.#ws)return;this.#ds&&(clearTimeout(this.#ds),this.#ds=null);const r=this.buildHighlightConfig(t);void 0!==n&&(r.showInfo=n),this.#hs.highlightInOverlay(e,r)}highlightInOverlayForTwoSeconds(e){this.highlightInOverlay(e),this.delayedHideHighlight(2e3)}highlightGridInPersistentOverlay(e){this.#ks&&(this.#ks.highlightGridInOverlay(e),this.dispatchEventToListeners(In.PersistentGridOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedGridInPersistentOverlay(e){return!!this.#ks&&this.#ks.isGridHighlighted(e)}hideGridInPersistentOverlay(e){this.#ks&&(this.#ks.hideGridInOverlay(e),this.dispatchEventToListeners(In.PersistentGridOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightScrollSnapInPersistentOverlay(e){this.#ks&&(this.#ks.highlightScrollSnapInOverlay(e),this.dispatchEventToListeners(In.PersistentScrollSnapOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedScrollSnapInPersistentOverlay(e){return!!this.#ks&&this.#ks.isScrollSnapHighlighted(e)}hideScrollSnapInPersistentOverlay(e){this.#ks&&(this.#ks.hideScrollSnapInOverlay(e),this.dispatchEventToListeners(In.PersistentScrollSnapOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightFlexContainerInPersistentOverlay(e){this.#ks&&(this.#ks.highlightFlexInOverlay(e),this.dispatchEventToListeners(In.PersistentFlexContainerOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedFlexContainerInPersistentOverlay(e){return!!this.#ks&&this.#ks.isFlexHighlighted(e)}hideFlexContainerInPersistentOverlay(e){this.#ks&&(this.#ks.hideFlexInOverlay(e),this.dispatchEventToListeners(In.PersistentFlexContainerOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightContainerQueryInPersistentOverlay(e){this.#ks&&(this.#ks.highlightContainerQueryInOverlay(e),this.dispatchEventToListeners(In.PersistentContainerQueryOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedContainerQueryInPersistentOverlay(e){return!!this.#ks&&this.#ks.isContainerQueryHighlighted(e)}hideContainerQueryInPersistentOverlay(e){this.#ks&&(this.#ks.hideContainerQueryInOverlay(e),this.dispatchEventToListeners(In.PersistentContainerQueryOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightSourceOrderInOverlay(t){const n={parentOutlineColor:e.Color.SourceOrderHighlight.ParentOutline.toProtocolRGBA(),childOutlineColor:e.Color.SourceOrderHighlight.ChildOutline.toProtocolRGBA()};this.#Ss.highlightSourceOrderInOverlay(t,n)}colorOfGridInPersistentOverlay(e){return this.#ks?this.#ks.colorOfGrid(e).asString("hex"):null}setColorOfGridInPersistentOverlay(t,n){if(!this.#ks)return;const r=e.Color.parse(n);r&&(this.#ks.setColorOfGrid(t,r),this.#ks.resetOverlay())}colorOfFlexInPersistentOverlay(e){return this.#ks?this.#ks.colorOfFlex(e).asString("hex"):null}setColorOfFlexInPersistentOverlay(t,n){if(!this.#ks)return;const r=e.Color.parse(n);r&&(this.#ks.setColorOfFlex(t,r),this.#ks.resetOverlay())}hideSourceOrderInOverlay(){this.#Ss.hideSourceOrderHighlight()}setSourceOrderActive(e){this.#ws=e}sourceOrderModeActive(){return this.#ws}highlightIsolatedElementInPersistentOverlay(e){this.#ks&&this.#ks.highlightIsolatedElementInOverlay(e)}hideIsolatedElementInPersistentOverlay(e){this.#ks&&this.#ks.hideIsolatedElementInOverlay(e)}isHighlightedIsolatedElementInPersistentOverlay(e){return!!this.#ks&&this.#ks.isIsolatedElementHighlighted(e)}delayedHideHighlight(e){null===this.#ds&&(this.#ds=window.setTimeout((()=>this.highlightInOverlay({clear:!0})),e))}highlightFrame(e){this.#ds&&(clearTimeout(this.#ds),this.#ds=null),this.#hs.highlightFrame(e)}showHingeForDualScreen(e){if(e){const{x:t,y:n,width:r,height:s,contentColor:i,outlineColor:a}=e;this.overlayAgent.invoke_setShowHinge({hingeConfig:{rect:{x:t,y:n,width:r,height:s},contentColor:i,outlineColor:a}})}else this.overlayAgent.invoke_setShowHinge({})}buildHighlightConfig(t="all",n=!1){const r=e.Settings.Settings.instance().moduleSetting("showMetricsRulers").get(),s=e.Settings.Settings.instance().moduleSetting("colorFormat").get(),i={showInfo:"all"===t||"container-outline"===t,showRulers:r,showStyles:n,showAccessibilityInfo:n,showExtensionLines:r,gridHighlightConfig:{},flexContainerHighlightConfig:{},flexItemHighlightConfig:{},contrastAlgorithm:o.Runtime.experiments.isEnabled("APCA")?"apca":"aa"};"all"!==t&&"content"!==t||(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA()),"all"!==t&&"padding"!==t||(i.paddingColor=e.Color.PageHighlight.Padding.toProtocolRGBA()),"all"!==t&&"border"!==t||(i.borderColor=e.Color.PageHighlight.Border.toProtocolRGBA()),"all"!==t&&"margin"!==t||(i.marginColor=e.Color.PageHighlight.Margin.toProtocolRGBA()),"all"===t&&(i.eventTargetColor=e.Color.PageHighlight.EventTarget.toProtocolRGBA(),i.shapeColor=e.Color.PageHighlight.Shape.toProtocolRGBA(),i.shapeMarginColor=e.Color.PageHighlight.ShapeMargin.toProtocolRGBA(),i.gridHighlightConfig={rowGapColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA(),rowHatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),columnGapColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA(),columnHatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0},i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},itemSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},lineSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},crossDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},rowGapSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},columnGapSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}},i.flexItemHighlightConfig={baseSizeBox:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA()},baseSizeBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},flexibilityArrow:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),t.endsWith("gap")&&(i.gridHighlightConfig={gridBorderColor:e.Color.PageHighlight.GridBorder.toProtocolRGBA(),gridBorderDash:!0},"gap"!==t&&"row-gap"!==t||(i.gridHighlightConfig.rowGapColor=e.Color.PageHighlight.GapBackground.toProtocolRGBA(),i.gridHighlightConfig.rowHatchColor=e.Color.PageHighlight.GapHatch.toProtocolRGBA()),"gap"!==t&&"column-gap"!==t||(i.gridHighlightConfig.columnGapColor=e.Color.PageHighlight.GapBackground.toProtocolRGBA(),i.gridHighlightConfig.columnHatchColor=e.Color.PageHighlight.GapHatch.toProtocolRGBA())),t.endsWith("gap")&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}},"gap"!==t&&"row-gap"!==t||(i.flexContainerHighlightConfig.rowGapSpace={hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}),"gap"!==t&&"column-gap"!==t||(i.flexContainerHighlightConfig.columnGapSpace={hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()})),"grid-areas"===t&&(i.gridHighlightConfig={rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0,showAreaNames:!0,areaBorderColor:e.Color.PageHighlight.GridAreaBorder.toProtocolRGBA()}),"grid-template-columns"===t&&(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA(),i.gridHighlightConfig={columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineDash:!0}),"grid-template-rows"===t&&(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA(),i.gridHighlightConfig={rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0}),"justify-content"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}}),"align-content"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},crossDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}}),"align-items"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},lineSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},crossAlignment:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),"flexibility"===t&&(i.flexItemHighlightConfig={baseSizeBox:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA()},baseSizeBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},flexibilityArrow:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),"container-outline"===t&&(i.containerQueryContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}});return new Set(["rgb","hsl","hex"]).has(s)&&(i.colorFormat=s),i}nodeHighlightRequested({nodeId:e}){const t=this.#Mr.nodeForId(e);t&&this.dispatchEventToListeners(In.HighlightNodeRequested,t)}static setInspectNodeHandler(e){vn.inspectNodeHandler=e}inspectNodeRequested({backendNodeId:t}){const n=new Rn(this.target(),t);vn.inspectNodeHandler?n.resolvePromise().then((e=>{e&&vn.inspectNodeHandler&&vn.inspectNodeHandler(e)})):e.Revealer.reveal(n),this.dispatchEventToListeners(In.ExitedInspectMode)}screenshotRequested({viewport:e}){this.dispatchEventToListeners(In.ScreenshotRequested,e),this.dispatchEventToListeners(In.ExitedInspectMode)}inspectModeCanceled(){this.dispatchEventToListeners(In.ExitedInspectMode)}static inspectNodeHandler=null;getOverlayAgent(){return this.overlayAgent}}var In;!function(e){e.InspectModeWillBeToggled="InspectModeWillBeToggled",e.ExitedInspectMode="InspectModeExited",e.HighlightNodeRequested="HighlightNodeRequested",e.ScreenshotRequested="ScreenshotRequested",e.PersistentGridOverlayStateChanged="PersistentGridOverlayStateChanged",e.PersistentFlexContainerOverlayStateChanged="PersistentFlexContainerOverlayStateChanged",e.PersistentScrollSnapOverlayStateChanged="PersistentScrollSnapOverlayStateChanged",e.PersistentContainerQueryOverlayStateChanged="PersistentContainerQueryOverlayStateChanged"}(In||(In={}));class kn{#$r;constructor(e){this.#$r=e}highlightInOverlay(e,t){const{node:n,deferredNode:r,object:s,selectorList:i}={node:void 0,deferredNode:void 0,object:void 0,selectorList:void 0,...e},a=n?n.id:void 0,o=r?r.backendNodeId():void 0,l=s?s.objectId:void 0;a||o||l?this.#$r.target().overlayAgent().invoke_highlightNode({highlightConfig:t,nodeId:a,backendNodeId:o,objectId:l,selector:i}):this.#$r.target().overlayAgent().invoke_hideHighlight()}async setInspectMode(e,t){await this.#$r.target().overlayAgent().invoke_setInspectMode({mode:e,highlightConfig:t})}highlightFrame(t){this.#$r.target().overlayAgent().invoke_highlightFrame({frameId:t,contentColor:e.Color.PageHighlight.Content.toProtocolRGBA(),contentOutlineColor:e.Color.PageHighlight.ContentOutline.toProtocolRGBA()})}}class Sn{#$r;constructor(e){this.#$r=e}highlightSourceOrderInOverlay(e,t){this.#$r.setSourceOrderActive(!0),this.#$r.setShowViewportSizeOnResize(!1),this.#$r.getOverlayAgent().invoke_highlightSourceOrder({sourceOrderConfig:t,nodeId:e.id})}hideSourceOrderHighlight(){this.#$r.setSourceOrderActive(!1),this.#$r.setShowViewportSizeOnResize(!0),this.#$r.clearHighlight()}}c.register(vn,{capabilities:z.DOM,autostart:!0});var wn,Cn=Object.freeze({__proto__:null,OverlayModel:vn,get Events(){return In},SourceOrderHighlighter:Sn});class Tn{#Cs;#Ts;ownerDocument;#Rs;id;index;#xs;#Ms;#Ps;#Ls;nodeValueInternal;#Es;#As;#Os;#Ns;#Fs;#Bs;#Ds;#Us;#Hs;assignedSlot;shadowRootsInternal;#qs;#_s;#zs;childNodeCountInternal;childrenInternal;nextSibling;previousSibling;firstChild;lastChild;parentNode;templateContentInternal;contentDocumentInternal;childDocumentPromiseForTesting;#js;publicId;systemId;internalSubset;name;value;constructor(e){this.#Cs=e,this.#Ts=this.#Cs.getAgent(),this.index=void 0,this.#Ds=null,this.#Us=new Map,this.#Hs=[],this.assignedSlot=null,this.shadowRootsInternal=[],this.#qs=new Map,this.#_s=new Map,this.#zs=0,this.childrenInternal=null,this.nextSibling=null,this.previousSibling=null,this.firstChild=null,this.lastChild=null,this.parentNode=null}static create(e,t,n,r){const s=new Tn(e);return s.init(t,n,r),s}init(e,t,n){if(this.#Ts=this.#Cs.getAgent(),this.ownerDocument=e,this.#Rs=t,this.id=n.nodeId,this.#xs=n.backendNodeId,this.#Cs.registerNode(this),this.#Ms=n.nodeType,this.#Ps=n.nodeName,this.#Ls=n.localName,this.nodeValueInternal=n.nodeValue,this.#Es=n.pseudoType,this.#As=n.pseudoIdentifier,this.#Os=n.shadowRootType,this.#Ns=n.frameId||null,this.#Fs=n.xmlVersion,this.#Bs=Boolean(n.isSVG),n.attributes&&this.setAttributesPayload(n.attributes),this.childNodeCountInternal=n.childNodeCount||0,n.shadowRoots)for(let e=0;ee.creation||null)),this.#Ds}get subtreeMarkerCount(){return this.#zs}domModel(){return this.#Cs}backendNodeId(){return this.#xs}children(){return this.childrenInternal?this.childrenInternal.slice():null}setChildren(e){this.childrenInternal=e}hasAttributes(){return this.#qs.size>0}childNodeCount(){return this.childNodeCountInternal}setChildNodeCount(e){this.childNodeCountInternal=e}hasShadowRoots(){return Boolean(this.shadowRootsInternal.length)}shadowRoots(){return this.shadowRootsInternal.slice()}templateContent(){return this.templateContentInternal||null}contentDocument(){return this.contentDocumentInternal||null}setContentDocument(e){this.contentDocumentInternal=e}isIframe(){return"IFRAME"===this.#Ps}isPortal(){return"PORTAL"===this.#Ps}importedDocument(){return this.#js||null}nodeType(){return this.#Ms}nodeName(){return this.#Ps}pseudoType(){return this.#Es}pseudoIdentifier(){return this.#As}hasPseudoElements(){return this.#Us.size>0}pseudoElements(){return this.#Us}beforePseudoElement(){return this.#Us.get("before")?.at(-1)}afterPseudoElement(){return this.#Us.get("after")?.at(-1)}markerPseudoElement(){return this.#Us.get("marker")?.at(-1)}backdropPseudoElement(){return this.#Us.get("backdrop")?.at(-1)}viewTransitionPseudoElements(){return[...this.#Us.get("view-transition")||[],...this.#Us.get("view-transition-group")||[],...this.#Us.get("view-transition-image-pair")||[],...this.#Us.get("view-transition-old")||[],...this.#Us.get("view-transition-new")||[]]}hasAssignedSlot(){return null!==this.assignedSlot}isInsertionPoint(){return!this.isXMLNode()&&("SHADOW"===this.#Ps||"CONTENT"===this.#Ps||"SLOT"===this.#Ps)}distributedNodes(){return this.#Hs}isInShadowTree(){return this.#Rs}ancestorShadowHost(){const e=this.ancestorShadowRoot();return e?e.parentNode:null}ancestorShadowRoot(){if(!this.#Rs)return null;let e=this;for(;e&&!e.isShadowRoot();)e=e.parentNode;return e}ancestorUserAgentShadowRoot(){const e=this.ancestorShadowRoot();return e&&e.shadowRootType()===Tn.ShadowRootTypes.UserAgent?e:null}isShadowRoot(){return Boolean(this.#Os)}shadowRootType(){return this.#Os||null}nodeNameInCorrectCase(){const e=this.shadowRootType();return e?"#shadow-root ("+e+")":this.localName()?this.localName().length!==this.nodeName().length?this.nodeName():this.localName():this.nodeName()}setNodeName(e,t){this.#Ts.invoke_setNodeName({nodeId:this.id,name:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}localName(){return this.#Ls}nodeValue(){return this.nodeValueInternal}setNodeValueInternal(e){this.nodeValueInternal=e}setNodeValue(e,t){this.#Ts.invoke_setNodeValue({nodeId:this.id,value:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null)}))}getAttribute(e){const t=this.#qs.get(e);return t?t.value:void 0}setAttribute(e,t,n){this.#Ts.invoke_setAttributesAsText({nodeId:this.id,text:t,name:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null)}))}setAttributeValue(e,t,n){this.#Ts.invoke_setAttributeValue({nodeId:this.id,name:e,value:t}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null)}))}setAttributeValuePromise(e,t){return new Promise((n=>this.setAttributeValue(e,t,n)))}attributes(){return[...this.#qs.values()]}async removeAttribute(e){(await this.#Ts.invoke_removeAttribute({nodeId:this.id,name:e})).getError()||(this.#qs.delete(e),this.#Cs.markUndoableState())}getChildNodes(e){this.childrenInternal?e(this.children()):this.#Ts.invoke_requestChildNodes({nodeId:this.id}).then((t=>{e(t.getError()?null:this.children())}))}async getSubtree(e,t){return(await this.#Ts.invoke_requestChildNodes({nodeId:this.id,depth:e,pierce:t})).getError()?null:this.childrenInternal}async getOuterHTML(){const{outerHTML:e}=await this.#Ts.invoke_getOuterHTML({nodeId:this.id});return e}setOuterHTML(e,t){this.#Ts.invoke_setOuterHTML({nodeId:this.id,outerHTML:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null)}))}removeNode(e){return this.#Ts.invoke_removeNode({nodeId:this.id}).then((t=>{t.getError()||this.#Cs.markUndoableState(),e&&e(t.getError()||null)}))}async copyNode(){const{outerHTML:e}=await this.#Ts.invoke_getOuterHTML({nodeId:this.id});return null!==e&&i.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(e),e}path(){function e(e){return(void 0!==e.index||e.isShadowRoot()&&e.parentNode)&&e.#Ps.length}const t=[];let n=this;for(;n&&e(n);){const e="number"==typeof n.index?n.index:n.shadowRootType()===Tn.ShadowRootTypes.UserAgent?"u":"a";t.push([e,n.#Ps]),n=n.parentNode}return t.reverse(),t.join(",")}isAncestor(e){if(!e)return!1;let t=e.parentNode;for(;t;){if(this===t)return!0;t=t.parentNode}return!1}isDescendant(e){return null!==e&&e.isAncestor(this)}frameOwnerFrameId(){return this.#Ns}frameId(){let e=this.parentNode||this;for(;!e.#Ns&&e.parentNode;)e=e.parentNode;return e.#Ns}setAttributesPayload(e){let t=!this.#qs||e.length!==2*this.#qs.size;const n=this.#qs||new Map;this.#qs=new Map;for(let r=0;rt!==e));n&&n.length>0?this.#Us.set(t,n):this.#Us.delete(t)}else{const t=this.shadowRootsInternal.indexOf(e);if(-1!==t)this.shadowRootsInternal.splice(t,1);else{if(!this.childrenInternal)throw new Error("DOMNode._children is expected to not be null.");if(-1===this.childrenInternal.indexOf(e))throw new Error("DOMNode._children is expected to contain the node to be removed.");this.childrenInternal.splice(this.childrenInternal.indexOf(e),1)}}e.parentNode=null,this.#zs-=e.#zs,e.#zs&&this.#Cs.dispatchEventToListeners(wn.MarkersChanged,this),this.renumber()}setChildrenPayload(e){this.childrenInternal=[];for(let t=0;t=0?this.childrenInternal[e-1]:null,t.parentNode=this}}addAttribute(e,t){const n={name:e,value:t,_node:this};this.#qs.set(e,n)}setAttributeInternal(e,t){const n=this.#qs.get(e);n?n.value=t:this.addAttribute(e,t)}removeAttributeInternal(e){this.#qs.delete(e)}copyTo(e,t,n){this.#Ts.invoke_copyTo({nodeId:this.id,targetNodeId:e.id,insertBeforeNodeId:t?t.id:void 0}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}moveTo(e,t,n){this.#Ts.invoke_moveTo({nodeId:this.id,targetNodeId:e.id,insertBeforeNodeId:t?t.id:void 0}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}isXMLNode(){return Boolean(this.#Fs)}setMarker(e,t){if(null!==t){if(this.parentNode&&!this.#_s.has(e))for(let e=this;e;e=e.parentNode)++e.#zs;this.#_s.set(e,t);for(let e=this;e;e=e.parentNode)this.#Cs.dispatchEventToListeners(wn.MarkersChanged,e)}else{if(!this.#_s.has(e))return;this.#_s.delete(e);for(let e=this;e;e=e.parentNode)--e.#zs;for(let e=this;e;e=e.parentNode)this.#Cs.dispatchEventToListeners(wn.MarkersChanged,e)}}marker(e){return this.#_s.get(e)||null}getMarkerKeysForTest(){return[...this.#_s.keys()]}traverseMarkers(e){!function t(n){if(n.#zs){for(const t of n.#_s.keys())e(n,t);if(n.childrenInternal)for(const e of n.childrenInternal)t(e)}}(this)}resolveURL(t){if(!t)return t;for(let n=this;n;n=n.parentNode)if(n instanceof Mn&&n.baseURL)return e.ParsedURL.ParsedURL.completeURL(n.baseURL,t);return null}highlight(e){this.#Cs.overlayModel().highlightInOverlay({node:this,selectorList:void 0},e)}highlightForTwoSeconds(){this.#Cs.overlayModel().highlightInOverlayForTwoSeconds({node:this,selectorList:void 0})}async resolveToObject(e){const{object:t}=await this.#Ts.invoke_resolveNode({nodeId:this.id,backendNodeId:void 0,objectGroup:e});return t&&this.#Cs.runtimeModelInternal.createRemoteObject(t)||null}async boxModel(){const{model:e}=await this.#Ts.invoke_getBoxModel({nodeId:this.id});return e}async setAsInspectedNode(){let e=this;for(e&&e.pseudoType()&&(e=e.parentNode);e;){let t=e.ancestorUserAgentShadowRoot();if(!t)break;if(t=e.ancestorShadowHost(),!t)break;e=t}if(!e)throw new Error("In DOMNode.setAsInspectedNode: node is expected to not be null.");await this.#Ts.invoke_setInspectedNode({nodeId:e.id})}enclosingElementOrSelf(){let e=this;return e&&e.nodeType()===Node.TEXT_NODE&&e.parentNode&&(e=e.parentNode),e&&e.nodeType()!==Node.ELEMENT_NODE&&(e=null),e}async scrollIntoView(){const e=this.enclosingElementOrSelf();if(!e)return;const t=await e.resolveToObject();t&&(t.callFunction((function(){this.scrollIntoViewIfNeeded(!0)})),t.release(),e.highlightForTwoSeconds())}async focus(){const e=this.enclosingElementOrSelf();if(!e)throw new Error("DOMNode.focus expects node to not be null.");const t=await e.resolveToObject();t&&(await t.callFunction((function(){this.focus()})),t.release(),e.highlightForTwoSeconds(),await this.#Cs.target().pageAgent().invoke_bringToFront())}simpleSelector(){const e=this.localName()||this.nodeName().toLowerCase();if(this.nodeType()!==Node.ELEMENT_NODE)return e;const t=this.getAttribute("type"),n=this.getAttribute("id"),r=this.getAttribute("class");if("input"===e&&t&&!n&&!r)return e+'[type="'+CSS.escape(t)+'"]';if(n)return e+"#"+CSS.escape(n);if(r){return("div"===e?"":e)+"."+r.trim().split(/\s+/g).map((e=>CSS.escape(e))).join(".")}return e}}!function(e){let t;!function(e){e.UserAgent="user-agent",e.Open="open",e.Closed="closed"}(t=e.ShadowRootTypes||(e.ShadowRootTypes={}))}(Tn||(Tn={}));class Rn{#Cs;#xs;constructor(e,t){this.#Cs=e.model(Pn),this.#xs=t}resolve(e){this.resolvePromise().then(e)}async resolvePromise(){const e=await this.#Cs.pushNodesByBackendIdsToFrontend(new Set([this.#xs]));return e&&e.get(this.#xs)||null}backendNodeId(){return this.#xs}domModel(){return this.#Cs}highlight(){this.#Cs.overlayModel().highlightInOverlay({deferredNode:this,selectorList:void 0})}}class xn{nodeType;nodeName;deferredNode;constructor(e,t,n,r){this.nodeType=n,this.nodeName=r,this.deferredNode=new Rn(e,t)}}class Mn extends Tn{body;documentElement;documentURL;baseURL;constructor(e,t){super(e),this.body=null,this.documentElement=null,this.init(this,!1,t),this.documentURL=t.documentURL||"",this.baseURL=t.baseURL||""}}class Pn extends c{agent;idToDOMNode=new Map;#Ws;#Vs;runtimeModelInternal;#Gs;#Ks;#$s;#Qs;#Xs;constructor(e){super(e),this.agent=e.domAgent(),this.#Ws=null,this.#Vs=new Set,e.registerDOMDispatcher(new Ln(this)),this.runtimeModelInternal=e.model(Cr),this.#Ks=null,e.suspended()||this.agent.invoke_enable({}),o.Runtime.experiments.isEnabled("captureNodeCreationStacks")&&this.agent.invoke_setNodeStackTracesEnabled({enable:!0})}runtimeModel(){return this.runtimeModelInternal}cssModel(){return this.target().model(en)}overlayModel(){return this.target().model(vn)}static cancelSearch(){for(const e of K.instance().models(Pn))e.cancelSearch()}scheduleMutationEvent(e){this.hasEventListeners(wn.DOMMutated)&&(this.#Gs=(this.#Gs||0)+1,Promise.resolve().then(function(e,t){if(!this.hasEventListeners(wn.DOMMutated)||this.#Gs!==t)return;this.dispatchEventToListeners(wn.DOMMutated,e)}.bind(this,e,this.#Gs)))}requestDocument(){return this.#Ws?Promise.resolve(this.#Ws):(this.#Ks||(this.#Ks=this.requestDocumentInternal()),this.#Ks)}async getOwnerNodeForFrame(e){const t=await this.agent.invoke_getFrameOwner({frameId:e});return t.getError()?null:new Rn(this.target(),t.backendNodeId)}async requestDocumentInternal(){const e=await this.agent.invoke_getDocument({});if(e.getError())return null;const{root:t}=e;if(this.#Ks=null,t&&this.setDocument(t),!this.#Ws)return console.error("No document"),null;const n=this.parentModel();if(n&&!this.#$s){await n.requestDocument();const e=this.target().model(jn)?.mainFrame;if(e){const t=await n.agent.invoke_getFrameOwner({frameId:e.id});!t.getError()&&t.nodeId&&(this.#$s=n.nodeForId(t.nodeId))}}if(this.#$s){const e=this.#$s.contentDocument();this.#$s.setContentDocument(this.#Ws),this.#$s.setChildren([]),this.#Ws?(this.#Ws.parentNode=this.#$s,this.dispatchEventToListeners(wn.NodeInserted,this.#Ws)):e&&this.dispatchEventToListeners(wn.NodeRemoved,{node:e,parent:this.#$s})}return this.#Ws}existingDocument(){return this.#Ws}async pushNodeToFrontend(e){await this.requestDocument();const{nodeId:t}=await this.agent.invoke_requestNode({objectId:e});return t?this.nodeForId(t):null}pushNodeByPathToFrontend(e){return this.requestDocument().then((()=>this.agent.invoke_pushNodeByPathToFrontend({path:e}))).then((({nodeId:e})=>e))}async pushNodesByBackendIdsToFrontend(e){await this.requestDocument();const t=[...e],{nodeIds:n}=await this.agent.invoke_pushNodesByBackendIdsToFrontend({backendNodeIds:t});if(!n)return null;const r=new Map;for(let e=0;e{if(!t)return;const n=this.idToDOMNode.get(e);n&&n.setAttributesPayload(t)&&(this.dispatchEventToListeners(wn.AttrModified,{node:n,name:"style"}),this.scheduleMutationEvent(n))}));this.#Vs.clear()}characterDataModified(e,t){const n=this.idToDOMNode.get(e);n?(n.setNodeValueInternal(t),this.dispatchEventToListeners(wn.CharacterDataModified,n),this.scheduleMutationEvent(n)):console.error("nodeId could not be resolved to a node")}nodeForId(e){return e&&this.idToDOMNode.get(e)||null}documentUpdated(){const e=this.#Ks;this.setDocument(null),this.parentModel()&&!e&&this.requestDocument()}setDocument(e){this.idToDOMNode=new Map,this.#Ws=e&&"nodeId"in e?new Mn(this,e):null,An.instance().dispose(this),this.parentModel()||this.dispatchEventToListeners(wn.DocumentUpdated,this)}setDetachedRoot(e){"#document"===e.nodeName?new Mn(this,e):Tn.create(this,null,!1,e)}setChildNodes(e,t){if(!e&&t.length)return void this.setDetachedRoot(t[0]);this.idToDOMNode.get(e)?.setChildrenPayload(t)}childNodeCountUpdated(e,t){const n=this.idToDOMNode.get(e);n?(n.setChildNodeCount(t),this.dispatchEventToListeners(wn.ChildNodeCountUpdated,n),this.scheduleMutationEvent(n)):console.error("nodeId could not be resolved to a node")}childNodeInserted(e,t,n){const r=this.idToDOMNode.get(e),s=this.idToDOMNode.get(t);if(!r)return void console.error("parentId could not be resolved to a node");const i=r.insertChild(s,n);this.idToDOMNode.set(i.id,i),this.dispatchEventToListeners(wn.NodeInserted,i),this.scheduleMutationEvent(i)}childNodeRemoved(e,t){const n=this.idToDOMNode.get(e),r=this.idToDOMNode.get(t);n&&r?(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r)):console.error("parentId or nodeId could not be resolved to a node")}shadowRootPushed(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=Tn.create(this,n.ownerDocument,!0,t);r.parentNode=n,this.idToDOMNode.set(r.id,r),n.shadowRootsInternal.unshift(r),this.dispatchEventToListeners(wn.NodeInserted,r),this.scheduleMutationEvent(r)}shadowRootPopped(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=this.idToDOMNode.get(t);r&&(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r))}pseudoElementAdded(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=Tn.create(this,n.ownerDocument,!1,t);r.parentNode=n,this.idToDOMNode.set(r.id,r);const s=r.pseudoType();if(!s)throw new Error("DOMModel._pseudoElementAdded expects pseudoType to be defined.");const i=n.pseudoElements().get(s);i?i.push(r):n.pseudoElements().set(s,[r]),this.dispatchEventToListeners(wn.NodeInserted,r),this.scheduleMutationEvent(r)}topLayerElementsUpdated(){this.dispatchEventToListeners(wn.TopLayerElementsChanged)}pseudoElementRemoved(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=this.idToDOMNode.get(t);r&&(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r))}distributedNodesUpdated(e,t){const n=this.idToDOMNode.get(e);n&&(n.setDistributedNodePayloads(t),this.dispatchEventToListeners(wn.DistributedNodesChanged,n),this.scheduleMutationEvent(n))}unbind(e){this.idToDOMNode.delete(e.id);const t=e.children();for(let e=0;t&&ee||[]))}querySelector(e,t){return this.agent.invoke_querySelector({nodeId:e,selector:t}).then((({nodeId:e})=>e))}querySelectorAll(e,t){return this.agent.invoke_querySelectorAll({nodeId:e,selector:t}).then((({nodeIds:e})=>e))}getTopLayerElements(){return this.agent.invoke_getTopLayerElements().then((({nodeIds:e})=>e))}markUndoableState(e){An.instance().markUndoableState(this,e||!1)}async nodeForLocation(e,t,n){const r=await this.agent.invoke_getNodeForLocation({x:e,y:t,includeUserAgentShadowDOM:n});return r.getError()||!r.nodeId?null:this.nodeForId(r.nodeId)}async getContainerForNode(e,t,n,r){const{nodeId:s}=await this.agent.invoke_getContainerForNode({nodeId:e,containerName:t,physicalAxes:n,logicalAxes:r});return s?this.nodeForId(s):null}pushObjectAsNodeToFrontend(e){return e.isNode()&&e.objectId?this.pushNodeToFrontend(e.objectId):Promise.resolve(null)}suspendModel(){return this.agent.invoke_disable().then((()=>this.setDocument(null)))}async resumeModel(){await this.agent.invoke_enable({})}dispose(){An.instance().dispose(this)}parentModel(){const e=this.target().parentTarget();return e?e.model(Pn):null}getAgent(){return this.agent}registerNode(e){this.idToDOMNode.set(e.id,e)}}!function(e){e.AttrModified="AttrModified",e.AttrRemoved="AttrRemoved",e.CharacterDataModified="CharacterDataModified",e.DOMMutated="DOMMutated",e.NodeInserted="NodeInserted",e.NodeRemoved="NodeRemoved",e.DocumentUpdated="DocumentUpdated",e.ChildNodeCountUpdated="ChildNodeCountUpdated",e.DistributedNodesChanged="DistributedNodesChanged",e.MarkersChanged="MarkersChanged",e.TopLayerElementsChanged="TopLayerElementsChanged"}(wn||(wn={}));class Ln{#Mr;constructor(e){this.#Mr=e}documentUpdated(){this.#Mr.documentUpdated()}attributeModified({nodeId:e,name:t,value:n}){this.#Mr.attributeModified(e,t,n)}attributeRemoved({nodeId:e,name:t}){this.#Mr.attributeRemoved(e,t)}inlineStyleInvalidated({nodeIds:e}){this.#Mr.inlineStyleInvalidated(e)}characterDataModified({nodeId:e,characterData:t}){this.#Mr.characterDataModified(e,t)}setChildNodes({parentId:e,nodes:t}){this.#Mr.setChildNodes(e,t)}childNodeCountUpdated({nodeId:e,childNodeCount:t}){this.#Mr.childNodeCountUpdated(e,t)}childNodeInserted({parentNodeId:e,previousNodeId:t,node:n}){this.#Mr.childNodeInserted(e,t,n)}childNodeRemoved({parentNodeId:e,nodeId:t}){this.#Mr.childNodeRemoved(e,t)}shadowRootPushed({hostId:e,root:t}){this.#Mr.shadowRootPushed(e,t)}shadowRootPopped({hostId:e,rootId:t}){this.#Mr.shadowRootPopped(e,t)}pseudoElementAdded({parentId:e,pseudoElement:t}){this.#Mr.pseudoElementAdded(e,t)}pseudoElementRemoved({parentId:e,pseudoElementId:t}){this.#Mr.pseudoElementRemoved(e,t)}distributedNodesUpdated({insertionPointId:e,distributedNodes:t}){this.#Mr.distributedNodesUpdated(e,t)}topLayerElementsUpdated(){this.#Mr.topLayerElementsUpdated()}}let En;class An{#Js;#Kr;#Ys;constructor(){this.#Js=[],this.#Kr=0,this.#Ys=null}static instance(e={forceNew:null}){const{forceNew:t}=e;return En&&!t||(En=new An),En}async markUndoableState(e,t){this.#Ys&&e!==this.#Ys&&(this.#Ys.markUndoableState(),this.#Ys=null),t&&this.#Ys===e||(this.#Js=this.#Js.slice(0,this.#Kr),this.#Js.push(e),this.#Kr=this.#Js.length,t?this.#Ys=e:(await e.getAgent().invoke_markUndoableState(),this.#Ys=null))}async undo(){if(0===this.#Kr)return Promise.resolve();--this.#Kr,this.#Ys=null,await this.#Js[this.#Kr].getAgent().invoke_undo()}async redo(){if(this.#Kr>=this.#Js.length)return Promise.resolve();++this.#Kr,this.#Ys=null,await this.#Js[this.#Kr-1].getAgent().invoke_redo()}dispose(e){let n=0;for(let t=0;t{this.#ai.push(e),this.#Zs&&!this.#Zs.finished||this.innerRequestContent()}))}canonicalMimeType(){return this.contentType().canonicalMimeType()||this.mimeType}async searchInContent(e,t,n){if(!this.frameId)return[];if(this.request)return this.request.searchInContent(e,t,n);return(await this.#Er.target().pageAgent().invoke_searchInResource({frameId:this.frameId,url:this.url,query:e,caseSensitive:t,isRegex:n})).result||[]}async populateImageSource(e){const{content:t}=await this.requestContent(),n=this.#ii;e.src=r.ContentProvider.contentAsDataURL(t,this.#kt,n)||this.#mt}requestFinished(){this.#Zs&&this.#Zs.removeEventListener(Te.FinishedLoading,this.requestFinished,this),this.#ai.length&&this.innerRequestContent()}async innerRequestContent(){if(this.#oi)return;this.#oi=!0;let e=null;if(this.request){const t=await this.request.contentData();t.error||(this.#si=t.content,this.#ii=t.encoded,e={content:t.content,isEncoded:t.encoded})}if(!e){const t=await this.#Er.target().pageAgent().invoke_getResourceContent({frameId:this.frameId,url:this.url}),n=t.getError();n?(this.#si=null,e={content:null,error:n,isEncoded:!1}):(this.#si=t.content,e={content:t.content,isEncoded:t.base64Encoded}),this.#ii=t.base64Encoded}null===this.#si&&(this.#ii=!1);for(const t of this.#ai.splice(0))t(e);this.#oi=void 0}hasTextContent(){return!!this.#ei.isTextType()||this.#ei===e.ResourceType.resourceTypes.Other&&(Boolean(this.#si)&&!this.#ii)}frame(){return this.#Ce?this.#Er.frameForId(this.#Ce):null}statusCode(){return this.#Zs?this.#Zs.statusCode:0}}var Fn,Bn=Object.freeze({__proto__:null,Resource:Nn});class Dn extends c{#li;#di;#ci;constructor(e){super(e),this.#li="",this.#di="",this.#ci=new Set}updateSecurityOrigins(e){const t=this.#ci;this.#ci=e;for(const e of t)this.#ci.has(e)||this.dispatchEventToListeners(Fn.SecurityOriginRemoved,e);for(const e of this.#ci)t.has(e)||this.dispatchEventToListeners(Fn.SecurityOriginAdded,e)}securityOrigins(){return[...this.#ci]}mainSecurityOrigin(){return this.#li}unreachableMainSecurityOrigin(){return this.#di}setMainSecurityOrigin(e,t){this.#li=e,this.#di=t||null,this.dispatchEventToListeners(Fn.MainSecurityOriginChanged,{mainSecurityOrigin:this.#li,unreachableMainSecurityOrigin:this.#di})}}!function(e){e.SecurityOriginAdded="SecurityOriginAdded",e.SecurityOriginRemoved="SecurityOriginRemoved",e.MainSecurityOriginChanged="MainSecurityOriginChanged"}(Fn||(Fn={})),c.register(Dn,{capabilities:z.None,autostart:!1});var Un,Hn=Object.freeze({__proto__:null,SecurityOriginManager:Dn,get Events(){return Fn}});class qn extends c{#hi;#ui;constructor(e){super(e),this.#hi="",this.#ui=new Set}updateStorageKeys(e){const t=this.#ui;this.#ui=e;for(const e of t)this.#ui.has(e)||this.dispatchEventToListeners(Un.StorageKeyRemoved,e);for(const e of this.#ui)t.has(e)||this.dispatchEventToListeners(Un.StorageKeyAdded,e)}storageKeys(){return[...this.#ui]}mainStorageKey(){return this.#hi}setMainStorageKey(e){this.#hi=e,this.dispatchEventToListeners(Un.MainStorageKeyChanged,{mainStorageKey:this.#hi})}}!function(e){e.StorageKeyAdded="StorageKeyAdded",e.StorageKeyRemoved="StorageKeyRemoved",e.MainStorageKeyChanged="MainStorageKeyChanged"}(Un||(Un={})),c.register(qn,{capabilities:z.None,autostart:!1});var _n,zn=Object.freeze({__proto__:null,StorageKeyManager:qn,parseStorageKey:function(t){const n=t.split("^"),r={origin:e.ParsedURL.ParsedURL.extractOrigin(n[0]),components:new Map};for(let e=1;e{this.processCachedResources(e.getError()?null:e.frameTree),this.mainFrame&&this.processPendingEvents(this.mainFrame)}))}static frameForRequest(e){const t=ne.forRequest(e),n=t?t.target().model(jn):null;return n&&e.frameId?n.frameForId(e.frameId):null}static frames(){const e=[];for(const t of K.instance().models(jn))e.push(...t.frames());return e}static resourceForURL(e){for(const t of K.instance().models(jn)){const n=t.mainFrame,r=n?n.resourceForURL(e):null;if(r)return r}return null}static reloadAllPages(e,t){for(const n of K.instance().models(jn))n.target().parentTarget()?.type()!==_.Frame&&n.reloadPage(e,t)}async storageKeyForFrame(e){if(!this.framesInternal.has(e))return null;const t=await this.storageAgent.invoke_getStorageKeyForFrame({frameId:e});return"Frame tree node for given frame not found"===t.getError()?null:t.storageKey}domModel(){return this.target().model(Pn)}processCachedResources(e){e&&":"!==e.frame.url&&(this.dispatchEventToListeners(_n.WillLoadCachedResources),this.addFramesRecursively(null,e),this.target().setInspectedURL(e.frame.url)),this.#mi=!0;const t=this.target().model(Cr);t&&(t.setExecutionContextComparator(this.executionContextComparator.bind(this)),t.fireExecutionContextOrderChanged()),this.dispatchEventToListeners(_n.CachedResourcesLoaded,this)}cachedResourcesLoaded(){return this.#mi}addFrame(e,t){this.framesInternal.set(e.id,e),e.isMainFrame()&&(this.mainFrame=e),this.dispatchEventToListeners(_n.FrameAdded,e),this.updateSecurityOrigins(),this.updateStorageKeys()}frameAttached(e,t,n){const r=t&&this.framesInternal.get(t)||null;if(!this.#mi&&r)return null;if(this.framesInternal.has(e))return null;const s=new Wn(this,r,e,null,n||null);return t&&!r&&(s.crossTargetParentFrameId=t),s.isMainFrame()&&this.mainFrame&&this.frameDetached(this.mainFrame.id,!1),this.addFrame(s,!0),s}frameNavigated(e,t){const n=e.parentId&&this.framesInternal.get(e.parentId)||null;if(!this.#mi&&n)return;let r=this.framesInternal.get(e.id)||null;if(!r&&(r=this.frameAttached(e.id,e.parentId||null),console.assert(Boolean(r)),!r))return;this.dispatchEventToListeners(_n.FrameWillNavigate,r),r.navigate(e),t&&(r.backForwardCacheDetails.restoredFromCache="BackForwardCacheRestore"===t),this.dispatchEventToListeners(_n.FrameNavigated,r),r.isPrimaryFrame()&&this.primaryPageChanged(r,"Navigation");const s=r.resources();for(let e=0;e=0,"Unbalanced call to ResourceTreeModel.resumeReload()"),!this.#bi&&this.#fi){const{ignoreCache:e,scriptToEvaluateOnLoad:t}=this.#fi;this.reloadPage(e,t)}}reloadPage(e,t){if(this.#fi||this.dispatchEventToListeners(_n.PageReloadRequested,this),this.#bi)return void(this.#fi={ignoreCache:e,scriptToEvaluateOnLoad:t});this.#fi=null;const n=this.target().model(ne);n&&n.clearRequests(),this.dispatchEventToListeners(_n.WillReloadPage),this.agent.invoke_reload({ignoreCache:e,scriptToEvaluateOnLoad:t})}navigate(e){return this.agent.invoke_navigate({url:e})}async navigationHistory(){const e=await this.agent.invoke_getNavigationHistory();return e.getError()?null:{currentIndex:e.currentIndex,entries:e.entries}}navigateToHistoryEntry(e){this.agent.invoke_navigateToHistoryEntry({entryId:e.id})}setLifecycleEventsEnabled(e){return this.agent.invoke_setLifecycleEventsEnabled({enabled:e})}async fetchAppManifest(){const e=await this.agent.invoke_getAppManifest();return e.getError()?{url:e.url,data:null,errors:[]}:{url:e.url,data:e.data||null,errors:e.errors}}async getInstallabilityErrors(){return(await this.agent.invoke_getInstallabilityErrors()).installabilityErrors||[]}async getAppId(){return this.agent.invoke_getAppId()}executionContextComparator(e,t){function n(e){let t=e;const n=[];for(;t;)n.push(t),t=t.sameTargetParentFrame();return n.reverse()}if(e.target()!==t.target())return Mr.comparator(e,t);const r=e.frameId?n(this.frameForId(e.frameId)):[],s=t.frameId?n(this.frameForId(t.frameId)):[];let i,a;for(let e=0;;e++)if(!r[e]||!s[e]||r[e]!==s[e]){i=r[e],a=s[e];break}return!i&&a?-1:!a&&i?1:i&&a?i.id.localeCompare(a.id):Mr.comparator(e,t)}getSecurityOriginData(){const t=new Set;let n=null,r=null;for(const s of this.framesInternal.values()){const i=s.securityOrigin;if(i&&(t.add(i),s.isMainFrame()&&(n=i,s.unreachableUrl()))){r=new e.ParsedURL.ParsedURL(s.unreachableUrl()).securityOrigin()}}return{securityOrigins:t,mainSecurityOrigin:n,unreachableMainSecurityOrigin:r}}async getStorageKeyData(){const e=new Set;let t=null;for(const{isMainFrame:n,storageKey:r}of await Promise.all([...this.framesInternal.values()].map((e=>e.getStorageKey(!1).then((t=>({isMainFrame:e.isMainFrame(),storageKey:t})))))))n&&(t=r),r&&e.add(r);return{storageKeys:e,mainStorageKey:t}}updateSecurityOrigins(){const e=this.getSecurityOriginData();this.#gi.setMainSecurityOrigin(e.mainSecurityOrigin||"",e.unreachableMainSecurityOrigin||""),this.#gi.updateSecurityOrigins(e.securityOrigins)}async updateStorageKeys(){const e=await this.getStorageKeyData();this.#pi.setMainStorageKey(e.mainStorageKey||""),this.#pi.updateStorageKeys(e.storageKeys)}async getMainStorageKey(){return this.mainFrame?this.mainFrame.getStorageKey(!1):null}getMainSecurityOrigin(){const e=this.getSecurityOriginData();return e.mainSecurityOrigin||e.unreachableMainSecurityOrigin}onBackForwardCacheNotUsed(e){this.mainFrame&&this.mainFrame.id===e.frameId&&this.mainFrame.loaderId===e.loaderId?(this.mainFrame.setBackForwardCacheDetails(e),this.dispatchEventToListeners(_n.BackForwardCacheDetailsUpdated,this.mainFrame)):this.#yi.add(e)}onPrerenderAttemptCompleted(e){this.mainFrame&&this.mainFrame.id===e.initiatingFrameId?(this.mainFrame.setPrerenderFinalStatus(e.finalStatus),this.dispatchEventToListeners(_n.PrerenderingStatusUpdated,this.mainFrame),e.disallowedApiMethod&&this.mainFrame.setPrerenderDisallowedApiMethod(e.disallowedApiMethod)):this.#vi.add(e),this.dispatchEventToListeners(_n.PrerenderAttemptCompleted,e)}processPendingEvents(e){if(e.isMainFrame()){for(const t of this.#yi)if(e.id===t.frameId&&e.loaderId===t.loaderId){e.setBackForwardCacheDetails(t),this.#yi.delete(t);break}for(const t of this.#vi)if(e.id===t.initiatingFrameId){e.setPrerenderFinalStatus(t.finalStatus),t.disallowedApiMethod&&e.setPrerenderDisallowedApiMethod(t.disallowedApiMethod),this.#vi.delete(t);break}}}}!function(e){e.FrameAdded="FrameAdded",e.FrameNavigated="FrameNavigated",e.FrameDetached="FrameDetached",e.FrameResized="FrameResized",e.FrameWillNavigate="FrameWillNavigate",e.PrimaryPageChanged="PrimaryPageChanged",e.ResourceAdded="ResourceAdded",e.WillLoadCachedResources="WillLoadCachedResources",e.CachedResourcesLoaded="CachedResourcesLoaded",e.DOMContentLoaded="DOMContentLoaded",e.LifecycleEvent="LifecycleEvent",e.Load="Load",e.PageReloadRequested="PageReloadRequested",e.WillReloadPage="WillReloadPage",e.InterstitialShown="InterstitialShown",e.InterstitialHidden="InterstitialHidden",e.BackForwardCacheDetailsUpdated="BackForwardCacheDetailsUpdated",e.PrerenderingStatusUpdated="PrerenderingStatusUpdated",e.PrerenderAttemptCompleted="PrerenderAttemptCompleted",e.JavaScriptDialogOpening="JavaScriptDialogOpening"}(_n||(_n={}));class Wn{#$r;#ki;#E;crossTargetParentFrameId;#Te;#u;#mt;#Si;#wi;#Ci;#Ti;#Ri;#xi;#Mi;#Pi;#Li;#Ei;#Ai;resourcesMap;backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};prerenderFinalStatus;prerenderDisallowedApiMethod;constructor(e,n,r,s,i){this.#$r=e,this.#ki=n,this.#E=r,this.crossTargetParentFrameId=null,this.#Te=s&&s.loaderId||"",this.#u=s&&s.name,this.#mt=s&&s.url||t.DevToolsPath.EmptyUrlString,this.#Si=s&&s.domainAndRegistry||"",this.#wi=s&&s.securityOrigin,this.#Ti=s&&s.unreachableUrl||t.DevToolsPath.EmptyUrlString,this.#Ri=s?.adFrameStatus,this.#xi=s&&s.secureContextType,this.#Mi=s&&s.crossOriginIsolatedContextType,this.#Pi=s&&s.gatedAPIFeatures,this.#Li=i,this.#Ei=null,this.#Ai=new Set,this.resourcesMap=new Map,this.prerenderFinalStatus=null,this.prerenderDisallowedApiMethod=null,this.#ki&&this.#ki.#Ai.add(this)}isSecureContext(){return null!==this.#xi&&this.#xi.startsWith("Secure")}getSecureContextType(){return this.#xi}isCrossOriginIsolated(){return null!==this.#Mi&&this.#Mi.startsWith("Isolated")}getCrossOriginIsolatedContextType(){return this.#Mi}getGatedAPIFeatures(){return this.#Pi}getCreationStackTraceData(){return{creationStackTrace:this.#Li,creationStackTraceTarget:this.#Ei||this.resourceTreeModel().target()}}navigate(e){this.#Te=e.loaderId,this.#u=e.name,this.#mt=e.url,this.#Si=e.domainAndRegistry,this.#wi=e.securityOrigin,this.getStorageKey(!0),this.#Ti=e.unreachableUrl||t.DevToolsPath.EmptyUrlString,this.#Ri=e?.adFrameStatus,this.#xi=e.secureContextType,this.#Mi=e.crossOriginIsolatedContextType,this.#Pi=e.gatedAPIFeatures,this.backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};const n=this.resourcesMap.get(this.#mt);this.resourcesMap.clear(),this.removeChildFrames(),n&&n.loaderId===this.#Te&&this.addResource(n)}resourceTreeModel(){return this.#$r}get id(){return this.#E}get name(){return this.#u||""}get url(){return this.#mt}domainAndRegistry(){return this.#Si}async getAdScriptId(e){return(await this.#$r.agent.invoke_getAdScriptId({frameId:e})).adScriptId||null}get securityOrigin(){return this.#wi}getStorageKey(e){return this.#Ci&&!e||(this.#Ci=this.#$r.storageKeyForFrame(this.#E)),this.#Ci}unreachableUrl(){return this.#Ti}get loaderId(){return this.#Te}adFrameType(){return this.#Ri?.adFrameType||"none"}adFrameStatus(){return this.#Ri}get childFrames(){return[...this.#Ai]}sameTargetParentFrame(){return this.#ki}crossTargetParentFrame(){if(!this.crossTargetParentFrameId)return null;const e=this.#$r.target().parentTarget();if(e?.type()!==_.Frame)return null;const t=e.model(jn);return t&&t.framesInternal.get(this.crossTargetParentFrameId)||null}parentFrame(){return this.sameTargetParentFrame()||this.crossTargetParentFrame()}isMainFrame(){return!this.#ki}isOutermostFrame(){return this.#$r.target().parentTarget()?.type()!==_.Frame&&!this.#ki&&!this.crossTargetParentFrameId}isPrimaryFrame(){return!this.#ki&&this.#$r.target()===K.instance().primaryPageTarget()}removeChildFrame(e,t){this.#Ai.delete(e),e.remove(t)}removeChildFrames(){const e=this.#Ai;this.#Ai=new Set;for(const t of e)t.remove(!1)}remove(e){this.removeChildFrames(),this.#$r.framesInternal.delete(this.id),this.#$r.dispatchEventToListeners(_n.FrameDetached,{frame:this,isSwap:e})}addResource(e){this.resourcesMap.get(e.url)!==e&&(this.resourcesMap.set(e.url,e),this.#$r.dispatchEventToListeners(_n.ResourceAdded,e))}addRequest(e){let t=this.resourcesMap.get(e.url());t&&t.request===e||(t=new Nn(this.#$r,e,e.url(),e.documentURL,e.frameId,e.loaderId,e.resourceType(),e.mimeType,null,null),this.resourcesMap.set(t.url,t),this.#$r.dispatchEventToListeners(_n.ResourceAdded,t))}resources(){return Array.from(this.resourcesMap.values())}resourceForURL(e){const t=this.resourcesMap.get(e);if(t)return t;for(const t of this.#Ai){const n=t.resourceForURL(e);if(n)return n}return null}callForFrameResources(e){for(const t of this.resourcesMap.values())if(e(t))return!0;for(const t of this.#Ai)if(t.callForFrameResources(e))return!0;return!1}displayName(){if(this.isOutermostFrame())return s.i18n.lockedString("top");const t=new e.ParsedURL.ParsedURL(this.#mt).displayName;return t?this.#u?this.#u+" ("+t+")":t:s.i18n.lockedString("iframe")}async getOwnerDeferredDOMNode(){const e=this.parentFrame();return e?e.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#E):null}async getOwnerDOMNodeOrDocument(){const e=await this.getOwnerDeferredDOMNode();return e?e.resolvePromise():this.isOutermostFrame()?this.resourceTreeModel().domModel().requestDocument():null}async highlight(){const e=this.parentFrame(),t=this.resourceTreeModel().target().parentTarget(),n=async e=>{const t=await e.getOwnerNodeForFrame(this.#E);t&&e.overlayModel().highlightInOverlay({deferredNode:t,selectorList:""},"all",!0)};if(e)return n(e.resourceTreeModel().domModel());if(t?.type()===_.Frame){const e=t.model(Pn);if(e)return n(e)}const r=await this.resourceTreeModel().domModel().requestDocument();r&&this.resourceTreeModel().domModel().overlayModel().highlightInOverlay({node:r,selectorList:""},"all",!0)}async getPermissionsPolicyState(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getPermissionsPolicyState({frameId:this.#E});return e.getError()?null:e.states}async getOriginTrials(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getOriginTrials({frameId:this.#E});return e.getError()?[]:e.originTrials}setCreationStackTrace(e){this.#Li=e.creationStackTrace,this.#Ei=e.creationStackTraceTarget}setBackForwardCacheDetails(e){this.backForwardCacheDetails.restoredFromCache=!1,this.backForwardCacheDetails.explanations=e.notRestoredExplanations,this.backForwardCacheDetails.explanationsTree=e.notRestoredExplanationsTree}getResourcesMap(){return this.resourcesMap}setPrerenderFinalStatus(e){this.prerenderFinalStatus=e}setPrerenderDisallowedApiMethod(e){this.prerenderDisallowedApiMethod=e}}class Vn{#Er;constructor(e){this.#Er=e}backForwardCacheNotUsed(e){this.#Er.onBackForwardCacheNotUsed(e)}domContentEventFired({timestamp:e}){this.#Er.dispatchEventToListeners(_n.DOMContentLoaded,e)}loadEventFired({timestamp:e}){this.#Er.dispatchEventToListeners(_n.Load,{resourceTreeModel:this.#Er,loadTime:e})}lifecycleEvent({frameId:e,name:t}){this.#Er.dispatchEventToListeners(_n.LifecycleEvent,{frameId:e,name:t})}frameAttached({frameId:e,parentFrameId:t,stack:n}){this.#Er.frameAttached(e,t,n)}frameNavigated({frame:e,type:t}){this.#Er.frameNavigated(e,t)}documentOpened({frame:e}){this.#Er.documentOpened(e)}frameDetached({frameId:e,reason:t}){this.#Er.frameDetached(e,"swap"===t)}frameStartedLoading({}){}frameStoppedLoading({}){}frameRequestedNavigation({}){}frameScheduledNavigation({}){}frameClearedScheduledNavigation({}){}navigatedWithinDocument({}){}frameResized(){this.#Er.dispatchEventToListeners(_n.FrameResized)}javascriptDialogOpening(e){this.#Er.dispatchEventToListeners(_n.JavaScriptDialogOpening,e),e.hasBrowserHandler||this.#Er.agent.invoke_handleJavaScriptDialog({accept:!1})}javascriptDialogClosed({}){}screencastFrame({}){}screencastVisibilityChanged({}){}interstitialShown(){this.#Er.isInterstitialShowing=!0,this.#Er.dispatchEventToListeners(_n.InterstitialShown)}interstitialHidden(){this.#Er.isInterstitialShowing=!1,this.#Er.dispatchEventToListeners(_n.InterstitialHidden)}windowOpen({}){}compilationCacheProduced({}){}fileChooserOpened({}){}downloadWillBegin({}){}downloadProgress(){}}class Gn{#Er;constructor(e){this.#Er=e}ruleSetUpdated(e){}ruleSetRemoved(e){}prerenderAttemptCompleted(e){this.#Er.onPrerenderAttemptCompleted(e)}prefetchStatusUpdated(e){}prerenderStatusUpdated(e){}preloadEnabledStateUpdated(e){}preloadingAttemptSourcesUpdated(){}}c.register(jn,{capabilities:z.DOM,autostart:!0,early:!0});var Kn=Object.freeze({__proto__:null,ResourceTreeModel:jn,get Events(){return _n},ResourceTreeFrame:Wn,PageDispatcher:Vn});const $n={scriptRemovedOrDeleted:"Script removed or deleted.",unableToFetchScriptSource:"Unable to fetch script source."},Qn=s.i18n.registerUIStrings("core/sdk/Script.ts",$n),Xn=s.i18n.getLocalizedString.bind(void 0,Qn);let Jn=null;class Yn{debuggerModel;scriptId;sourceURL;lineOffset;columnOffset;endLine;endColumn;executionContextId;hash;#Oi;#Ni;sourceMapURL;debugSymbols;hasSourceURL;contentLength;originStackTrace;#Fi;#Bi;#Di;#Ui;isModule;constructor(e,t,n,r,s,i,a,o,l,d,c,h,u,g,p,m,f,b,y,v){this.debuggerModel=e,this.scriptId=t,this.sourceURL=n,this.lineOffset=r,this.columnOffset=s,this.endLine=i,this.endColumn=a,this.isModule=p,this.executionContextId=o,this.hash=l,this.#Oi=d,this.#Ni=c,this.sourceMapURL=h,this.debugSymbols=y,this.hasSourceURL=u,this.contentLength=g,this.originStackTrace=m,this.#Fi=f,this.#Bi=b,this.#Di=null,this.#Ui=v}embedderName(){return this.#Ui}target(){return this.debuggerModel.target()}static trimSourceURLComment(e){let t=e.lastIndexOf("//# sourceURL=");if(-1===t&&(t=e.lastIndexOf("//@ sourceURL="),-1===t))return e;const n=e.lastIndexOf("\n",t);if(-1===n)return e;return e.substr(n+1).match(er)?e.substr(0,n):e}isContentScript(){return this.#Oi}codeOffset(){return this.#Fi}isJavaScript(){return"JavaScript"===this.#Bi}isWasm(){return"WebAssembly"===this.#Bi}scriptLanguage(){return this.#Bi}executionContext(){return this.debuggerModel.runtimeModel().executionContext(this.executionContextId)}isLiveEdit(){return this.#Ni}contentURL(){return this.sourceURL}contentType(){return e.ResourceType.resourceTypes.Script}async loadTextContent(){const e=await this.debuggerModel.target().debuggerAgent().invoke_getScriptSource({scriptId:this.scriptId});if(e.getError())throw new Error(e.getError());const{scriptSource:t,bytecode:n}=e;if(n)return{content:n,isEncoded:!0};let r=t||"";return this.hasSourceURL&&this.sourceURL.startsWith("snippet://")&&(r=Yn.trimSourceURLComment(r)),{content:r,isEncoded:!1}}async loadWasmContent(){if(!this.isWasm())throw new Error("Not a wasm script");const t=await this.debuggerModel.target().debuggerAgent().invoke_disassembleWasmModule({scriptId:this.scriptId});if(t.getError())return this.loadTextContent();const{streamId:n,functionBodyOffsets:r,chunk:{lines:s,bytecodeOffsets:i}}=t,a=[],o=[];let l=s.reduce(((e,t)=>e+t.length+1),0);const d="",c=1e9-d.length;if(n)for(;;){const e=await this.debuggerModel.target().debuggerAgent().invoke_nextWasmDisassemblyChunk({streamId:n});if(e.getError())throw new Error(e.getError());const{chunk:{lines:t,bytecodeOffsets:r}}=e;if(l+=t.reduce(((e,t)=>e+t.length+1),0),0===t.length)break;if(l>=c){a.push([d]),o.push([0]);break}a.push(t),o.push(r)}const h=[];for(let e=0;ee){Jn||(Jn={cache:new Map,registry:new FinalizationRegistry((e=>Jn?.cache.delete(e)))});const e=[this.#Bi,this.contentLength,this.lineOffset,this.columnOffset,this.endLine,this.endColumn,this.#Fi,this.hash].join(":"),t=Jn.cache.get(e)?.deref();t?this.#Di=t:(this.#Di=this.requestContentInternal(),Jn.cache.set(e,new WeakRef(this.#Di)),Jn.registry.register(this.#Di,e))}else this.#Di=this.requestContentInternal()}return this.#Di}async requestContentInternal(){if(!this.scriptId)return{content:null,error:Xn($n.scriptRemovedOrDeleted),isEncoded:!1};try{return this.isWasm()?await this.loadWasmContent():await this.loadTextContent()}catch(e){return{content:null,error:Xn($n.unableToFetchScriptSource),isEncoded:!1}}}async getWasmBytecode(){const e=await this.debuggerModel.target().debuggerAgent().invoke_getWasmBytecode({scriptId:this.scriptId});return(await fetch(`data:application/wasm;base64,${e.bytecode}`)).arrayBuffer()}originalContentProvider(){return new r.StaticContentProvider.StaticContentProvider(this.contentURL(),this.contentType(),(()=>this.requestContent()))}async searchInContent(e,t,n){if(!this.scriptId)return[];return((await this.debuggerModel.target().debuggerAgent().invoke_searchInContent({scriptId:this.scriptId,query:e,caseSensitive:t,isRegex:n})).result||[]).map((e=>new r.ContentProvider.SearchMatch(e.lineNumber,e.lineContent)))}appendSourceURLCommentIfNeeded(e){return this.hasSourceURL?e+"\n //# sourceURL="+this.sourceURL:e}async editSource(e){e=Yn.trimSourceURLComment(e),e=this.appendSourceURLCommentIfNeeded(e);const{content:t}=await this.requestContent();if(t===e)return{changed:!1,status:"Ok"};const n=await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({scriptId:this.scriptId,scriptSource:e,allowTopFrameEditing:!0});if(n.getError())throw new Error(`Script#editSource failed for script with id ${this.scriptId}: ${n.getError()}`);return n.getError()||"Ok"!==n.status||(this.#Di=Promise.resolve({content:e,isEncoded:!1})),this.debuggerModel.dispatchEventToListeners(cr.ScriptSourceWasEdited,{script:this,status:n.status}),{changed:!0,status:n.status,exceptionDetails:n.exceptionDetails}}rawLocation(e,t){return this.containsLocation(e,t)?new ur(this.debuggerModel,this.scriptId,e,t):null}isInlineScript(){const e=!this.lineOffset&&!this.columnOffset;return!this.isWasm()&&Boolean(this.sourceURL)&&!e}isAnonymousScript(){return!this.sourceURL}async setBlackboxedRanges(e){return!(await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({scriptId:this.scriptId,positions:e})).getError()}containsLocation(e,t){const n=e===this.lineOffset&&t>=this.columnOffset||e>this.lineOffset,r=e=0:!(r>0)||t(e.start,n.end)<=0}if(0===e.length)return[];e.sort(((e,n)=>e.scriptIdn.scriptId?1:t(e.start,n.start)||t(e.end,n.end)));let r=e[0];const s=[];for(let i=1;ithis.#Hi.setEnabled(e.data)));const n=t.model(jn);n&&n.addEventListener(_n.FrameNavigated,this.onFrameNavigated,this)}sourceMapManager(){return this.#Hi}runtimeModel(){return this.runtimeModelInternal}debuggerEnabled(){return Boolean(this.#Vi)}debuggerId(){return this.#Gi}async enableDebugger(){if(this.#Vi)return;this.#Vi=!0;const t=o.Runtime.Runtime.queryParam("remoteFrontend")||o.Runtime.Runtime.queryParam("ws")?1e7:1e8,n=this.agent.invoke_enable({maxScriptsCacheSize:t});let r;o.Runtime.experiments.isEnabled(o.Runtime.ExperimentName.INSTRUMENTATION_BREAKPOINTS)&&(r=this.agent.invoke_setInstrumentationBreakpoint({instrumentation:"beforeScriptExecution"})),this.pauseOnExceptionStateChanged(),this.asyncStackTracesStateChanged(),e.Settings.Settings.instance().moduleSetting("breakpointsActive").get()||this.breakpointsActiveChanged(),this.dispatchEventToListeners(cr.DebuggerWasEnabled,this);const[s]=await Promise.all([n,r]);this.registerDebugger(s)}async syncDebuggerId(){const e=o.Runtime.Runtime.queryParam("remoteFrontend")||o.Runtime.Runtime.queryParam("ws")?1e7:1e8,t=this.agent.invoke_enable({maxScriptsCacheSize:e});return t.then(this.registerDebugger.bind(this)),t}onFrameNavigated(){or.shouldResyncDebuggerId||(or.shouldResyncDebuggerId=!0)}registerDebugger(e){if(e.getError())return;const{debuggerId:t}=e;lr.set(t,this),this.#Gi=t,this.dispatchEventToListeners(cr.DebuggerIsReadyToPause,this)}isReadyToPause(){return Boolean(this.#Gi)}static async modelForDebuggerId(e){return or.shouldResyncDebuggerId&&(await or.resyncDebuggerIdForModels(),or.shouldResyncDebuggerId=!1),lr.get(e)||null}static async resyncDebuggerIdForModels(){const e=lr.values();for(const t of e)t.debuggerEnabled()&&await t.syncDebuggerId()}async disableDebugger(){this.#Vi&&(this.#Vi=!1,await this.asyncStackTracesStateChanged(),await this.agent.invoke_disable(),this.#ea=!1,this.globalObjectCleared(),this.dispatchEventToListeners(cr.DebuggerWasDisabled,this),"string"==typeof this.#Gi&&lr.delete(this.#Gi),this.#Gi=null)}skipAllPauses(e){this.#Ki&&(clearTimeout(this.#Ki),this.#Ki=0),this.agent.invoke_setSkipAllPauses({skip:e})}skipAllPausesUntilReloadOrTimeout(e){this.#Ki&&clearTimeout(this.#Ki),this.agent.invoke_setSkipAllPauses({skip:!0}),this.#Ki=window.setTimeout(this.skipAllPauses.bind(this,!1),e)}pauseOnExceptionStateChanged(){const t=e.Settings.Settings.instance().moduleSetting("pauseOnCaughtException").get();let n;const r=e.Settings.Settings.instance().moduleSetting("pauseOnUncaughtException").get();n=t&&r?"all":t?"caught":r?"uncaught":"none",this.agent.invoke_setPauseOnExceptions({state:n})}asyncStackTracesStateChanged(){const t=!e.Settings.Settings.instance().moduleSetting("disableAsyncStackTraces").get()&&this.#Vi?32:0;return this.agent.invoke_setAsyncCallStackDepth({maxDepth:t})}breakpointsActiveChanged(){this.agent.invoke_setBreakpointsActive({active:e.Settings.Settings.instance().moduleSetting("breakpointsActive").get()})}setComputeAutoStepRangesCallback(e){this.#Qi=e}async computeAutoStepSkipList(e){let t=[];if(this.#Qi&&this.#qi&&this.#qi.callFrames.length>0){const[n]=this.#qi.callFrames;t=await this.#Qi.call(null,e,n)}return ir(t.map((({start:e,end:t})=>({scriptId:e.scriptId,start:{lineNumber:e.lineNumber,columnNumber:e.columnNumber},end:{lineNumber:t.lineNumber,columnNumber:t.columnNumber}}))))}async stepInto(){const e=await this.computeAutoStepSkipList(ar.StepInto);this.agent.invoke_stepInto({breakOnAsyncCall:!1,skipList:e})}async stepOver(){this.#Zi=this.#qi?.callFrames[0]?.functionLocation()??null;const e=await this.computeAutoStepSkipList(ar.StepOver);this.agent.invoke_stepOver({skipList:e})}async stepOut(){const e=await this.computeAutoStepSkipList(ar.StepOut);0!==e.length?this.agent.invoke_stepOver({skipList:e}):this.agent.invoke_stepOut()}scheduleStepIntoAsync(){this.computeAutoStepSkipList(ar.StepInto).then((e=>{this.agent.invoke_stepInto({breakOnAsyncCall:!0,skipList:e})}))}resume(){this.agent.invoke_resume({terminateOnResume:!1}),this.#ea=!1}pause(){this.#ea=!0,this.skipAllPauses(!1),this.agent.invoke_pause()}async setBreakpointByURL(n,r,s,a){let o;if(this.target().type()===_.Node&&n.startsWith("file://")){const r=e.ParsedURL.ParsedURL.urlToRawPathString(n,i.Platform.isWin());o=`${t.StringUtilities.escapeForRegExp(r)}|${t.StringUtilities.escapeForRegExp(n)}`,i.Platform.isWin()&&r.match(/^.:\\/)&&(o=`[${r[0].toUpperCase()}${r[0].toLowerCase()}]`+o.substr(1))}let l=0;const d=this.#zi.get(n)||[];for(let e=0,t=d.length;eur.fromPayload(this,e)))),{locations:h,breakpointId:c.breakpointId}}async setBreakpointInAnonymousScript(e,t,n,r){const s=await this.agent.invoke_setBreakpointByUrl({lineNumber:t,scriptHash:e,columnNumber:n,condition:r});if(s.getError())return{locations:[],breakpointId:null};let i=[];return s.locations&&(i=s.locations.map((e=>ur.fromPayload(this,e)))),{locations:i,breakpointId:s.breakpointId}}async removeBreakpoint(e){await this.agent.invoke_removeBreakpoint({breakpointId:e})}async getPossibleBreakpoints(e,t,n){const r=await this.agent.invoke_getPossibleBreakpoints({start:e.payload(),end:t?t.payload():void 0,restrictToFunction:n});return r.getError()||!r.locations?[]:r.locations.map((e=>gr.fromPayload(this,e)))}async fetchAsyncStackTrace(e){const t=await this.agent.invoke_getStackTrace({stackTraceId:e});return t.getError()?null:t.stackTrace}breakpointResolved(e,t){this.#Yi.dispatchEventToListeners(e,ur.fromPayload(this,t))}globalObjectCleared(){this.resetDebuggerPausedDetails(),this.reset(),this.dispatchEventToListeners(cr.GlobalObjectCleared,this)}reset(){for(const e of this.#_i.values())this.#Hi.detachSourceMap(e);this.#_i.clear(),this.#zi.clear(),this.#ji=[],this.#Zi=null}scripts(){return Array.from(this.#_i.values())}scriptForId(e){return this.#_i.get(e)||null}scriptsForSourceURL(e){return this.#zi.get(e)||[]}scriptsForExecutionContext(e){const t=[];for(const n of this.#_i.values())n.executionContextId===e.id&&t.push(n);return t}get callFrames(){return this.#qi?this.#qi.callFrames:null}debuggerPausedDetails(){return this.#qi}async setDebuggerPausedDetails(e){return this.#ea=!1,this.#qi=e,!(this.#$i&&!await this.#$i.call(null,e,this.#Zi))&&(this.#Zi=null,this.dispatchEventToListeners(cr.DebuggerPaused,this),this.setSelectedCallFrame(e.callFrames[0]),!0)}resetDebuggerPausedDetails(){this.#ea=!1,this.#qi=null,this.setSelectedCallFrame(null)}setBeforePausedCallback(e){this.#$i=e}setExpandCallFramesCallback(e){this.#Xi=e}setEvaluateOnCallFrameCallback(e){this.evaluateOnCallFrameCallback=e}setSynchronizeBreakpointsCallback(e){this.#Ji=e}async pausedScript(t,n,r,s,i,a){if("instrumentation"===n){const e=this.scriptForId(r.scriptId);return this.#Ji&&e&&await this.#Ji(e),void this.resume()}const o=new fr(this,t,n,r,s,i,a);if(this.#Xi&&(o.callFrames=await this.#Xi.call(null,o.callFrames)),this.continueToLocationCallback){const e=this.continueToLocationCallback;if(this.continueToLocationCallback=null,e(o))return}await this.setDebuggerPausedDetails(o)?e.EventTarget.fireEvent("DevTools.DebuggerPaused"):this.#Zi?this.stepOver():this.stepInto()}resumedScript(){this.resetDebuggerPausedDetails(),this.dispatchEventToListeners(cr.DebuggerResumed,this)}parsedScriptSource(e,t,n,r,s,a,o,l,d,c,h,u,g,p,m,f,b,y,v,I){const k=this.#_i.get(e);if(k)return k;let S=!1;d&&"isDefault"in d&&(S=!d.isDefault);const w=new Yn(this,e,t,n,r,s,a,o,l,S,c,h,u,p,m,f,b,y,v,I);this.registerScript(w),this.dispatchEventToListeners(cr.ParsedScriptSource,w),w.isInlineScript()&&!w.hasSourceURL&&(w.isModule?i.userMetrics.inlineScriptParsed(0):i.userMetrics.inlineScriptParsed(1)),w.sourceMapURL&&!g&&this.#Hi.attachSourceMap(w,w.sourceURL,w.sourceMapURL);return g&&w.isAnonymousScript()&&(this.#ji.push(w),this.collectDiscardedScripts()),w}setSourceMapURL(e,t){this.#Hi.detachSourceMap(e),e.sourceMapURL=t,this.#Hi.attachSourceMap(e,e.sourceURL,e.sourceMapURL)}async setDebugInfoURL(e,t){this.#Xi&&this.#qi&&(this.#qi.callFrames=await this.#Xi.call(null,this.#qi.callFrames)),this.dispatchEventToListeners(cr.DebugInfoAttached,e)}executionContextDestroyed(e){for(const t of this.#_i.values())t.executionContextId===e.id&&this.#Hi.detachSourceMap(t)}registerScript(e){if(this.#_i.set(e.scriptId,e),e.isAnonymousScript())return;let t=this.#zi.get(e.sourceURL);t||(t=[],this.#zi.set(e.sourceURL,t)),t.unshift(e)}unregisterScript(e){console.assert(e.isAnonymousScript()),this.#_i.delete(e.scriptId)}collectDiscardedScripts(){if(this.#ji.length<1e3)return;const e=this.#ji.splice(0,100);for(const t of e)this.unregisterScript(t),this.dispatchEventToListeners(cr.DiscardedAnonymousScriptSource,t)}createRawLocation(e,t,n,r){return this.createRawLocationByScriptId(e.scriptId,t,n,r)}createRawLocationByURL(e,t,n,r){for(const s of this.#zi.get(e)||[])if(!(s.lineOffset>t||s.lineOffset===t&&void 0!==n&&s.columnOffset>n||s.endLinenull===this.#Ta.axNodeForId(e)))}hasUnloadedChildren(){return!(!this.#Na||!this.#Na.length)&&this.#Na.some((e=>null===this.#Ta.axNodeForId(e)))}getFrameId(){return this.#Oa||this.parentNode()?.getFrameId()||null}}(Lr||(Lr={})).TreeUpdated="TreeUpdated";class Or extends c{agent;#Fa;#Ba;#Da;#Ua;#Ha;constructor(e){super(e),e.registerAccessibilityDispatcher(this),this.agent=e.accessibilityAgent(),this.resumeModel(),this.#Fa=new Map,this.#Ba=new Map,this.#Da=new Map,this.#Ua=new Map,this.#Ha=null}clear(){this.#Ha=null,this.#Fa.clear(),this.#Ba.clear(),this.#Da.clear()}async resumeModel(){await this.agent.invoke_enable()}async suspendModel(){await this.agent.invoke_disable()}async requestPartialAXTree(e){const{nodes:t}=await this.agent.invoke_getPartialAXTree({nodeId:e.id,fetchRelatives:!0});if(!t)return;const n=[];for(const e of t)n.push(new Ar(this,e))}loadComplete({root:e}){this.clear(),this.#Ha=new Ar(this,e),this.dispatchEventToListeners(Lr.TreeUpdated,{root:this.#Ha})}nodesUpdated({nodes:e}){this.createNodesFromPayload(e),this.dispatchEventToListeners(Lr.TreeUpdated,{})}createNodesFromPayload(e){return e.map((e=>new Ar(this,e)))}async requestRootNode(e){if(e&&this.#Da.has(e))return this.#Da.get(e);if(!e&&this.#Ha)return this.#Ha;const{node:t}=await this.agent.invoke_getRootAXNode({frameId:e});return t?this.createNodesFromPayload([t])[0]:void 0}async requestAXChildren(e,t){const n=this.#Fa.get(e);if(!n)throw Error("Cannot request children before parent");if(!n.hasUnloadedChildren())return n.children();const r=this.#Ua.get(e);if(r)await r;else{const n=this.agent.invoke_getChildAXNodes({id:e,frameId:t});this.#Ua.set(e,n);const r=await n;r.getError()||(this.createNodesFromPayload(r.nodes),this.#Ua.delete(e))}return n.children()}async requestAndLoadSubTreeToNode(e){const t=[];let n=this.axNodeForDOMNode(e);for(;n;){t.push(n);const e=n.parentNode();if(!e)return t;n=e}const{nodes:r}=await this.agent.invoke_getAXNodeAndAncestors({backendNodeId:e.backendNodeId()});if(!r)return null;return this.createNodesFromPayload(r)}axNodeForId(e){return this.#Fa.get(e)||null}setRootAXNodeForFrameId(e,t){this.#Da.set(e,t)}axNodeForFrameId(e){return this.#Da.get(e)??null}setAXNodeForAXId(e,t){this.#Fa.set(e,t)}axNodeForDOMNode(e){return e?this.#Ba.get(e.backendNodeId())??null:null}setAXNodeForBackendDOMNodeId(e,t){this.#Ba.set(e,t)}getAgent(){return this.agent}}c.register(Or,{capabilities:z.DOM,autostart:!1});var Nr=Object.freeze({__proto__:null,get CoreAxPropertyName(){return Pr},AccessibilityNode:Ar,get Events(){return Lr},AccessibilityModel:Or});class Fr{#qa;titleInternal;enabledInternal;constructor(e,t){this.#qa=e,this.titleInternal=t,this.enabledInternal=!1}category(){return this.#qa}enabled(){return this.enabledInternal}setEnabled(e){this.enabledInternal=e}title(){return this.titleInternal}setTitle(e){this.titleInternal=e}}var Br=Object.freeze({__proto__:null,CategorizedBreakpoint:Fr});class Dr{onMessage;#_a;#za;#ja;#ar;constructor(){this.onMessage=null,this.#_a=null,this.#za="",this.#ja=0,this.#ar=[i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.DispatchMessage,this.dispatchMessage,this),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.DispatchMessageChunk,this.dispatchMessageChunk,this)]}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}sendRawMessage(e){this.onMessage&&i.InspectorFrontendHost.InspectorFrontendHostInstance.sendMessageToBackend(e)}dispatchMessage(e){this.onMessage&&this.onMessage.call(null,e.data)}dispatchMessageChunk(e){const{messageChunk:t,messageSize:n}=e.data;n&&(this.#za="",this.#ja=n),this.#za+=t,this.#za.length===this.#ja&&this.onMessage&&(this.onMessage.call(null,this.#za),this.#za="",this.#ja=0)}async disconnect(){const t=this.#_a;e.EventTarget.removeEventListeners(this.#ar),this.#_a=null,this.onMessage=null,t&&t.call(null,"force disconnect")}}class Ur{#Wa;onMessage;#_a;#Va;#Ga;#Ka;constructor(e,t){this.#Wa=new WebSocket(e),this.#Wa.onerror=this.onError.bind(this),this.#Wa.onopen=this.onOpen.bind(this),this.#Wa.onmessage=e=>{this.onMessage&&this.onMessage.call(null,e.data)},this.#Wa.onclose=this.onClose.bind(this),this.onMessage=null,this.#_a=null,this.#Va=t,this.#Ga=!1,this.#Ka=[]}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}onError(){this.#Va&&this.#Va.call(null),this.#_a&&this.#_a.call(null,"connection failed"),this.close()}onOpen(){if(this.#Ga=!0,this.#Wa){this.#Wa.onerror=console.error;for(const e of this.#Ka)this.#Wa.send(e)}this.#Ka=[]}onClose(){this.#Va&&this.#Va.call(null),this.#_a&&this.#_a.call(null,"websocket closed"),this.close()}close(e){this.#Wa&&(this.#Wa.onerror=null,this.#Wa.onopen=null,this.#Wa.onclose=e||null,this.#Wa.onmessage=null,this.#Wa.close(),this.#Wa=null),this.#Va=null}sendRawMessage(e){this.#Ga&&this.#Wa?this.#Wa.send(e):this.#Ka.push(e)}disconnect(){return new Promise((e=>{this.close((()=>{this.#_a&&this.#_a.call(null,"force disconnect"),e()}))}))}}class Hr{onMessage;#_a;constructor(){this.onMessage=null,this.#_a=null}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}sendRawMessage(e){window.setTimeout(this.respondWithError.bind(this,e),0)}respondWithError(e){const t=JSON.parse(e),n={message:"This is a stub connection, can't dispatch message.",code:a.InspectorBackend.DevToolsStubErrorCode,data:t};this.onMessage&&this.onMessage.call(null,{id:t.id,error:n})}async disconnect(){this.#_a&&this.#_a.call(null,"force disconnect"),this.#_a=null,this.onMessage=null}}class qr{#$a;#Qa;onMessage;#_a;constructor(e,t){this.#$a=e,this.#Qa=t,this.onMessage=null,this.#_a=null}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}getOnDisconnect(){return this.#_a}sendRawMessage(e){const t=JSON.parse(e);t.sessionId||(t.sessionId=this.#Qa),this.#$a.sendRawMessage(JSON.stringify(t))}getSessionId(){return this.#Qa}async disconnect(){this.#_a&&this.#_a.call(null,"force disconnect"),this.#_a=null,this.onMessage=null}}function _r(e){const t=o.Runtime.Runtime.queryParam("ws"),n=o.Runtime.Runtime.queryParam("wss");if(t||n){return new Ur(t?`ws://${t}`:`wss://${n}`,e)}return i.InspectorFrontendHost.InspectorFrontendHostInstance.isHostedMode()?new Hr:new Dr}var zr,jr=Object.freeze({__proto__:null,MainConnection:Dr,WebSocketConnection:Ur,StubConnection:Hr,ParallelConnection:qr,initMainConnection:async function(e,t){a.InspectorBackend.Connection.setFactory(_r.bind(null,t)),await e(),i.InspectorFrontendHost.InspectorFrontendHostInstance.connectionReady(),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.ReattachRootTarget,(()=>{const t=K.instance().rootTarget();if(t){const e=t.router();e&&e.connection().disconnect()}e()}))}});class Wr extends c{#Xa;#Ja;#Ya;#Za=new Map;#eo=new Map;#to=new Map;#no=new Map;#ro=null;constructor(e){super(e),this.#Xa=e.targetManager(),this.#Ja=e,this.#Ya=e.targetAgent(),e.registerTargetDispatcher(this);const t=this.#Xa.browserTarget();t?t!==e&&t.targetAgent().invoke_autoAttachRelated({targetId:e.id(),waitForDebuggerOnStart:!0}):this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),e.parentTarget()?.type()===_.Frame||i.InspectorFrontendHost.isUnderTest()||(this.#Ya.invoke_setDiscoverTargets({discover:!0}),this.#Ya.invoke_setRemoteLocations({locations:[{host:"localhost",port:9229}]}))}static install(e){Wr.attachCallback=e,c.register(Wr,{capabilities:z.Target,autostart:!0})}childTargets(){return Array.from(this.#eo.values())}async suspendModel(){await this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0})}async resumeModel(){await this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0})}dispose(){for(const e of this.#eo.keys())this.detachedFromTarget({sessionId:e,targetId:void 0})}targetCreated({targetInfo:e}){this.#Za.set(e.targetId,e),this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetCreated,e)}targetInfoChanged({targetInfo:e}){this.#Za.set(e.targetId,e);const t=this.#to.get(e.targetId);if(t)if("prerender"!==t.targetInfo()?.subtype||e.subtype)t.updateTargetInfo(e);else{const n=t.model(jn);t.updateTargetInfo(e),n&&n.mainFrame&&n.primaryPageChanged(n.mainFrame,"Activation")}this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetInfoChanged,e)}targetDestroyed({targetId:e}){this.#Za.delete(e),this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetDestroyed,e)}targetCrashed({targetId:e,status:t,errorCode:n}){}fireAvailableTargetsChanged(){K.instance().dispatchEventToListeners($.AvailableTargetsChanged,[...this.#Za.values()])}async getParentTargetId(){return this.#ro||(this.#ro=(await this.#Ja.targetAgent().invoke_getTargetInfo({})).targetInfo.targetId),this.#ro}async attachedToTarget({sessionId:t,targetInfo:n,waitingForDebugger:r}){if(this.#ro===n.targetId)return;let s=_.Browser,i="";if("worker"===n.type&&n.title&&n.title!==n.url)i=n.title;else if(!["page","iframe","webview"].includes(n.type))if("chrome://print/"===n.url||n.url.startsWith("chrome://")&&n.url.endsWith(".top-chrome/"))s=_.Frame;else{const t=e.ParsedURL.ParsedURL.fromString(n.url);i=t?t.lastPathComponentWithFragment():"#"+ ++Wr.lastAnonymousTargetId,"devtools"===t?.scheme&&"other"===n.type&&(s=_.Frame)}"iframe"===n.type||"webview"===n.type||"background_page"===n.type||"app"===n.type||"popup_page"===n.type||"page"===n.type?s=_.Frame:"worker"===n.type?s=_.Worker:"shared_worker"===n.type?s=_.SharedWorker:"service_worker"===n.type?s=_.ServiceWorker:"auction_worklet"===n.type&&(s=_.AuctionWorklet);const a=this.#Xa.createTarget(n.targetId,i,s,this.#Ja,t,void 0,void 0,n);this.#eo.set(t,a),this.#to.set(a.id(),a),Wr.attachCallback&&await Wr.attachCallback({target:a,waitingForDebugger:r}),r&&a.runtimeAgent().invoke_runIfWaitingForDebugger()}detachedFromTarget({sessionId:e}){if(this.#no.has(e))this.#no.delete(e);else{const t=this.#eo.get(e);t&&(t.dispose("target terminated"),this.#eo.delete(e),this.#to.delete(t.id()))}}receivedMessageFromTarget({}){}async createParallelConnection(e){const t=await this.getParentTargetId(),{connection:n,sessionId:r}=await this.createParallelConnectionAndSessionForTarget(this.#Ja,t);return n.setOnMessage(e),this.#no.set(r,n),{connection:n,sessionId:r}}async createParallelConnectionAndSessionForTarget(e,t){const n=e.targetAgent(),r=e.router(),s=(await n.invoke_attachToTarget({targetId:t,flatten:!0})).sessionId,i=new qr(r.connection(),s);return r.registerSession(e,s,i),i.setOnDisconnect((()=>{r.unregisterSession(s),n.invoke_detachFromTarget({sessionId:s})})),{connection:i,sessionId:s}}targetInfos(){return Array.from(this.#Za.values())}static lastAnonymousTargetId=0;static attachCallback}!function(e){e.TargetCreated="TargetCreated",e.TargetDestroyed="TargetDestroyed",e.TargetInfoChanged="TargetInfoChanged"}(zr||(zr={}));var Vr=Object.freeze({__proto__:null,ChildTargetManager:Wr,get Events(){return zr}});const Gr={couldNotLoadContentForSS:"Could not load content for {PH1} ({PH2})"},Kr=s.i18n.registerUIStrings("core/sdk/CompilerSourceMappingContentProvider.ts",Gr),$r=s.i18n.getLocalizedString.bind(void 0,Kr);var Qr,Xr,Jr=Object.freeze({__proto__:null,CompilerSourceMappingContentProvider:class{#so;#io;#ao;constructor(e,t,n){this.#so=e,this.#io=t,this.#ao=n}contentURL(){return this.#so}contentType(){return this.#io}async requestContent(){try{const{content:e}=await Ht.instance().loadResource(this.#so,this.#ao);return{content:e,isEncoded:!1}}catch(e){const t=$r(Gr.couldNotLoadContentForSS,{PH1:this.#so,PH2:e.message});return console.error(t),{content:null,error:t,isEncoded:!1}}}async searchInContent(e,t,n){const{content:s}=await this.requestContent();return"string"!=typeof s?[]:r.TextUtils.performSearchInContent(s,e,t,n)}}});!function(e){e.Result="result",e.Command="command",e.System="system",e.QueryObjectResult="queryObjectResult"}(Qr||(Qr={})),function(e){e.CSS="css",e.ConsoleAPI="console-api"}(Xr||(Xr={}));const Yr={profileD:"Profile {PH1}"},Zr=s.i18n.registerUIStrings("core/sdk/CPUProfilerModel.ts",Yr),es=s.i18n.getLocalizedString.bind(void 0,Zr);class ts extends c{#oo;#lo;#do;#co;#ho;#uo;registeredConsoleProfileMessages=[];constructor(e){super(e),this.#oo=!1,this.#lo=1,this.#do=new Map,this.#co=e.profilerAgent(),this.#ho=null,e.registerProfilerDispatcher(this),this.#co.invoke_enable(),this.#uo=e.model(or)}runtimeModel(){return this.#uo.runtimeModel()}debuggerModel(){return this.#uo}consoleProfileStarted({id:e,location:t,title:n}){n||(n=es(Yr.profileD,{PH1:this.#lo++}),this.#do.set(e,n));const r=this.createEventDataFrom(e,t,n);this.dispatchEventToListeners(ns.ConsoleProfileStarted,r)}consoleProfileFinished({id:e,location:t,profile:n,title:r}){r||(r=this.#do.get(e),this.#do.delete(e));const s={...this.createEventDataFrom(e,t,r),cpuProfile:n};this.registeredConsoleProfileMessages.push(s),this.dispatchEventToListeners(ns.ConsoleProfileFinished,s)}createEventDataFrom(e,t,n){const r=ur.fromPayload(this.#uo,t);return{id:this.target().id()+"."+e,scriptLocation:r,title:n||"",cpuProfilerModel:this}}isRecordingProfile(){return this.#oo}startRecording(){this.#oo=!0;return this.#co.invoke_setSamplingInterval({interval:100}),this.#co.invoke_start()}stopRecording(){return this.#oo=!1,this.#co.invoke_stop().then((e=>e.profile||null))}startPreciseCoverage(e,t){this.#ho=t;return this.#co.invoke_startPreciseCoverage({callCount:!1,detailed:e,allowTriggeredUpdates:!0})}async takePreciseCoverage(){const e=await this.#co.invoke_takePreciseCoverage();return{timestamp:e&&e.timestamp||0,coverage:e&&e.result||[]}}stopPreciseCoverage(){return this.#ho=null,this.#co.invoke_stopPreciseCoverage()}preciseCoverageDeltaUpdate({timestamp:e,occasion:t,result:n}){this.#ho&&this.#ho(e,t,n)}}var ns;!function(e){e.ConsoleProfileStarted="ConsoleProfileStarted",e.ConsoleProfileFinished="ConsoleProfileFinished"}(ns||(ns={})),c.register(ts,{capabilities:z.JS,autostart:!0});var rs,ss=Object.freeze({__proto__:null,CPUProfilerModel:ts,get Events(){return ns}});class is extends c{#go;constructor(e){super(e),e.registerLogDispatcher(this),this.#go=e.logAgent(),this.#go.invoke_enable(),i.InspectorFrontendHost.isUnderTest()||this.#go.invoke_startViolationsReport({config:[{name:"longTask",threshold:200},{name:"longLayout",threshold:30},{name:"blockedEvent",threshold:100},{name:"blockedParser",threshold:-1},{name:"handler",threshold:150},{name:"recurringHandler",threshold:50},{name:"discouragedAPIUse",threshold:-1}]})}entryAdded({entry:e}){this.dispatchEventToListeners(rs.EntryAdded,{logModel:this,entry:e})}requestClear(){this.#go.invoke_clear()}}(rs||(rs={})).EntryAdded="EntryAdded",c.register(is,{capabilities:z.Log,autostart:!0});var as=Object.freeze({__proto__:null,LogModel:is,get Events(){return rs}});const os={navigatedToS:"Navigated to {PH1}",bfcacheNavigation:"Navigation to {PH1} was restored from back/forward cache (see https://web.dev/bfcache/)",profileSStarted:"Profile ''{PH1}'' started.",profileSFinished:"Profile ''{PH1}'' finished.",failedToSaveToTempVariable:"Failed to save to temp variable."},ls=s.i18n.registerUIStrings("core/sdk/ConsoleModel.ts",os),ds=s.i18n.getLocalizedString.bind(void 0,ls);class cs extends c{#po;#mo;#fo;#bo;#yo;#vo;#Io;#ko;constructor(n){super(n),this.#po=[],this.#mo=new t.MapUtilities.Multimap,this.#fo=new Map,this.#bo=0,this.#yo=0,this.#vo=0,this.#Io=0,this.#ko=new WeakMap;const r=n.model(jn);if(!r||r.cachedResourcesLoaded())return void this.initTarget(n);const s=r.addEventListener(_n.CachedResourcesLoaded,(()=>{e.EventTarget.removeEventListeners([s]),this.initTarget(n)}))}initTarget(e){const t=[],n=e.model(ts);n&&(t.push(n.addEventListener(ns.ConsoleProfileStarted,this.consoleProfileStarted.bind(this,n))),t.push(n.addEventListener(ns.ConsoleProfileFinished,this.consoleProfileFinished.bind(this,n))));const r=e.model(jn);r&&e.parentTarget()?.type()!==_.Frame&&t.push(r.addEventListener(_n.PrimaryPageChanged,this.primaryPageChanged,this));const s=e.model(Cr);s&&(t.push(s.addEventListener(Rr.ExceptionThrown,this.exceptionThrown.bind(this,s))),t.push(s.addEventListener(Rr.ExceptionRevoked,this.exceptionRevoked.bind(this,s))),t.push(s.addEventListener(Rr.ConsoleAPICalled,this.consoleAPICalled.bind(this,s))),e.parentTarget()?.type()!==_.Frame&&t.push(s.debuggerModel().addEventListener(cr.GlobalObjectCleared,this.clearIfNecessary,this)),t.push(s.addEventListener(Rr.QueryObjectRequested,this.queryObjectRequested.bind(this,s)))),this.#ko.set(e,t)}targetRemoved(t){const n=t.model(Cr);n&&this.#fo.delete(n),e.EventTarget.removeEventListeners(this.#ko.get(t)||[])}async evaluateCommandInConsole(t,n,r,s){const a=await t.evaluate({expression:r,objectGroup:"console",includeCommandLineAPI:s,silent:!1,returnByValue:!1,generatePreview:!0,replMode:!0,allowUnsafeEvalBlockedByCSP:!1},e.Settings.Settings.instance().moduleSetting("consoleUserActivationEval").get(),!1);i.userMetrics.actionTaken(i.UserMetrics.Action.ConsoleEvaluated),"error"in a||(await e.Console.Console.instance().showPromise(),this.dispatchEventToListeners(hs.CommandEvaluated,{result:a.object,commandMessage:n,exceptionDetails:a.exceptionDetails}))}addCommandMessage(e,t){const n=new gs(e.runtimeModel,"javascript",null,t,{type:Qr.Command});return n.setExecutionContextId(e.id),this.addMessage(n),n}addMessage(e){e.setPageLoadSequenceNumber(this.#Io),e.source===Xr.ConsoleAPI&&"clear"===e.type&&this.clearIfNecessary(),this.#po.push(e),this.#mo.set(e.timestamp,e);const t=e.runtimeModel(),n=e.getExceptionId();if(n&&t){let r=this.#fo.get(t);r||(r=new Map,this.#fo.set(t,r)),r.set(n,e)}this.incrementErrorWarningCount(e),this.dispatchEventToListeners(hs.MessageAdded,e)}exceptionThrown(e,t){const n=t.data,r=function(e){if(!e)return;return{requestId:e.requestId||void 0,issueId:e.issueId||void 0}}(n.details.exceptionMetaData),s=gs.fromException(e,n.details,void 0,n.timestamp,void 0,r);s.setExceptionId(n.details.exceptionId),this.addMessage(s)}exceptionRevoked(e,t){const n=t.data,r=this.#fo.get(e),s=r?r.get(n):null;s&&(this.#yo--,s.level="verbose",this.dispatchEventToListeners(hs.MessageUpdated,s))}consoleAPICalled(e,t){const n=t.data;let r="info";"debug"===n.type?r="verbose":"error"===n.type||"assert"===n.type?r="error":"warning"===n.type?r="warning":"info"!==n.type&&"log"!==n.type||(r="info");let s="";n.args.length&&n.args[0].unserializableValue?s=n.args[0].unserializableValue:!n.args.length||"object"==typeof n.args[0].value&&null!==n.args[0].value?n.args.length&&n.args[0].description&&(s=n.args[0].description):s=String(n.args[0].value);const i=n.stackTrace&&n.stackTrace.callFrames.length?n.stackTrace.callFrames[0]:null,a={type:n.type,url:i?.url,line:i?.lineNumber,column:i?.columnNumber,parameters:n.args,stackTrace:n.stackTrace,timestamp:n.timestamp,executionContextId:n.executionContextId,context:n.context},o=new gs(e,Xr.ConsoleAPI,r,s,a);for(const e of this.#mo.get(o.timestamp).values())if(o.isEqual(e))return;this.addMessage(o)}queryObjectRequested(e,t){const{objects:n,executionContextId:r}=t.data,s={type:Qr.QueryObjectResult,parameters:[n],executionContextId:r},i=new gs(e,Xr.ConsoleAPI,"info","",s);this.addMessage(i)}clearIfNecessary(){e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()||this.clear(),++this.#Io}primaryPageChanged(t){if(e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()){const{frame:n}=t.data;n.backForwardCacheDetails.restoredFromCache?e.Console.Console.instance().log(ds(os.bfcacheNavigation,{PH1:n.url})):e.Console.Console.instance().log(ds(os.navigatedToS,{PH1:n.url}))}}consoleProfileStarted(e,t){const{data:n}=t;this.addConsoleProfileMessage(e,"profile",n.scriptLocation,ds(os.profileSStarted,{PH1:n.title}))}consoleProfileFinished(e,t){const{data:n}=t;this.addConsoleProfileMessage(e,"profileEnd",n.scriptLocation,ds(os.profileSFinished,{PH1:n.title}))}addConsoleProfileMessage(e,t,n,r){const s=n.script(),i=[{functionName:"",scriptId:n.scriptId,url:s?s.contentURL():"",lineNumber:n.lineNumber,columnNumber:n.columnNumber||0}];this.addMessage(new gs(e.runtimeModel(),Xr.ConsoleAPI,"info",r,{type:t,stackTrace:{callFrames:i}}))}incrementErrorWarningCount(e){if("violation"!==e.source)switch(e.level){case"warning":this.#bo++;break;case"error":this.#yo++}else this.#vo++}messages(){return this.#po}static allMessagesUnordered(){const e=[];for(const t of K.instance().targets()){const n=t.model(cs)?.messages()||[];e.push(...n)}return e}static requestClearMessages(){for(const e of K.instance().models(is))e.requestClear();for(const e of K.instance().models(Cr))e.discardConsoleEntries();for(const e of K.instance().targets())e.model(cs)?.clear()}clear(){this.#po=[],this.#mo.clear(),this.#fo.clear(),this.#yo=0,this.#bo=0,this.#vo=0,this.dispatchEventToListeners(hs.ConsoleCleared)}errors(){return this.#yo}static allErrors(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.errors()||0;return e}warnings(){return this.#bo}static allWarnings(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.warnings()||0;return e}violations(){return this.#vo}static allViolations(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.violations()||0;return e}async saveToTempVariable(t,n){if(!n||!t)return void o(null);const r=t,s=await r.globalObject("",!1);if("error"in s||Boolean(s.exceptionDetails)||!s.object)return void o("object"in s&&s.object||null);const i=s.object,a=await i.callFunction((function(e){const t="temp";let n=1;for(;t+n in this;)++n;const r=t+n;return this[r]=e,r}),[Le.toCallArgument(n)]);if(i.release(),a.wasThrown||!a.object||"string"!==a.object.type)o(a.object||null);else{const e=a.object.value,t=this.addCommandMessage(r,e);this.evaluateCommandInConsole(r,t,e,!1)}function o(t){let n=ds(os.failedToSaveToTempVariable);t&&(n=n+" "+t.description),e.Console.Console.instance().error(n)}a.object&&a.object.release()}}var hs;function us(e,t){if(!e!=!t)return!1;if(!e||!t)return!0;const n=e.callFrames,r=t.callFrames;if(n.length!==r.length)return!1;for(let e=0,t=n.length;et.includes(e)));if(-1===n||n===e.length-1)return{callFrame:null,type:null};const r=e[n].url===br?"LOGPOINT":"CONDITIONAL_BREAKPOINT";return{callFrame:e[n+1],type:r}}}c.register(cs,{capabilities:z.JS,autostart:!0});const ps=new Map([["xml","xml"],["javascript","javascript"],["network","network"],[Xr.ConsoleAPI,"console-api"],["storage","storage"],["appcache","appcache"],["rendering","rendering"],[Xr.CSS,"css"],["security","security"],["deprecation","deprecation"],["worker","worker"],["violation","violation"],["intervention","intervention"],["recommendation","recommendation"],["other","other"]]);var ms=Object.freeze({__proto__:null,ConsoleModel:cs,get Events(){return hs},ConsoleMessage:gs,MessageSourceDisplayName:ps,get FrontendMessageSource(){return Xr},get FrontendMessageType(){return Qr}});class fs extends c{#Mo;#Po;constructor(e){super(e),this.#Mo=new Map,this.#Po=new Map}addBlockedCookie(e,t){const n=e.key(),r=this.#Mo.get(n);this.#Mo.set(n,e),t?this.#Po.set(e,t):this.#Po.delete(e),r&&this.#Po.delete(r)}getCookieToBlockedReasonsMap(){return this.#Po}async getCookies(e){const t=await this.target().networkAgent().invoke_getCookies({urls:e});if(t.getError())return[];return t.cookies.map(F.fromProtocolCookie).concat(Array.from(this.#Mo.values()))}async deleteCookie(e){await this.deleteCookies([e])}async clear(e,t){const n=await this.getCookiesForDomain(e||null);if(t){const e=n.filter((e=>e.matchesSecurityOrigin(t)));await this.deleteCookies(e)}else await this.deleteCookies(n)}async saveCookie(e){let t,n=e.domain();n.startsWith(".")||(n=""),e.expires()&&(t=Math.floor(Date.parse(`${e.expires()}`)/1e3));const r=o.Runtime.experiments.isEnabled("experimentalCookieFeatures"),s={name:e.name(),value:e.value(),url:e.url()||void 0,domain:n,path:e.path(),secure:e.secure(),httpOnly:e.httpOnly(),sameSite:e.sameSite(),expires:t,priority:e.priority(),partitionKey:e.partitionKey(),sourceScheme:r?e.sourceScheme():(i=e.sourceScheme(),"Unset"===i?i:void 0),sourcePort:r?e.sourcePort():void 0};var i;const a=await this.target().networkAgent().invoke_setCookie(s);return!(a.getError()||!a.success)&&a.success}getCookiesForDomain(t){const n=[];const r=this.target().model(jn);return r&&(r.mainFrame&&r.mainFrame.unreachableUrl()&&n.push(r.mainFrame.unreachableUrl()),r.forAllResources((function(r){const s=e.ParsedURL.ParsedURL.fromString(r.documentURL);return!s||t&&s.securityOrigin()!==t||n.push(r.url),!1}))),this.getCookies(n)}async deleteCookies(e){const t=this.target().networkAgent();this.#Mo.clear(),this.#Po.clear(),await Promise.all(e.map((e=>t.invoke_deleteCookies({name:e.name(),url:void 0,domain:e.domain(),path:e.path()}))))}}c.register(fs,{capabilities:z.Network,autostart:!1});var bs=Object.freeze({__proto__:null,CookieModel:fs});class ys extends A{id;self;positionTicks;deoptReason;constructor(e,t,n){super(e.callFrame||{functionName:e.functionName,scriptId:e.scriptId,url:e.url,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber-1},n),this.id=e.id,this.self=(e.hitCount||0)*t,this.positionTicks=e.positionTicks,this.deoptReason=e.deoptReason&&"no reason"!==e.deoptReason?e.deoptReason:null}}var vs=Object.freeze({__proto__:null,CPUProfileNode:ys,CPUProfileDataModel:class extends O{profileStartTime;profileEndTime;timestamps;samples;lines;totalHitCount;profileHead;#Lo;gcNode;programNode;idleNode;#Eo;#Ao;constructor(e,t){super(t);Boolean(e.head)?(this.profileStartTime=1e3*e.startTime,this.profileEndTime=1e3*e.endTime,this.timestamps=e.timestamps,this.compatibilityConversionHeadToNodes(e)):(this.profileStartTime=e.startTime/1e3,this.profileEndTime=e.endTime/1e3,this.timestamps=this.convertTimeDeltas(e)),this.samples=e.samples,this.lines=e.lines,this.totalHitCount=0,this.profileHead=this.translateProfileTree(e.nodes),this.initialize(this.profileHead),this.extractMetaNodes(),this.samples&&(this.sortSamples(),this.normalizeTimestamps(),this.fixMissingSamples())}compatibilityConversionHeadToNodes(e){if(!e.head||e.nodes)return;const t=[];!function e(n){return t.push(n),n.children=n.children.map(e),n.id}(e.head),e.nodes=t,delete e.head}convertTimeDeltas(e){if(!e.timeDeltas)return[];let t=e.startTime;const n=new Array(e.timeDeltas.length);for(let r=0;re+(t.hitCount||0)),0);const r=(this.profileEndTime-this.profileStartTime)/this.totalHitCount,s=Boolean(e.Settings.Settings.instance().moduleSetting("showNativeFunctionsInJSProfile").get()),i=t[0],a=new Map([[i.id,i.id]]);this.#Lo=new Map;const o=new ys(i,r,this.target());if(this.#Lo.set(i.id,o),!i.children)throw new Error("Missing children for root");const l=i.children.map((()=>o)),d=i.children.map((e=>n.get(e)));for(;d.length;){let e=l.pop();const t=d.pop();if(!t||!e)continue;t.children||(t.children=[]);const i=new ys(t,r,this.target());s||!((c=t).callFrame?Boolean(c.callFrame.url)&&c.callFrame.url.startsWith("native "):Boolean(c.url)&&c.url.startsWith("native "))?(e.children.push(i),e=i):e.self+=i.self,a.set(t.id,e.id),l.push.apply(l,t.children.map((()=>e))),d.push.apply(d,t.children.map((e=>n.get(e)))),this.#Lo.set(t.id,i)}var c;return this.samples&&(this.samples=this.samples.map((e=>a.get(e)))),o}sortSamples(){if(!this.timestamps||!this.samples)return;const e=this.timestamps,t=this.samples,n=e.map(((e,t)=>t));n.sort(((t,n)=>e[t]-e[n])),this.timestamps=[],this.samples=[];for(let r=0;r=s));I++){const t=i[I];if(t===p)continue;v=o.get(t);let r=o.get(p);if(v!==l){if(r===l&&m){const e=b[h],t=g-e;y[h-1]+=t,n(m.depth+1,l,e,t,t-y[h]),--h,r=m,p=r.id,m=null}for(;v&&v.depth>r.depth;)u.push(v),v=v.parent;for(;r!==v;){const e=b[h],t=g-e;y[h-1]+=t,n(r.depth,r,e,t,t-y[h]),--h,v&&v.depth===r.depth&&(u.push(v),v=v.parent),r=r.parent}for(;u.length;){const t=u.pop();v=t,e(t.depth,t,g),b[++h]=g,y[h]=0}p=t}else m=r,e(m.depth+1,l,g),b[++h]=g,y[h]=0,p=t}if(g=a[I]||this.profileEndTime,m&&o.get(p)===l){const e=b[h],t=g-e;y[h-1]+=t,n(m.depth+1,v,e,t,t-y[h]),--h,p=m.id}for(let e=o.get(p);e&&e.parent;e=e.parent){const t=b[h],r=g-t;y[h-1]+=r,n(e.depth,e,t,r,r-y[h]),--h}}nodeByIndex(e){return this.samples&&this.#Lo.get(this.samples[e])||null}nodes(){return this.#Lo?[...this.#Lo.values()]:null}}});class Is extends c{#Oo;#No;#jr;#Fo;#Bo;#Do;#Uo;#Ho;#qo;#_o;constructor(t){super(t),this.#Oo=t.emulationAgent(),this.#No=t.deviceOrientationAgent(),this.#jr=t.model(en),this.#Fo=t.model(vn),this.#Fo&&this.#Fo.addEventListener(In.InspectModeWillBeToggled,(()=>{this.updateTouch()}),this);const n=e.Settings.Settings.instance().moduleSetting("javaScriptDisabled");n.addChangeListener((async()=>await this.#Oo.invoke_setScriptExecutionDisabled({value:n.get()}))),n.get()&&this.#Oo.invoke_setScriptExecutionDisabled({value:!0});const r=e.Settings.Settings.instance().moduleSetting("emulation.touch");r.addChangeListener((()=>{const e=r.get();this.overrideEmulateTouch("force"===e)}));const s=e.Settings.Settings.instance().moduleSetting("emulation.idleDetection");s.addChangeListener((async()=>{const e=s.get();if("none"===e)return void await this.clearIdleOverride();const t=JSON.parse(e);await this.setIdleOverride(t)}));const i=e.Settings.Settings.instance().moduleSetting("emulatedCSSMedia"),a=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeatureColorGamut"),o=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersColorScheme"),l=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeatureForcedColors"),d=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersContrast"),c=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersReducedData"),h=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersReducedMotion");this.#Bo=new Map([["type",i.get()],["color-gamut",a.get()],["prefers-color-scheme",o.get()],["forced-colors",l.get()],["prefers-contrast",d.get()],["prefers-reduced-data",c.get()],["prefers-reduced-motion",h.get()]]),i.addChangeListener((()=>{this.#Bo.set("type",i.get()),this.updateCssMedia()})),a.addChangeListener((()=>{this.#Bo.set("color-gamut",a.get()),this.updateCssMedia()})),o.addChangeListener((()=>{this.#Bo.set("prefers-color-scheme",o.get()),this.updateCssMedia()})),l.addChangeListener((()=>{this.#Bo.set("forced-colors",l.get()),this.updateCssMedia()})),d.addChangeListener((()=>{this.#Bo.set("prefers-contrast",d.get()),this.updateCssMedia()})),c.addChangeListener((()=>{this.#Bo.set("prefers-reduced-data",c.get()),this.updateCssMedia()})),h.addChangeListener((()=>{this.#Bo.set("prefers-reduced-motion",h.get()),this.updateCssMedia()})),this.updateCssMedia();const u=e.Settings.Settings.instance().moduleSetting("emulateAutoDarkMode");u.addChangeListener((()=>{const e=u.get();o.setDisabled(e),o.set(e?"dark":""),this.emulateAutoDarkMode(e)})),u.get()&&(o.setDisabled(!0),o.set("dark"),this.emulateAutoDarkMode(!0));const g=e.Settings.Settings.instance().moduleSetting("emulatedVisionDeficiency");g.addChangeListener((()=>this.emulateVisionDeficiency(g.get()))),g.get()&&this.emulateVisionDeficiency(g.get());const p=e.Settings.Settings.instance().moduleSetting("localFontsDisabled");p.addChangeListener((()=>this.setLocalFontsDisabled(p.get()))),p.get()&&this.setLocalFontsDisabled(p.get());const m=e.Settings.Settings.instance().moduleSetting("avifFormatDisabled"),f=e.Settings.Settings.instance().moduleSetting("webpFormatDisabled"),b=()=>{const e=[];m.get()&&e.push("avif"),f.get()&&e.push("webp"),this.setDisabledImageTypes(e)};m.addChangeListener(b),f.addChangeListener(b),(m.get()||f.get())&&b(),this.#Ho=!0,this.#Do=!1,this.#Uo=!1,this.#qo=!1,this.#_o={enabled:!1,configuration:"mobile"}}setTouchEmulationAllowed(e){this.#Ho=e}supportsDeviceEmulation(){return this.target().hasAllCapabilities(z.DeviceEmulation)}async resetPageScaleFactor(){await this.#Oo.invoke_resetPageScaleFactor()}async emulateDevice(e){e?await this.#Oo.invoke_setDeviceMetricsOverride(e):await this.#Oo.invoke_clearDeviceMetricsOverride()}overlayModel(){return this.#Fo}async emulateLocation(e){if(!e||e.error)await Promise.all([this.#Oo.invoke_clearGeolocationOverride(),this.#Oo.invoke_setTimezoneOverride({timezoneId:""}),this.#Oo.invoke_setLocaleOverride({locale:""}),this.#Oo.invoke_setUserAgentOverride({userAgent:ue.instance().currentUserAgent()})]);else{function t(e,t){const n=t.getError();return n?Promise.reject({type:e,message:n}):Promise.resolve()}await Promise.all([this.#Oo.invoke_setGeolocationOverride({latitude:e.latitude,longitude:e.longitude,accuracy:ks.defaultGeoMockAccuracy}).then((e=>t("emulation-set-location",e))),this.#Oo.invoke_setTimezoneOverride({timezoneId:e.timezoneId}).then((e=>t("emulation-set-timezone",e))),this.#Oo.invoke_setLocaleOverride({locale:e.locale}).then((e=>t("emulation-set-locale",e))),this.#Oo.invoke_setUserAgentOverride({userAgent:ue.instance().currentUserAgent(),acceptLanguage:e.locale}).then((e=>t("emulation-set-user-agent",e)))])}}async emulateDeviceOrientation(e){e?await this.#No.invoke_setDeviceOrientationOverride({alpha:e.alpha,beta:e.beta,gamma:e.gamma}):await this.#No.invoke_clearDeviceOrientationOverride()}async setIdleOverride(e){await this.#Oo.invoke_setIdleOverride(e)}async clearIdleOverride(){await this.#Oo.invoke_clearIdleOverride()}async emulateCSSMedia(e,t){await this.#Oo.invoke_setEmulatedMedia({media:e,features:t}),this.#jr&&this.#jr.mediaQueryResultChanged()}async emulateAutoDarkMode(e){e&&(this.#Bo.set("prefers-color-scheme","dark"),await this.updateCssMedia()),await this.#Oo.invoke_setAutoDarkModeOverride({enabled:e||void 0})}async emulateVisionDeficiency(e){await this.#Oo.invoke_setEmulatedVisionDeficiency({type:e})}setLocalFontsDisabled(e){this.#jr&&this.#jr.setLocalFontsEnabled(!e)}setDisabledImageTypes(e){this.#Oo.invoke_setDisabledImageTypes({imageTypes:e})}async setCPUThrottlingRate(e){await this.#Oo.invoke_setCPUThrottlingRate({rate:e})}async setHardwareConcurrency(e){if(e<1)throw new Error("hardwareConcurrency must be a positive value");await this.#Oo.invoke_setHardwareConcurrencyOverride({hardwareConcurrency:e})}async emulateTouch(e,t){this.#Do=e&&this.#Ho,this.#Uo=t&&this.#Ho,await this.updateTouch()}async overrideEmulateTouch(e){this.#qo=e&&this.#Ho,await this.updateTouch()}async updateTouch(){let e={enabled:this.#Do,configuration:this.#Uo?"mobile":"desktop"};this.#qo&&(e={enabled:!0,configuration:"mobile"}),this.#Fo&&this.#Fo.inspectModeEnabled()&&(e={enabled:!1,configuration:"mobile"}),(this.#_o.enabled||e.enabled)&&(this.#_o.enabled&&e.enabled&&this.#_o.configuration===e.configuration||(this.#_o=e,await this.#Oo.invoke_setTouchEmulationEnabled({enabled:e.enabled,maxTouchPoints:1}),await this.#Oo.invoke_setEmitTouchEventsForMouse({enabled:e.enabled,configuration:e.configuration})))}async updateCssMedia(){const e=this.#Bo.get("type")??"",t=[{name:"color-gamut",value:this.#Bo.get("color-gamut")??""},{name:"prefers-color-scheme",value:this.#Bo.get("prefers-color-scheme")??""},{name:"forced-colors",value:this.#Bo.get("forced-colors")??""},{name:"prefers-contrast",value:this.#Bo.get("prefers-contrast")??""},{name:"prefers-reduced-data",value:this.#Bo.get("prefers-reduced-data")??""},{name:"prefers-reduced-motion",value:this.#Bo.get("prefers-reduced-motion")??""}];return this.emulateCSSMedia(e,t)}}class ks{latitude;longitude;timezoneId;locale;error;constructor(e,t,n,r,s){this.latitude=e,this.longitude=t,this.timezoneId=n,this.locale=r,this.error=s}static parseSetting(e){if(e){const[t,n,r,s]=e.split(":"),[i,a]=t.split("@");return new ks(parseFloat(i),parseFloat(a),n,r,Boolean(s))}return new ks(0,0,"","",!1)}static parseUserInput(e,t,n,r){if(!e&&!t)return null;const{valid:s}=ks.latitudeValidator(e),{valid:i}=ks.longitudeValidator(t);if(!s&&!i)return null;const a=s?parseFloat(e):-1,o=i?parseFloat(t):-1;return new ks(a,o,n,r,!1)}static latitudeValidator(e){const t=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&t>=-90&&t<=90,errorMessage:void 0}}static longitudeValidator(e){const t=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&t>=-180&&t<=180,errorMessage:void 0}}static timezoneIdValidator(e){return{valid:""===e||/[a-zA-Z]/.test(e),errorMessage:void 0}}static localeValidator(e){return{valid:""===e||/[a-zA-Z]{2}/.test(e),errorMessage:void 0}}toSetting(){return`${this.latitude}@${this.longitude}:${this.timezoneId}:${this.locale}:${this.error||""}`}static defaultGeoMockAccuracy=150}class Ss{alpha;beta;gamma;constructor(e,t,n){this.alpha=e,this.beta=t,this.gamma=n}static parseSetting(e){if(e){const t=JSON.parse(e);return new Ss(t.alpha,t.beta,t.gamma)}return new Ss(0,0,0)}static parseUserInput(e,t,n){if(!e&&!t&&!n)return null;const{valid:r}=Ss.alphaAngleValidator(e),{valid:s}=Ss.betaAngleValidator(t),{valid:i}=Ss.gammaAngleValidator(n);if(!r&&!s&&!i)return null;const a=r?parseFloat(e):-1,o=s?parseFloat(t):-1,l=i?parseFloat(n):-1;return new Ss(a,o,l)}static angleRangeValidator(e,t){const n=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&n>=t.minimum&&n{this.#Wo=n=>{e(n),t(n)}}:e=>{this.#Wo=e});const n=await e.runtimeAgent().invoke_evaluate({expression:"navigator.hardwareConcurrency",returnByValue:!0,silent:!0,throwOnSideEffect:!0}),r=n.getError();if(r)throw new Error(r);const{result:s,exceptionDetails:i}=n;if(i)throw new Error(i.text);return s.value}modelAdded(e){if(this.#zo!==xs.NoThrottling&&e.setCPUThrottlingRate(this.#zo),void 0!==this.#jo&&e.setHardwareConcurrency(this.#jo),this.#Wo){const e=this.#Wo;this.#Wo=void 0,this.getHardwareConcurrency().then(e)}}modelRemoved(e){}}var Rs,xs;!function(e){e.RateChanged="RateChanged",e.HardwareConcurrencyChanged="HardwareConcurrencyChanged"}(Rs||(Rs={})),function(e){e[e.NoThrottling=1]="NoThrottling",e[e.MidTierMobile=4]="MidTierMobile",e[e.LowEndMobile=6]="LowEndMobile"}(xs||(xs={}));var Ms=Object.freeze({__proto__:null,CPUThrottlingManager:Ts,get Events(){return Rs},throttlingManager:function(){return Ts.instance()},get CPUThrottlingRates(){return xs}});const Ps=new Set(["inherit","initial","unset"]),Ls=/[\x20-\x7E]{4}/,Es=new RegExp(`(?:'(${Ls.source})')|(?:"(${Ls.source})")\\s+(${/[+-]?(?:\d*\.)?\d+(?:[eE]\d+)?/.source})`);const As=/^"(.+)"|'(.+)'$/;function Os(e){return e.split(",").map((e=>e.trim()))}function Ns(e){return e.replaceAll(/(\/\*(?:.|\s)*?\*\/)/g,"")}var Fs=Object.freeze({__proto__:null,parseFontVariationSettings:function(e){if(Ps.has(e.trim())||"normal"===e.trim())return[];const t=[];for(const n of Os(Ns(e))){const e=n.match(Es);e&&t.push({tag:e[1]||e[2],value:parseFloat(e[3])})}return t},parseFontFamily:function(e){if(Ps.has(e.trim()))return[];const t=[];for(const n of Os(Ns(e))){const e=n.match(As);e?t.push(e[1]||e[2]):t.push(n)}return t},splitByComma:Os,stripComments:Ns});const Bs={trustedTypeViolations:"Trusted Type Violations",sinkViolations:"Sink Violations",policyViolations:"Policy Violations",animation:"Animation",canvas:"Canvas",geolocation:"Geolocation",notification:"Notification",parse:"Parse",script:"Script",timer:"Timer",window:"Window",webaudio:"WebAudio",media:"Media",pictureinpicture:"Picture-in-Picture",clipboard:"Clipboard",control:"Control",device:"Device",domMutation:"DOM Mutation",dragDrop:"Drag / drop",keyboard:"Keyboard",load:"Load",mouse:"Mouse",pointer:"Pointer",touch:"Touch",xhr:"XHR",setTimeoutOrIntervalFired:"{PH1} fired",scriptFirstStatement:"Script First Statement",scriptBlockedByContentSecurity:"Script Blocked by Content Security Policy",requestAnimationFrame:"Request Animation Frame",cancelAnimationFrame:"Cancel Animation Frame",animationFrameFired:"Animation Frame Fired",webglErrorFired:"WebGL Error Fired",webglWarningFired:"WebGL Warning Fired",setInnerhtml:"Set `innerHTML`",createCanvasContext:"Create canvas context",createAudiocontext:"Create `AudioContext`",closeAudiocontext:"Close `AudioContext`",resumeAudiocontext:"Resume `AudioContext`",suspendAudiocontext:"Suspend `AudioContext`",webglErrorFiredS:"WebGL Error Fired ({PH1})",scriptBlockedDueToContent:"Script blocked due to Content Security Policy directive: {PH1}",worker:"Worker"},Ds=s.i18n.registerUIStrings("core/sdk/DOMDebuggerModel.ts",Bs),Us=s.i18n.getLocalizedString.bind(void 0,Ds);class Hs extends c{agent;#ba;#Mr;#Vo;#Go;suspended=!1;constructor(t){super(t),this.agent=t.domdebuggerAgent(),this.#ba=t.model(Cr),this.#Mr=t.model(Pn),this.#Mr.addEventListener(wn.DocumentUpdated,this.documentUpdated,this),this.#Mr.addEventListener(wn.NodeRemoved,this.nodeRemoved,this),this.#Vo=[],this.#Go=e.Settings.Settings.instance().createLocalSetting("domBreakpoints",[]),this.#Mr.existingDocument()&&this.documentUpdated()}runtimeModel(){return this.#ba}async suspendModel(){this.suspended=!0}async resumeModel(){this.suspended=!1}async eventListeners(e){if(console.assert(e.runtimeModel()===this.#ba),!e.objectId)return[];const t=await this.agent.invoke_getEventListeners({objectId:e.objectId}),n=[];for(const r of t.listeners||[]){const t=this.#ba.debuggerModel().createRawLocationByScriptId(r.scriptId,r.lineNumber,r.columnNumber);t&&n.push(new js(this,e,r.type,r.useCapture,r.passive,r.once,r.handler?this.#ba.createRemoteObject(r.handler):null,r.originalHandler?this.#ba.createRemoteObject(r.originalHandler):null,t,null))}return n}retrieveDOMBreakpoints(){this.#Mr.requestDocument()}domBreakpoints(){return this.#Vo.slice()}hasDOMBreakpoint(e,t){return this.#Vo.some((n=>n.node===e&&n.type===t))}setDOMBreakpoint(e,t){for(const n of this.#Vo)if(n.node===e&&n.type===t)return this.toggleDOMBreakpoint(n,!0),n;const n=new zs(this,e,t,!0);return this.#Vo.push(n),this.saveDOMBreakpoints(),this.enableDOMBreakpoint(n),this.dispatchEventToListeners(qs.DOMBreakpointAdded,n),n}removeDOMBreakpoint(e,t){this.removeDOMBreakpoints((n=>n.node===e&&n.type===t))}removeAllDOMBreakpoints(){this.removeDOMBreakpoints((e=>!0))}toggleDOMBreakpoint(e,t){t!==e.enabled&&(e.enabled=t,t?this.enableDOMBreakpoint(e):this.disableDOMBreakpoint(e),this.dispatchEventToListeners(qs.DOMBreakpointToggled,e))}enableDOMBreakpoint(e){e.node.id&&(this.agent.invoke_setDOMBreakpoint({nodeId:e.node.id,type:e.type}),e.node.setMarker(_s,!0))}disableDOMBreakpoint(e){e.node.id&&(this.agent.invoke_removeDOMBreakpoint({nodeId:e.node.id,type:e.type}),e.node.setMarker(_s,!!this.nodeHasBreakpoints(e.node)||null))}nodeHasBreakpoints(e){for(const t of this.#Vo)if(t.node===e&&t.enabled)return!0;return!1}resolveDOMBreakpointData(e){const t=e.type,n=this.#Mr.nodeForId(e.nodeId);if(!t||!n)return null;let r=null,s=!1;return"subtree-modified"===t&&(s=e.insertion||!1,r=this.#Mr.nodeForId(e.targetNodeId)),{type:t,node:n,targetNode:r,insertion:s}}currentURL(){const e=this.#Mr.existingDocument();return e?e.documentURL:t.DevToolsPath.EmptyUrlString}async documentUpdated(){if(this.suspended)return;const e=this.#Vo;this.#Vo=[],this.dispatchEventToListeners(qs.DOMBreakpointsRemoved,e);const n=await this.#Mr.requestDocument(),r=n?n.documentURL:t.DevToolsPath.EmptyUrlString;for(const e of this.#Go.get())e.url===r&&this.#Mr.pushNodeByPathToFrontend(e.path).then(s.bind(this,e));function s(e,t){const n=t?this.#Mr.nodeForId(t):null;if(!n)return;const r=new zs(this,n,e.type,e.enabled);this.#Vo.push(r),e.enabled&&this.enableDOMBreakpoint(r),this.dispatchEventToListeners(qs.DOMBreakpointAdded,r)}}removeDOMBreakpoints(e){const t=[],n=[];for(const r of this.#Vo)e(r)?(t.push(r),r.enabled&&(r.enabled=!1,this.disableDOMBreakpoint(r))):n.push(r);t.length&&(this.#Vo=n,this.saveDOMBreakpoints(),this.dispatchEventToListeners(qs.DOMBreakpointsRemoved,t))}nodeRemoved(e){if(this.suspended)return;const{node:t}=e.data,n=t.children()||[];this.removeDOMBreakpoints((e=>e.node===t||-1!==n.indexOf(e.node)))}saveDOMBreakpoints(){const e=this.currentURL(),t=this.#Go.get().filter((t=>t.url!==e));for(const n of this.#Vo)t.push({url:e,path:n.node.path(),type:n.type,enabled:n.enabled});this.#Go.set(t)}}var qs;!function(e){e.DOMBreakpointAdded="DOMBreakpointAdded",e.DOMBreakpointToggled="DOMBreakpointToggled",e.DOMBreakpointsRemoved="DOMBreakpointsRemoved"}(qs||(qs={}));const _s="breakpoint-marker";class zs{domDebuggerModel;node;type;enabled;constructor(e,t,n,r){this.domDebuggerModel=e,this.node=t,this.type=n,this.enabled=r}}class js{#Ko;#$o;#p;#Qo;#Xo;#Jo;#Yo;#Zo;#na;#el;#tl;#nl;constructor(e,n,r,s,i,a,o,l,d,c,h){this.#Ko=e,this.#$o=n,this.#p=r,this.#Qo=s,this.#Xo=i,this.#Jo=a,this.#Yo=o,this.#Zo=l||o,this.#na=d;const u=d.script();this.#el=u?u.contentURL():t.DevToolsPath.EmptyUrlString,this.#tl=c,this.#nl=h||js.Origin.Raw}domDebuggerModel(){return this.#Ko}type(){return this.#p}useCapture(){return this.#Qo}passive(){return this.#Xo}once(){return this.#Jo}handler(){return this.#Yo}location(){return this.#na}sourceURL(){return this.#el}originalHandler(){return this.#Zo}canRemove(){return Boolean(this.#tl)||this.#nl!==js.Origin.FrameworkUser}remove(){if(!this.canRemove())return Promise.resolve(void 0);if(this.#nl!==js.Origin.FrameworkUser){function e(e,t,n){this.removeEventListener(e,t,n),this["on"+e]&&(this["on"+e]=void 0)}return this.#$o.callFunction(e,[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo)]).then((()=>{}))}if(this.#tl){function e(e,t,n,r){this.call(null,e,t,n,r)}return this.#tl.callFunction(e,[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo),Le.toCallArgument(this.#Xo)]).then((()=>{}))}return Promise.resolve(void 0)}canTogglePassive(){return this.#nl!==js.Origin.FrameworkUser}togglePassive(){return this.#$o.callFunction((function(e,t,n,r){this.removeEventListener(e,t,{capture:n}),this.addEventListener(e,t,{capture:n,passive:!r})}),[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo),Le.toCallArgument(this.#Xo)]).then((()=>{}))}origin(){return this.#nl}markAsFramework(){this.#nl=js.Origin.Framework}isScrollBlockingType(){return"touchstart"===this.#p||"touchmove"===this.#p||"mousewheel"===this.#p||"wheel"===this.#p}}!function(e){let t;!function(e){e.Raw="Raw",e.Framework="Framework",e.FrameworkUser="FrameworkUser"}(t=e.Origin||(e.Origin={}))}(js||(js={}));class Ws extends Fr{#p;constructor(e,t,n){super(e,t),this.#p=n}type(){return this.#p}}class Vs extends Fr{instrumentationName;eventName;eventTargetNames;constructor(e,t,n,r,s){super(r,s),this.instrumentationName=e,this.eventName=t,this.eventTargetNames=n}setEnabled(e){if(this.enabled()!==e){super.setEnabled(e);for(const e of K.instance().models(Hs))this.updateOnModel(e)}}updateOnModel(e){if(this.instrumentationName)this.enabled()?e.agent.invoke_setInstrumentationBreakpoint({eventName:this.instrumentationName}):e.agent.invoke_removeInstrumentationBreakpoint({eventName:this.instrumentationName});else for(const t of this.eventTargetNames)this.enabled()?e.agent.invoke_setEventListenerBreakpoint({eventName:this.eventName,targetName:t}):e.agent.invoke_removeEventListenerBreakpoint({eventName:this.eventName,targetName:t})}static listener="listener:";static instrumentation="instrumentation:"}let Gs;class Ks{#rl;#sl;#il;#al;constructor(){this.#rl=e.Settings.Settings.instance().createLocalSetting("xhrBreakpoints",[]),this.#sl=new Map;for(const e of this.#rl.get())this.#sl.set(e.url,e.enabled);this.#il=[],this.#il.push(new Ws(Us(Bs.trustedTypeViolations),Us(Bs.sinkViolations),"trustedtype-sink-violation")),this.#il.push(new Ws(Us(Bs.trustedTypeViolations),Us(Bs.policyViolations),"trustedtype-policy-violation")),this.#al=[],this.createInstrumentationBreakpoints(Us(Bs.animation),["requestAnimationFrame","cancelAnimationFrame","requestAnimationFrame.callback"]),this.createInstrumentationBreakpoints(Us(Bs.canvas),["canvasContextCreated","webglErrorFired","webglWarningFired"]),this.createInstrumentationBreakpoints(Us(Bs.geolocation),["Geolocation.getCurrentPosition","Geolocation.watchPosition"]),this.createInstrumentationBreakpoints(Us(Bs.notification),["Notification.requestPermission"]),this.createInstrumentationBreakpoints(Us(Bs.parse),["Element.setInnerHTML","Document.write"]),this.createInstrumentationBreakpoints(Us(Bs.script),["scriptFirstStatement","scriptBlockedByCSP"]),this.createInstrumentationBreakpoints(Us(Bs.timer),["setTimeout","clearTimeout","setInterval","clearInterval","setTimeout.callback","setInterval.callback"]),this.createInstrumentationBreakpoints(Us(Bs.window),["DOMWindow.close"]),this.createInstrumentationBreakpoints(Us(Bs.webaudio),["audioContextCreated","audioContextClosed","audioContextResumed","audioContextSuspended"]),this.createEventListenerBreakpoints(Us(Bs.media),["play","pause","playing","canplay","canplaythrough","seeking","seeked","timeupdate","ended","ratechange","durationchange","volumechange","loadstart","progress","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","waiting"],["audio","video"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["enterpictureinpicture","leavepictureinpicture"],["video"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["resize"],["PictureInPictureWindow"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["enter"],["documentPictureInPicture"]),this.createEventListenerBreakpoints(Us(Bs.clipboard),["copy","cut","paste","beforecopy","beforecut","beforepaste"],["*"]),this.createEventListenerBreakpoints(Us(Bs.control),["resize","scroll","scrollend","zoom","focus","blur","select","change","submit","reset"],["*"]),this.createEventListenerBreakpoints(Us(Bs.device),["deviceorientation","devicemotion"],["*"]),this.createEventListenerBreakpoints(Us(Bs.domMutation),["DOMActivate","DOMFocusIn","DOMFocusOut","DOMAttrModified","DOMCharacterDataModified","DOMNodeInserted","DOMNodeInsertedIntoDocument","DOMNodeRemoved","DOMNodeRemovedFromDocument","DOMSubtreeModified","DOMContentLoaded"],["*"]),this.createEventListenerBreakpoints(Us(Bs.dragDrop),["drag","dragstart","dragend","dragenter","dragover","dragleave","drop"],["*"]),this.createEventListenerBreakpoints(Us(Bs.keyboard),["keydown","keyup","keypress","input"],["*"]),this.createEventListenerBreakpoints(Us(Bs.load),["load","beforeunload","unload","abort","error","hashchange","popstate","navigate","navigatesuccess","navigateerror","currentchange","navigateto","navigatefrom","finish","dispose"],["*"]),this.createEventListenerBreakpoints(Us(Bs.mouse),["auxclick","click","dblclick","mousedown","mouseup","mouseover","mousemove","mouseout","mouseenter","mouseleave","mousewheel","wheel","contextmenu"],["*"]),this.createEventListenerBreakpoints(Us(Bs.pointer),["pointerover","pointerout","pointerenter","pointerleave","pointerdown","pointerup","pointermove","pointercancel","gotpointercapture","lostpointercapture","pointerrawupdate"],["*"]),this.createEventListenerBreakpoints(Us(Bs.touch),["touchstart","touchmove","touchend","touchcancel"],["*"]),this.createEventListenerBreakpoints(Us(Bs.worker),["message","messageerror"],["*"]),this.createEventListenerBreakpoints(Us(Bs.xhr),["readystatechange","load","loadstart","loadend","abort","error","progress","timeout"],["xmlhttprequest","xmlhttprequestupload"]);for(const[e,t]of[["setTimeout.callback",Us(Bs.setTimeoutOrIntervalFired,{PH1:"setTimeout"})],["setInterval.callback",Us(Bs.setTimeoutOrIntervalFired,{PH1:"setInterval"})],["scriptFirstStatement",Us(Bs.scriptFirstStatement)],["scriptBlockedByCSP",Us(Bs.scriptBlockedByContentSecurity)],["requestAnimationFrame",Us(Bs.requestAnimationFrame)],["cancelAnimationFrame",Us(Bs.cancelAnimationFrame)],["requestAnimationFrame.callback",Us(Bs.animationFrameFired)],["webglErrorFired",Us(Bs.webglErrorFired)],["webglWarningFired",Us(Bs.webglWarningFired)],["Element.setInnerHTML",Us(Bs.setInnerhtml)],["canvasContextCreated",Us(Bs.createCanvasContext)],["Geolocation.getCurrentPosition","getCurrentPosition"],["Geolocation.watchPosition","watchPosition"],["Notification.requestPermission","requestPermission"],["DOMWindow.close","window.close"],["Document.write","document.write"],["audioContextCreated",Us(Bs.createAudiocontext)],["audioContextClosed",Us(Bs.closeAudiocontext)],["audioContextResumed",Us(Bs.resumeAudiocontext)],["audioContextSuspended",Us(Bs.suspendAudiocontext)]]){const n=this.resolveEventListenerBreakpointInternal("instrumentation:"+e);n&&n.setTitle(t)}K.instance().observeModels(Hs,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return Gs&&!t||(Gs=new Ks),Gs}cspViolationBreakpoints(){return this.#il.slice()}createInstrumentationBreakpoints(e,t){for(const n of t)this.#al.push(new Vs(n,"",[],e,n))}createEventListenerBreakpoints(e,t,n){for(const r of t)this.#al.push(new Vs("",r,n,e,r))}resolveEventListenerBreakpointInternal(e,t){const n="instrumentation:",r="listener:";let s="";if(e.startsWith(n))s=e.substring(n.length),e="";else{if(!e.startsWith(r))return null;e=e.substring(r.length)}t=(t||"*").toLowerCase();let i=null;for(const n of this.#al)s&&n.instrumentationName===s&&(i=n),e&&n.eventName===e&&-1!==n.eventTargetNames.indexOf(t)&&(i=n),!i&&e&&n.eventName===e&&-1!==n.eventTargetNames.indexOf("*")&&(i=n);return i}eventListenerBreakpoints(){return this.#al.slice()}resolveEventListenerBreakpointTitle(e){const t=e.eventName;if("instrumentation:webglErrorFired"===t&&e.webglErrorName){let t=e.webglErrorName;return t=t.replace(/^.*(0x[0-9a-f]+).*$/i,"$1"),Us(Bs.webglErrorFiredS,{PH1:t})}if("instrumentation:scriptBlockedByCSP"===t&&e.directiveText)return Us(Bs.scriptBlockedDueToContent,{PH1:e.directiveText});const n=this.resolveEventListenerBreakpointInternal(t,e.targetName);return n?e.targetName?e.targetName+"."+n.title():n.title():""}resolveEventListenerBreakpoint(e){return this.resolveEventListenerBreakpointInternal(e.eventName,e.targetName)}updateCSPViolationBreakpoints(){const e=this.#il.filter((e=>e.enabled())).map((e=>e.type()));for(const t of K.instance().models(Hs))this.updateCSPViolationBreakpointsForModel(t,e)}updateCSPViolationBreakpointsForModel(e,t){e.agent.invoke_setBreakOnCSPViolation({violationTypes:t})}xhrBreakpoints(){return this.#sl}saveXHRBreakpoints(){const e=[];for(const t of this.#sl.keys())e.push({url:t,enabled:this.#sl.get(t)||!1});this.#rl.set(e)}addXHRBreakpoint(e,t){if(this.#sl.set(e,t),t)for(const t of K.instance().models(Hs))t.agent.invoke_setXHRBreakpoint({url:e});this.saveXHRBreakpoints()}removeXHRBreakpoint(e){const t=this.#sl.get(e);if(this.#sl.delete(e),t)for(const t of K.instance().models(Hs))t.agent.invoke_removeXHRBreakpoint({url:e});this.saveXHRBreakpoints()}toggleXHRBreakpoint(e,t){this.#sl.set(e,t);for(const n of K.instance().models(Hs))t?n.agent.invoke_setXHRBreakpoint({url:e}):n.agent.invoke_removeXHRBreakpoint({url:e});this.saveXHRBreakpoints()}modelAdded(e){for(const t of this.#sl.keys())this.#sl.get(t)&&e.agent.invoke_setXHRBreakpoint({url:t});for(const t of this.#al)t.enabled()&&t.updateOnModel(e);const t=this.#il.filter((e=>e.enabled())).map((e=>e.type()));this.updateCSPViolationBreakpointsForModel(e,t)}modelRemoved(e){}}c.register(Hs,{capabilities:z.DOM,autostart:!1});var $s=Object.freeze({__proto__:null,DOMDebuggerModel:Hs,get Events(){return qs},DOMBreakpoint:zs,get EventListener(){return js},CSPViolationBreakpoint:Ws,DOMEventListenerBreakpoint:Vs,DOMDebuggerManager:Ks});const Qs={auctionWorklet:"Ad Auction Worklet",beforeBidderWorkletBiddingStart:"Bidder Bidding Phase Start",beforeBidderWorkletReportingStart:"Bidder Reporting Phase Start",beforeSellerWorkletScoringStart:"Seller Scoring Phase Start",beforeSellerWorkletReportingStart:"Seller Reporting Phase Start"},Xs=s.i18n.registerUIStrings("core/sdk/EventBreakpointsModel.ts",Qs),Js=s.i18n.getLocalizedString.bind(void 0,Xs);class Ys extends c{agent;constructor(e){super(e),this.agent=e.eventBreakpointsAgent()}}class Zs extends Fr{instrumentationName;constructor(e,t){super(t,function(e){switch(e){case"beforeBidderWorkletBiddingStart":return Js(Qs.beforeBidderWorkletBiddingStart);case"beforeBidderWorkletReportingStart":return Js(Qs.beforeBidderWorkletReportingStart);case"beforeSellerWorkletScoringStart":return Js(Qs.beforeSellerWorkletScoringStart);case"beforeSellerWorkletReportingStart":return Js(Qs.beforeSellerWorkletReportingStart)}}(e)),this.instrumentationName=e}setEnabled(e){if(this.enabled()!==e){super.setEnabled(e);for(const e of K.instance().models(Ys))this.updateOnModel(e)}}updateOnModel(e){this.enabled()?e.agent.invoke_setInstrumentationBreakpoint({eventName:this.instrumentationName}):e.agent.invoke_removeInstrumentationBreakpoint({eventName:this.instrumentationName})}static instrumentationPrefix="instrumentation:"}let ei;class ti{#al=[];constructor(){this.createInstrumentationBreakpoints(Js(Qs.auctionWorklet),["beforeBidderWorkletBiddingStart","beforeBidderWorkletReportingStart","beforeSellerWorkletScoringStart","beforeSellerWorkletReportingStart"]),K.instance().observeModels(Ys,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return ei&&!t||(ei=new ti),ei}createInstrumentationBreakpoints(e,t){for(const n of t)this.#al.push(new Zs(n,e))}eventListenerBreakpoints(){return this.#al.slice()}resolveEventListenerBreakpointTitle(e){const t=this.resolveEventListenerBreakpoint(e);return t?t.title():null}resolveEventListenerBreakpoint(e){const t=e.eventName;if(!t.startsWith(Zs.instrumentationPrefix))return null;const n=t.substring(Zs.instrumentationPrefix.length);return this.#al.find((e=>e.instrumentationName===n))||null}modelAdded(e){for(const t of this.#al)t.enabled()&&t.updateOnModel(e)}modelRemoved(e){}}c.register(Ys,{capabilities:z.EventBreakpoints,autostart:!1});var ni=Object.freeze({__proto__:null,EventBreakpointsModel:Ys,EventBreakpointsManager:ti});class ri{#ol;#ll;#dl;#cl;#hl;#ul;#gl;#pl;#ml;#fl;#bl;#yl;#vl=[];constructor(e){this.#ol=e,this.#ll=new Map,this.#dl=new Map,this.#cl=Number(1/0),this.#hl=Number(-1/0),this.#ul=[],this.#gl=[],this.#pl=new Map,this.#ml=new Map,this.#fl=new Map,this.#bl=new Map,this.#yl=new Map}static isTopLevelEvent(e){return vi(e,li)&&"RunTask"===e.name||vi(e,ai)||vi(e,oi)&&"Program"===e.name}static extractId(e){const t=e.scope||"";if(void 0===e.id2)return t&&e.id?`${t}@${e.id}`:e.id;const n=e.id2;if("object"==typeof n&&"global"in n!="local"in n)return void 0!==n.global?`:${t}:${n.global}`:`:${t}:${e.pid}:${n.local}`;console.error(`Unexpected id2 field at ${e.ts/1e3}, one and only one of 'local' and 'global' should be present.`)}static browserMainThread(t){const n=t.sortedProcesses();if(!n.length)return null;const r="CrBrowserMain",s=[],i=[];for(const e of n)e.name().toLowerCase().endsWith("browser")&&s.push(e),i.push(...e.sortedThreads().filter((e=>e.name()===r)));if(1===i.length)return i[0];if(1===s.length)return s[0].threadByName(r);const a=t.devToolsMetadataEvents().filter((e=>"TracingStartedInBrowser"===e.name));return 1===a.length?a[0].thread:(e.Console.Console.instance().error("Failed to find browser main thread in trace, some timeline features may be unavailable"),null)}allRawEvents(){return this.#vl}devToolsMetadataEvents(){return this.#ul}addEvents(e){for(let t=0;te.#kl!==t.#kl?e.#kl-t.#kl:e.name().localeCompare(t.name())))}setName(e){this.#u=e}name(){return this.#u}id(){return this.idInternal}setSortIndex(e){this.#kl=e}getModel(){return this.model}}class fi extends mi{threads;#Sl;constructor(e,t){super(e,t),this.threads=new Map,this.#Sl=new Map}threadById(e){let t=this.threads.get(e);return t||(t=new bi(this,e),this.threads.set(e,t)),t}threadByName(e){return this.#Sl.get(e)||null}setThreadByName(e,t){this.#Sl.set(e,t)}addEvent(e){return this.threadById(e.tid).addEvent(e)}sortedThreads(){return mi.sort([...this.threads.values()])}}class bi extends mi{#wl;#Cl;#Tl;#Rl;constructor(e,t){super(e.getModel(),t),this.#wl=e,this.#Cl=[],this.#Tl=[],this.#Rl=null}#xl(e,t){return e.phase===t}tracingComplete(){this.#Tl.sort(di.compareStartTime),this.#Cl.sort(di.compareStartTime);const e=[],t=new Set;for(let n=0;n!t.has(n)))}addEvent(e){const t="O"===e.ph?ui.fromPayload(e,this):hi.fromPayload(e,this);if(ri.isTopLevelEvent(t)){const e=this.#Rl;if(e&&(e.endTime||0)>t.startTime)return null;this.#Rl=t}return this.#Cl.push(t),t}addAsyncEvent(e){this.#Tl.push(e)}setName(e){super.setName(e),this.#wl.setThreadByName(e,this)}process(){return this.#wl}events(){return this.#Cl}asyncEvents(){return this.#Tl}removeEventsByName(e){const t=[];return this.#Cl=this.#Cl.filter((n=>!!n&&(n.name!==e||(t.push(n),!1)))),t}}const yi=new Map;function vi(e,t){if(e instanceof di)return e.hasCategory(t);let n=yi.get(e.cat);return n||(n=new Set(e.cat.split(",")||[])),n.has(t)}var Ii=Object.freeze({__proto__:null,TracingModel:ri,eventPhasesOfInterestForTraceBounds:si,MetadataEvent:ii,LegacyTopLevelEventCategory:ai,DevToolsMetadataEventCategory:oi,DevToolsTimelineEventCategory:li,eventHasPayload:function(e){return"rawPayload"in e},Event:di,ConstructedEvent:ci,PayloadEvent:hi,ObjectSnapshot:ui,AsyncEvent:gi,Process:fi,Thread:bi,timesForEventInMilliseconds:function(e){if(e instanceof di)return{startTime:l.Types.Timing.MilliSeconds(e.startTime),endTime:e.endTime?l.Types.Timing.MilliSeconds(e.endTime):void 0,duration:l.Types.Timing.MilliSeconds(e.duration||0),selfTime:l.Types.Timing.MilliSeconds(e.selfTime)};const t=e.dur?l.Helpers.Timing.microSecondsToMilliseconds(e.dur):l.Types.Timing.MilliSeconds(0);return{startTime:l.Helpers.Timing.microSecondsToMilliseconds(e.ts),endTime:l.Helpers.Timing.microSecondsToMilliseconds(l.Types.Timing.MicroSeconds(e.ts+(e.dur||0))),duration:e.dur?l.Helpers.Timing.microSecondsToMilliseconds(e.dur):l.Types.Timing.MilliSeconds(0),selfTime:t}},eventHasCategory:vi,phaseForEvent:function(e){return e instanceof di?e.phase:e.ph},threadIDForEvent:function(e){return e instanceof di?e.thread.idInternal:e.tid},eventIsFromNewEngine:function(e){return null!==e&&!(e instanceof di)}});const ki="disabled-by-default-devtools.screenshot",Si={Screenshot:"Screenshot"};class wi{#Ml;timestamp;index;#Pl;#Ll;constructor(e,t,n){this.#Ml=e,this.timestamp=t,this.index=n,this.#Ll=null,this.#Pl=null}static fromSnapshot(e,t,n){const r=new wi(e,t.startTime,n);return r.#Pl=t,r}static fromTraceEvent(e,t,n){const r=l.Helpers.Timing.microSecondsToMilliseconds(t.ts),s=new wi(e,r,n);return s.#Ll=t,s}model(){return this.#Ml}imageDataPromise(){return this.#Ll?Promise.resolve(this.#Ll.args.snapshot):this.#Pl?Promise.resolve(this.#Pl.getSnapshot()):Promise.resolve(null)}}var Ci=Object.freeze({__proto__:null,FilmStripModel:class{#Ve;#El;#Al;constructor(e,t){this.#Ve=[],this.#El=0,this.#Al=0,this.reset(e,t)}hasFrames(){return this.#Ve.length>0}reset(e,t){this.#El=t||e.minimumRecordTime(),this.#Al=e.maximumRecordTime()-this.#El,this.#Ve=[];const n=ri.browserMainThread(e);if(!n)return;const r=n.events();for(let e=0;et.timestampe.update()))),await new Promise((e=>window.setTimeout(e,Pi)))}}var Mi;(Mi||(Mi={})).MemoryChanged="MemoryChanged";const Pi=2e3;class Li{#E;modelsInternal;#Bl;#Dl;constructor(e){this.#E=e,this.modelsInternal=new Set,this.#Bl=0;const t=12e4/Pi;this.#Dl=new Ei(t)}id(){return this.#E}models(){return this.modelsInternal}runtimeModel(){return this.modelsInternal.values().next().value||null}heapProfilerModel(){const e=this.runtimeModel();return e&&e.heapProfilerModel()}async update(){const e=this.runtimeModel(),t=e&&await e.heapUsage();t&&(this.#Bl=t.usedSize,this.#Dl.add(this.#Bl),xi.instance().dispatchEventToListeners(Mi.MemoryChanged,this))}samplesCount(){return this.#Dl.count()}usedHeapSize(){return this.#Bl}usedHeapSizeGrowRate(){return this.#Dl.fitSlope()}isMainThread(){const e=this.runtimeModel();return!!e&&"main"===e.target().id()}}class Ei{#Ul;#Hl;#Kr;#ql;#_l;#zl;#jl;#Wl;#Vl;constructor(e){this.#Ul=0|e,this.reset()}reset(){this.#Hl=Date.now(),this.#Kr=0,this.#ql=[],this.#_l=[],this.#zl=0,this.#jl=0,this.#Wl=0,this.#Vl=0}count(){return this.#ql.length}add(e,t){const n="number"==typeof t?t:Date.now()-this.#Hl,r=e;if(this.#ql.length===this.#Ul){const e=this.#ql[this.#Kr],t=this.#_l[this.#Kr];this.#zl-=e,this.#jl-=t,this.#Wl-=e*e,this.#Vl-=e*t}this.#zl+=n,this.#jl+=r,this.#Wl+=n*n,this.#Vl+=n*r,this.#ql[this.#Kr]=n,this.#_l[this.#Kr]=r,this.#Kr=(this.#Kr+1)%this.#Ul}fitSlope(){const e=this.count();return e<2?0:(this.#Vl-this.#zl*this.#jl/e)/(this.#Wl-this.#zl*this.#zl/e)}}var Ai=Object.freeze({__proto__:null,IsolateManager:xi,get Events(){return Mi},MemoryTrendWindowMs:12e4,Isolate:Li,MemoryTrend:Ei});class Oi extends c{#Gl=!1;#ma=!1;constructor(e){super(e),this.ensureEnabled()}async ensureEnabled(){if(this.#ma)return;this.#ma=!0,this.target().registerAuditsDispatcher(this);const e=this.target().auditsAgent();await e.invoke_enable()}issueAdded(e){this.dispatchEventToListeners("IssueAdded",{issuesModel:this,inspectorIssue:e.issue})}dispose(){super.dispose(),this.#Gl=!0}getTargetIfNotDisposed(){return this.#Gl?null:this.target()}}c.register(Oi,{capabilities:z.Audits,autostart:!0});var Ni,Fi=Object.freeze({__proto__:null,IssuesModel:Oi});!function(e){let t;!function(e){e.NonFastScrollable="NonFastScrollable",e.TouchEventHandler="TouchEventHandler",e.WheelEventHandler="WheelEventHandler",e.RepaintsOnScroll="RepaintsOnScroll",e.MainThreadScrollingReason="MainThreadScrollingReason"}(t=e.ScrollRectType||(e.ScrollRectType={}))}(Ni||(Ni={}));var Bi=Object.freeze({__proto__:null,get Layer(){return Ni},StickyPositionConstraint:class{#Kl;#$l;#Ql;#Xl;constructor(e,t){this.#Kl=t.stickyBoxRect,this.#$l=t.containingBlockRect,this.#Ql=null,e&&t.nearestLayerShiftingStickyBox&&(this.#Ql=e.layerById(t.nearestLayerShiftingStickyBox)),this.#Xl=null,e&&t.nearestLayerShiftingContainingBlock&&(this.#Xl=e.layerById(t.nearestLayerShiftingContainingBlock))}stickyBoxRect(){return this.#Kl}containingBlockRect(){return this.#$l}nearestLayerShiftingStickyBox(){return this.#Ql}nearestLayerShiftingContainingBlock(){return this.#Xl}},LayerTreeBase:class{#e;#Mr;layersById;#Jl;#Yl;#Zl;#ed;constructor(e){this.#e=e,this.#Mr=e?e.model(Pn):null,this.layersById=new Map,this.#Jl=null,this.#Yl=null,this.#Zl=new Map}target(){return this.#e}root(){return this.#Jl}setRoot(e){this.#Jl=e}contentRoot(){return this.#Yl}setContentRoot(e){this.#Yl=e}forEachLayer(e,t){return!(!t&&!(t=this.root()))&&(e(t)||t.children().some(this.forEachLayer.bind(this,e)))}layerById(e){return this.layersById.get(e)||null}async resolveBackendNodeIds(e){if(!e.size||!this.#Mr)return;const t=await this.#Mr.pushNodesByBackendIdsToFrontend(e);if(t)for(const e of t.keys())this.#Zl.set(e,t.get(e)||null)}backendNodeIdToNode(){return this.#Zl}setViewportSize(e){this.#ed=e}viewportSize(){return this.#ed}nodeForId(e){return this.#Mr?this.#Mr.nodeForId(e):null}}});class Di{id;url;startTime;loadTime;contentLoadTime;mainRequest;constructor(e){this.id=++Di.lastIdentifier,this.url=e.url(),this.startTime=e.startTime,this.mainRequest=e}static forRequest(e){return Ui.get(e)||null}bindRequest(e){Ui.set(e,this)}static lastIdentifier=0}const Ui=new WeakMap;var Hi=Object.freeze({__proto__:null,PageLoad:Di});class qi extends c{layerTreeAgent;constructor(e){super(e),this.layerTreeAgent=e.layerTreeAgent()}async loadSnapshotFromFragments(e){const{snapshotId:t}=await this.layerTreeAgent.invoke_loadSnapshot({tiles:e});return t?new _i(this,t):null}loadSnapshot(e){const t={x:0,y:0,picture:e};return this.loadSnapshotFromFragments([t])}async makeSnapshot(e){const{snapshotId:t}=await this.layerTreeAgent.invoke_makeSnapshot({layerId:e});return t?new _i(this,t):null}}class _i{#td;#nd;#rd;constructor(e,t){this.#td=e,this.#nd=t,this.#rd=1}release(){console.assert(this.#rd>0,"release is already called on the object"),--this.#rd||this.#td.layerTreeAgent.invoke_releaseSnapshot({snapshotId:this.#nd})}addReference(){++this.#rd,console.assert(this.#rd>0,"Referencing a dead object")}async replay(e,t,n){return(await this.#td.layerTreeAgent.invoke_replaySnapshot({snapshotId:this.#nd,fromStep:t,toStep:n,scale:e||1})).dataURL}async profile(e){return(await this.#td.layerTreeAgent.invoke_profileSnapshot({snapshotId:this.#nd,minRepeatCount:5,minDuration:1,clipRect:e||void 0})).timings}async commandLog(){const e=await this.#td.layerTreeAgent.invoke_snapshotCommandLog({snapshotId:this.#nd});return e.commandLog?e.commandLog.map(((e,t)=>new zi(e,t))):null}}class zi{method;params;commandIndex;constructor(e,t){this.method=e.method,this.params=e.params,this.commandIndex=t}}c.register(qi,{capabilities:z.DOM,autostart:!1});var ji=Object.freeze({__proto__:null,PaintProfilerModel:qi,PaintProfilerSnapshot:_i,PaintProfilerLogItem:zi});class Wi extends c{#Ts;#sd;#id;constructor(e){super(e),this.#Ts=e.performanceAgent(),this.#sd=new Map([["TaskDuration","CumulativeTime"],["ScriptDuration","CumulativeTime"],["LayoutDuration","CumulativeTime"],["RecalcStyleDuration","CumulativeTime"],["LayoutCount","CumulativeCount"],["RecalcStyleCount","CumulativeCount"]]),this.#id=new Map}enable(){return this.#Ts.invoke_enable({})}disable(){return this.#Ts.invoke_disable()}async requestMetrics(){const e=await this.#Ts.invoke_getMetrics()||[],n=new Map,r=performance.now();for(const s of e.metrics){let e,i=this.#id.get(s.name);switch(i||(i={lastValue:void 0,lastTimestamp:void 0},this.#id.set(s.name,i)),this.#sd.get(s.name)){case"CumulativeTime":e=i.lastTimestamp&&i.lastValue?t.NumberUtilities.clamp(1e3*(s.value-i.lastValue)/(r-i.lastTimestamp),0,1):0,i.lastValue=s.value,i.lastTimestamp=r;break;case"CumulativeCount":e=i.lastTimestamp&&i.lastValue?Math.max(0,1e3*(s.value-i.lastValue)/(r-i.lastTimestamp)):0,i.lastValue=s.value,i.lastTimestamp=r;break;default:e=s.value}n.set(s.name,e)}return{metrics:n,timestamp:r}}}c.register(Wi,{capabilities:z.DOM,autostart:!1});var Vi,Gi=Object.freeze({__proto__:null,PerformanceMetricsModel:Wi});class Ki extends c{agent;loaderIds=[];targetJustAttached=!0;lastPrimaryPageModel=null;documents=new Map;getFeatureFlagsPromise;constructor(e){super(e),e.registerPreloadDispatcher(new $i(this)),this.agent=e.preloadAgent(),this.agent.invoke_enable(),this.getFeatureFlagsPromise=this.getFeatureFlags();const t=e.targetInfo();void 0!==t&&"prerender"===t.subtype&&(this.lastPrimaryPageModel=K.instance().primaryPageTarget()?.model(Ki)||null),K.instance().addModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this)}dispose(){super.dispose(),K.instance().removeModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),this.agent.invoke_disable()}ensureDocumentPreloadingData(e){void 0===this.documents.get(e)&&this.documents.set(e,new Qi)}currentLoaderId(){if(this.targetJustAttached)return null;if(0===this.loaderIds.length)throw new Error("unreachable");return this.loaderIds[this.loaderIds.length-1]}currentDocument(){const e=this.currentLoaderId();return null===e?null:this.documents.get(e)||null}getRuleSetById(e){return this.currentDocument()?.ruleSets.getById(e)||null}getAllRuleSets(){return this.currentDocument()?.ruleSets.getAll()||[]}getPreloadingAttemptById(e){const t=this.currentDocument();return null===t?null:t.preloadingAttempts.getById(e,t.sources)||null}getPreloadingAttempts(e){const t=this.currentDocument();return null===t?[]:t.preloadingAttempts.getAll(e,t.sources)}getPreloadingAttemptsOfPreviousPage(){if(this.loaderIds.length<=1)return[];const e=this.documents.get(this.loaderIds[this.loaderIds.length-2]);return void 0===e?[]:e.preloadingAttempts.getAll(null,e.sources)}onPrimaryPageChanged(e){const{frame:t,type:n}=e.data;if(null===this.lastPrimaryPageModel&&"Activation"===n)return;if(null!==this.lastPrimaryPageModel&&"Activation"!==n)return;if(null!==this.lastPrimaryPageModel&&"Activation"===n){this.loaderIds=this.lastPrimaryPageModel.loaderIds;for(const[e,t]of this.lastPrimaryPageModel.documents.entries())this.ensureDocumentPreloadingData(e),this.documents.get(e)?.mergePrevious(t)}this.lastPrimaryPageModel=null;const r=t.loaderId;this.loaderIds.push(r),this.loaderIds=this.loaderIds.slice(-2),this.ensureDocumentPreloadingData(r);for(const e of this.documents.keys())this.loaderIds.includes(e)||this.documents.delete(e);this.dispatchEventToListeners(Vi.ModelUpdated)}onRuleSetUpdated(e){const t=e.ruleSet,n=t.loaderId;null===this.currentLoaderId()&&(this.loaderIds=[n],this.targetJustAttached=!1),this.ensureDocumentPreloadingData(n),this.documents.get(n)?.ruleSets.upsert(t),this.dispatchEventToListeners(Vi.ModelUpdated)}onRuleSetRemoved(e){const t=e.id;for(const e of this.documents.values())e.ruleSets.delete(t);this.dispatchEventToListeners(Vi.ModelUpdated)}onPreloadingAttemptSourcesUpdated(e){const t=e.loaderId;this.ensureDocumentPreloadingData(t);const n=this.documents.get(t);void 0!==n&&(n.sources.update(e.preloadingAttemptSources),n.preloadingAttempts.maybeRegisterNotTriggered(n.sources),this.dispatchEventToListeners(Vi.ModelUpdated))}onPrefetchStatusUpdated(e){const t=e.key.loaderId;this.ensureDocumentPreloadingData(t);const n={action:"Prefetch",key:e.key,status:Ji(e.status),prefetchStatus:e.prefetchStatus||null};this.documents.get(t)?.preloadingAttempts.upsert(n),this.dispatchEventToListeners(Vi.ModelUpdated)}onPrerenderStatusUpdated(e){const t=e.key.loaderId;this.ensureDocumentPreloadingData(t);const n={action:"Prerender",key:e.key,status:Ji(e.status),prerenderStatus:e.prerenderStatus||null};this.documents.get(t)?.preloadingAttempts.upsert(n),this.dispatchEventToListeners(Vi.ModelUpdated)}async getFeatureFlags(){const e=this.target().systemInfo().invoke_getFeatureState({featureState:"PreloadingHoldback"}),t=this.target().systemInfo().invoke_getFeatureState({featureState:"PrerenderHoldback"});return{preloadingHoldback:(await e).featureEnabled,prerender2Holdback:(await t).featureEnabled}}async onPreloadEnabledStateUpdated(e){const t=await this.getFeatureFlagsPromise,n={featureFlagPreloadingHoldback:t.preloadingHoldback,featureFlagPrerender2Holdback:t.prerender2Holdback,...e};this.dispatchEventToListeners(Vi.WarningsUpdated,n)}}c.register(Ki,{capabilities:z.DOM,autostart:!1}),function(e){e.ModelUpdated="ModelUpdated",e.WarningsUpdated="WarningsUpdated"}(Vi||(Vi={}));class $i{model;constructor(e){this.model=e}ruleSetUpdated(e){this.model.onRuleSetUpdated(e)}ruleSetRemoved(e){this.model.onRuleSetRemoved(e)}preloadingAttemptSourcesUpdated(e){this.model.onPreloadingAttemptSourcesUpdated(e)}prefetchStatusUpdated(e){this.model.onPrefetchStatusUpdated(e)}prerenderAttemptCompleted(e){}prerenderStatusUpdated(e){this.model.onPrerenderStatusUpdated(e)}preloadEnabledStateUpdated(e){this.model.onPreloadEnabledStateUpdated(e)}}class Qi{ruleSets=new Xi;preloadingAttempts=new Zi;sources=new ea;mergePrevious(e){if(!this.ruleSets.isEmpty()||!this.sources.isEmpty())throw new Error("unreachable");this.ruleSets=e.ruleSets,this.preloadingAttempts.mergePrevious(e.preloadingAttempts),this.sources=e.sources}}class Xi{map=new Map;isEmpty(){return 0===this.map.size}getById(e){return this.map.get(e)||null}getAll(){return Array.from(this.map.entries()).map((([e,t])=>({id:e,value:t})))}upsert(e){this.map.set(e.id,e)}delete(e){this.map.delete(e)}}function Ji(e){switch(e){case"Pending":return"Pending";case"Running":return"Running";case"Ready":return"Ready";case"Success":return"Success";case"Failure":return"Failure";case"NotSupported":return"NotSupported"}throw new Error("unreachable")}function Yi(e){let t,n;switch(e.action){case"Prefetch":t="Prefetch";break;case"Prerender":t="Prerender"}switch(e.targetHint){case void 0:n="undefined";break;case"Blank":n="Blank";break;case"Self":n="Self"}return`${e.loaderId}:${t}:${e.url}:${n}`}class Zi{map=new Map;enrich(e,t){let n=[],r=[];return null!==t&&(n=t.ruleSetIds,r=t.nodeIds),{...e,ruleSetIds:n,nodeIds:r}}getById(e,t){const n=this.map.get(e)||null;return null===n?null:this.enrich(n,t.getById(e))}getAll(e,t){return[...this.map.entries()].map((([e,n])=>({id:e,value:this.enrich(n,t.getById(e))}))).filter((({value:t})=>!e||t.ruleSetIds.includes(e)))}upsert(e){const t=Yi(e.key);this.map.set(t,e)}maybeRegisterNotTriggered(e){for(const[t,{key:n}]of e.entries()){if(void 0!==this.map.get(t))continue;let e;switch(n.action){case"Prefetch":e={action:"Prefetch",key:n,status:"NotTriggered",prefetchStatus:null};break;case"Prerender":e={action:"Prerender",key:n,status:"NotTriggered",prerenderStatus:null}}this.map.set(t,e)}}mergePrevious(e){for(const[t,n]of this.map.entries())e.map.set(t,n);this.map=e.map}}class ea{map=new Map;entries(){return this.map.entries()}isEmpty(){return 0===this.map.size}getById(e){return this.map.get(e)||null}update(e){this.map=new Map(e.map((e=>[Yi(e.key),e])))}}var ta=Object.freeze({__proto__:null,PreloadingModel:Ki,get Events(){return Vi}});class na extends c{#Ts;#ad;#od;constructor(e){super(e),this.#Ts=e.pageAgent(),this.#ad=null,this.#od=null,e.registerPageDispatcher(this)}startScreencast(e,t,n,r,s,i,a){this.#ad=i,this.#od=a,this.#Ts.invoke_startScreencast({format:e,quality:t,maxWidth:n,maxHeight:r,everyNthFrame:s})}stopScreencast(){this.#ad=null,this.#od=null,this.#Ts.invoke_stopScreencast()}async captureScreenshot(e,t,n,r){const s={format:e,quality:t,fromSurface:!0};switch(n){case"fromClip":s.captureBeyondViewport=!0,s.clip=r;break;case"fullpage":s.captureBeyondViewport=!0;break;case"fromViewport":s.captureBeyondViewport=!1;break;default:throw new Error("Unexpected or unspecified screnshotMode")}await vn.muteHighlight();const i=await this.#Ts.invoke_captureScreenshot(s);return await vn.unmuteHighlight(),i.data}async fetchLayoutMetrics(){const e=await this.#Ts.invoke_getLayoutMetrics();return e.getError()?null:{viewportX:e.cssVisualViewport.pageX,viewportY:e.cssVisualViewport.pageY,viewportScale:e.cssVisualViewport.scale,contentWidth:e.cssContentSize.width,contentHeight:e.cssContentSize.height}}screencastFrame({data:e,metadata:t,sessionId:n}){this.#Ts.invoke_screencastFrameAck({sessionId:n}),this.#ad&&this.#ad.call(null,e,t)}screencastVisibilityChanged({visible:e}){this.#od&&this.#od.call(null,e)}backForwardCacheNotUsed(e){}domContentEventFired(e){}loadEventFired(e){}lifecycleEvent(e){}navigatedWithinDocument(e){}frameAttached(e){}frameNavigated(e){}documentOpened(e){}frameDetached(e){}frameStartedLoading(e){}frameStoppedLoading(e){}frameRequestedNavigation(e){}frameScheduledNavigation(e){}frameClearedScheduledNavigation(e){}frameResized(){}javascriptDialogOpening(e){}javascriptDialogClosed(e){}interstitialShown(){}interstitialHidden(){}windowOpen(e){}fileChooserOpened(e){}compilationCacheProduced(e){}downloadWillBegin(e){}downloadProgress(){}prerenderAttemptCompleted(e){}prefetchStatusUpdated(e){}prerenderStatusUpdated(e){}}c.register(na,{capabilities:z.ScreenCapture,autostart:!1});var ra=Object.freeze({__proto__:null,ScreenCaptureModel:na});class sa extends c{enabled=!1;storageAgent;storageKeyManager;bucketsById=new Map;trackedStorageKeys=new Set;constructor(e){super(e),e.registerStorageDispatcher(this),this.storageAgent=e.storageAgent(),this.storageKeyManager=e.model(qn)}getBuckets(){return new Set(this.bucketsById.values())}getBucketsForStorageKey(e){const t=[...this.bucketsById.values()];return new Set(t.filter((({bucket:t})=>t.storageKey===e)))}getDefaultBucketForStorageKey(e){return[...this.bucketsById.values()].find((({bucket:t})=>t.storageKey===e&&void 0===t.name))??null}getBucketById(e){return this.bucketsById.get(e)??null}getBucketByName(e,t){if(!t)return this.getDefaultBucketForStorageKey(e);return[...this.bucketsById.values()].find((({bucket:n})=>n.storageKey===e&&n.name===t))??null}deleteBucket(e){this.storageAgent.invoke_deleteStorageBucket({bucket:e})}enable(){if(!this.enabled){if(this.storageKeyManager){this.storageKeyManager.addEventListener(Un.StorageKeyAdded,this.storageKeyAdded,this),this.storageKeyManager.addEventListener(Un.StorageKeyRemoved,this.storageKeyRemoved,this);for(const e of this.storageKeyManager.storageKeys())this.addStorageKey(e)}this.enabled=!0}}storageKeyAdded(e){this.addStorageKey(e.data)}storageKeyRemoved(e){this.removeStorageKey(e.data)}addStorageKey(e){if(this.trackedStorageKeys.has(e))throw new Error("Can't call addStorageKey for a storage key if it has already been added.");this.trackedStorageKeys.add(e),this.storageAgent.invoke_setStorageBucketTracking({storageKey:e,enable:!0})}removeStorageKey(e){if(!this.trackedStorageKeys.has(e))throw new Error("Can't call removeStorageKey for a storage key if it hasn't already been added.");const t=this.getBucketsForStorageKey(e);for(const e of t)this.bucketRemoved(e);this.trackedStorageKeys.delete(e),this.storageAgent.invoke_setStorageBucketTracking({storageKey:e,enable:!1})}bucketAdded(e){this.bucketsById.set(e.id,e),this.dispatchEventToListeners("BucketAdded",{model:this,bucketInfo:e})}bucketRemoved(e){this.bucketsById.delete(e.id),this.dispatchEventToListeners("BucketRemoved",{model:this,bucketInfo:e})}bucketChanged(e){this.dispatchEventToListeners("BucketChanged",{model:this,bucketInfo:e})}bucketInfosAreEqual(e,t){return e.bucket.storageKey===t.bucket.storageKey&&e.id===t.id&&e.bucket.name===t.bucket.name&&e.expiration===t.expiration&&e.quota===t.quota&&e.persistent===t.persistent&&e.durability===t.durability}storageBucketCreatedOrUpdated({bucketInfo:e}){const t=this.getBucketById(e.id);t?this.bucketInfosAreEqual(t,e)||this.bucketChanged(e):this.bucketAdded(e)}storageBucketDeleted({bucketId:e}){const t=this.getBucketById(e);if(!t)throw new Error(`Received an event that Storage Bucket '${e}' was deleted, but it wasn't in the StorageBucketsModel.`);this.bucketRemoved(t)}interestGroupAccessed(e){}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}cacheStorageListUpdated(e){}cacheStorageContentUpdated(e){}sharedStorageAccessed(e){}}c.register(sa,{capabilities:z.Storage,autostart:!1});var ia=Object.freeze({__proto__:null,StorageBucketsModel:sa});const aa={serviceworkercacheagentError:"`ServiceWorkerCacheAgent` error deleting cache entry {PH1} in cache: {PH2}"},oa=s.i18n.registerUIStrings("core/sdk/ServiceWorkerCacheModel.ts",aa),la=s.i18n.getLocalizedString.bind(void 0,oa);class da extends c{cacheAgent;#ld;#dd;#cd=new Map;#hd=new Set;#ud=new Set;#gd=new e.Throttler.Throttler(2e3);#ma=!1;#pd=!1;constructor(e){super(e),e.registerStorageDispatcher(this),this.cacheAgent=e.cacheStorageAgent(),this.#ld=e.storageAgent(),this.#dd=e.model(sa)}enable(){if(!this.#ma){this.#dd.addEventListener("BucketAdded",this.storageBucketAdded,this),this.#dd.addEventListener("BucketRemoved",this.storageBucketRemoved,this);for(const e of this.#dd.getBuckets())this.addStorageBucket(e.bucket);this.#ma=!0}}clearForStorageKey(e){for(const[t,n]of this.#cd.entries())n.storageKey===e&&(this.#cd.delete(t),this.cacheRemoved(n));for(const t of this.#dd.getBucketsForStorageKey(e))this.loadCacheNames(t.bucket)}refreshCacheNames(){for(const e of this.#cd.values())this.cacheRemoved(e);this.#cd.clear();const e=this.#dd.getBuckets();for(const t of e)this.loadCacheNames(t.bucket)}async deleteCache(e){const t=await this.cacheAgent.invoke_deleteCache({cacheId:e.cacheId});t.getError()?console.error(`ServiceWorkerCacheAgent error deleting cache ${e.toString()}: ${t.getError()}`):(this.#cd.delete(e.cacheId),this.cacheRemoved(e))}async deleteCacheEntry(t,n){const r=await this.cacheAgent.invoke_deleteEntry({cacheId:t.cacheId,request:n});r.getError()&&e.Console.Console.instance().error(la(aa.serviceworkercacheagentError,{PH1:t.toString(),PH2:String(r.getError())}))}loadCacheData(e,t,n,r,s){this.requestEntries(e,t,n,r,s)}loadAllCacheData(e,t,n){this.requestAllEntries(e,t,n)}caches(){const e=new Array;for(const t of this.#cd.values())e.push(t);return e}dispose(){for(const e of this.#cd.values())this.cacheRemoved(e);this.#cd.clear(),this.#ma&&(this.#dd.removeEventListener("BucketAdded",this.storageBucketAdded,this),this.#dd.removeEventListener("BucketRemoved",this.storageBucketRemoved,this))}addStorageBucket(e){this.loadCacheNames(e),this.#hd.has(e.storageKey)||(this.#hd.add(e.storageKey),this.#ld.invoke_trackCacheStorageForStorageKey({storageKey:e.storageKey}))}removeStorageBucket(e){let t=0;for(const[n,r]of this.#cd.entries())e.storageKey===r.storageKey&&t++,r.inBucket(e)&&(t--,this.#cd.delete(n),this.cacheRemoved(r));0===t&&(this.#hd.delete(e.storageKey),this.#ld.invoke_untrackCacheStorageForStorageKey({storageKey:e.storageKey}))}async loadCacheNames(e){const t=await this.cacheAgent.invoke_requestCacheNames({storageBucket:e});t.getError()||this.updateCacheNames(e,t.caches)}updateCacheNames(e,t){const n=new Set,r=new Map,s=new Map;for(const e of t){const t=e.storageBucket??this.#dd.getDefaultBucketForStorageKey(e.storageKey)?.bucket;if(!t)continue;const s=new ha(this,t,e.cacheName,e.cacheId);n.add(s.cacheId),this.#cd.has(s.cacheId)||(r.set(s.cacheId,s),this.#cd.set(s.cacheId,s))}this.#cd.forEach((function(t){t.inBucket(e)&&!n.has(t.cacheId)&&(s.set(t.cacheId,t),this.#cd.delete(t.cacheId))}),this),r.forEach(this.cacheAdded,this),s.forEach(this.cacheRemoved,this)}storageBucketAdded({data:{bucketInfo:{bucket:e}}}){this.addStorageBucket(e)}storageBucketRemoved({data:{bucketInfo:{bucket:e}}}){this.removeStorageBucket(e)}cacheAdded(e){this.dispatchEventToListeners(ca.CacheAdded,{model:this,cache:e})}cacheRemoved(e){this.dispatchEventToListeners(ca.CacheRemoved,{model:this,cache:e})}async requestEntries(e,t,n,r,s){const i=await this.cacheAgent.invoke_requestEntries({cacheId:e.cacheId,skipCount:t,pageSize:n,pathFilter:r});i.getError()?console.error("ServiceWorkerCacheAgent error while requesting entries: ",i.getError()):s(i.cacheDataEntries,i.returnCount)}async requestAllEntries(e,t,n){const r=await this.cacheAgent.invoke_requestEntries({cacheId:e.cacheId,pathFilter:t});r.getError()?console.error("ServiceWorkerCacheAgent error while requesting entries: ",r.getError()):n(r.cacheDataEntries,r.returnCount)}cacheStorageListUpdated({bucketId:e}){const t=this.#dd.getBucketById(e)?.bucket;t&&(this.#ud.add(t),this.#gd.schedule((()=>{const e=Array.from(this.#ud,(e=>this.loadCacheNames(e)));return this.#ud.clear(),Promise.all(e)}),this.#pd))}cacheStorageContentUpdated({bucketId:e,cacheName:t}){const n=this.#dd.getBucketById(e)?.bucket;n&&this.dispatchEventToListeners(ca.CacheStorageContentUpdated,{storageBucket:n,cacheName:t})}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}interestGroupAccessed(e){}sharedStorageAccessed(e){}storageBucketCreatedOrUpdated(e){}storageBucketDeleted(e){}setThrottlerSchedulesAsSoonAsPossibleForTest(){this.#pd=!0}}var ca;!function(e){e.CacheAdded="CacheAdded",e.CacheRemoved="CacheRemoved",e.CacheStorageContentUpdated="CacheStorageContentUpdated"}(ca||(ca={}));class ha{#$r;storageKey;storageBucket;cacheName;cacheId;constructor(e,t,n,r){this.#$r=e,this.storageBucket=t,this.storageKey=t.storageKey,this.cacheName=n,this.cacheId=r}inBucket(e){return this.storageKey===e.storageKey&&this.storageBucket.name===e.name}equals(e){return this.cacheId===e.cacheId}toString(){return this.storageKey+this.cacheName}async requestCachedResponse(e,t){const n=await this.#$r.cacheAgent.invoke_requestCachedResponse({cacheId:this.cacheId,requestURL:e,requestHeaders:t});return n.getError()?null:n.response}}c.register(da,{capabilities:z.Storage,autostart:!1});var ua=Object.freeze({__proto__:null,ServiceWorkerCacheModel:da,get Events(){return ca},Cache:ha});const ga={running:"running",starting:"starting",stopped:"stopped",stopping:"stopping",activated:"activated",activating:"activating",installed:"installed",installing:"installing",new:"new",redundant:"redundant",sSS:"{PH1} #{PH2} ({PH3})"},pa=s.i18n.registerUIStrings("core/sdk/ServiceWorkerManager.ts",ga),ma=s.i18n.getLocalizedString.bind(void 0,pa),fa=s.i18n.getLazilyComputedLocalizedString.bind(void 0,pa);class ba extends c{#Ts;#md;#ma;#fd;serviceWorkerNetworkRequestsPanelStatus;constructor(t){super(t),t.registerServiceWorkerDispatcher(new va(this)),this.#Ts=t.serviceWorkerAgent(),this.#md=new Map,this.#ma=!1,this.enable(),this.#fd=e.Settings.Settings.instance().createSetting("serviceWorkerUpdateOnReload",!1),this.#fd.get()&&this.forceUpdateSettingChanged(),this.#fd.addChangeListener(this.forceUpdateSettingChanged,this),new wa(t,this),this.serviceWorkerNetworkRequestsPanelStatus={isOpen:!1,openedAt:0}}async enable(){this.#ma||(this.#ma=!0,await this.#Ts.invoke_enable())}async disable(){this.#ma&&(this.#ma=!1,this.#md.clear(),await this.#Ts.invoke_enable())}registrations(){return this.#md}hasRegistrationForURLs(e){for(const t of this.#md.values())if(e.filter((e=>e&&e.startsWith(t.scopeURL))).length===e.length)return!0;return!1}findVersion(e){for(const t of this.registrations().values()){const n=t.versions.get(e);if(n)return n}return null}deleteRegistration(e){const t=this.#md.get(e);if(t){if(t.isRedundant())return this.#md.delete(e),void this.dispatchEventToListeners(ya.RegistrationDeleted,t);t.deleting=!0;for(const e of t.versions.values())this.stopWorker(e.id);this.unregister(t.scopeURL)}}async updateRegistration(e){const t=this.#md.get(e);t&&await this.#Ts.invoke_updateRegistration({scopeURL:t.scopeURL})}async deliverPushMessage(t,n){const r=this.#md.get(t);if(!r)return;const s=e.ParsedURL.ParsedURL.extractOrigin(r.scopeURL);await this.#Ts.invoke_deliverPushMessage({origin:s,registrationId:t,data:n})}async dispatchSyncEvent(t,n,r){const s=this.#md.get(t);if(!s)return;const i=e.ParsedURL.ParsedURL.extractOrigin(s.scopeURL);await this.#Ts.invoke_dispatchSyncEvent({origin:i,registrationId:t,tag:n,lastChance:r})}async dispatchPeriodicSyncEvent(t,n){const r=this.#md.get(t);if(!r)return;const s=e.ParsedURL.ParsedURL.extractOrigin(r.scopeURL);await this.#Ts.invoke_dispatchPeriodicSyncEvent({origin:s,registrationId:t,tag:n})}async unregister(e){await this.#Ts.invoke_unregister({scopeURL:e})}async startWorker(e){await this.#Ts.invoke_startWorker({scopeURL:e})}async skipWaiting(e){await this.#Ts.invoke_skipWaiting({scopeURL:e})}async stopWorker(e){await this.#Ts.invoke_stopWorker({versionId:e})}async inspectWorker(e){await this.#Ts.invoke_inspectWorker({versionId:e})}workerRegistrationUpdated(e){for(const t of e){let e=this.#md.get(t.registrationId);e?(e.update(t),e.shouldBeRemoved()?(this.#md.delete(e.id),this.dispatchEventToListeners(ya.RegistrationDeleted,e)):this.dispatchEventToListeners(ya.RegistrationUpdated,e)):(e=new Sa(t),this.#md.set(t.registrationId,e),this.dispatchEventToListeners(ya.RegistrationUpdated,e))}}workerVersionUpdated(e){const t=new Set;for(const n of e){const e=this.#md.get(n.registrationId);e&&(e.updateVersion(n),t.add(e))}for(const e of t)e.shouldBeRemoved()?(this.#md.delete(e.id),this.dispatchEventToListeners(ya.RegistrationDeleted,e)):this.dispatchEventToListeners(ya.RegistrationUpdated,e)}workerErrorReported(e){const t=this.#md.get(e.registrationId);t&&(t.errors.push(e),this.dispatchEventToListeners(ya.RegistrationErrorAdded,{registration:t,error:e}))}forceUpdateOnReloadSetting(){return this.#fd}forceUpdateSettingChanged(){const e=this.#fd.get();this.#Ts.invoke_setForceUpdateOnPageLoad({forceUpdateOnPageLoad:e})}}var ya;!function(e){e.RegistrationUpdated="RegistrationUpdated",e.RegistrationErrorAdded="RegistrationErrorAdded",e.RegistrationDeleted="RegistrationDeleted"}(ya||(ya={}));class va{#$;constructor(e){this.#$=e}workerRegistrationUpdated({registrations:e}){this.#$.workerRegistrationUpdated(e)}workerVersionUpdated({versions:e}){this.#$.workerVersionUpdated(e)}workerErrorReported({errorMessage:e}){this.#$.workerErrorReported(e)}}class Ia{runningStatus;status;last_updated_timestamp;previousState;constructor(e,t,n,r){this.runningStatus=e,this.status=t,this.last_updated_timestamp=r,this.previousState=n}}class ka{id;scriptURL;parsedURL;securityOrigin;scriptLastModified;scriptResponseTime;controlledClients;targetId;currentState;registration;constructor(e,t){this.registration=e,this.update(t)}update(t){this.id=t.versionId,this.scriptURL=t.scriptURL;const n=new e.ParsedURL.ParsedURL(t.scriptURL);this.securityOrigin=n.securityOrigin(),this.currentState=new Ia(t.runningStatus,t.status,this.currentState,Date.now()),this.scriptLastModified=t.scriptLastModified,this.scriptResponseTime=t.scriptResponseTime,t.controlledClients?this.controlledClients=t.controlledClients.slice():this.controlledClients=[],this.targetId=t.targetId||null}isStartable(){return!this.registration.isDeleted&&this.isActivated()&&this.isStopped()}isStoppedAndRedundant(){return"stopped"===this.runningStatus&&"redundant"===this.status}isStopped(){return"stopped"===this.runningStatus}isStarting(){return"starting"===this.runningStatus}isRunning(){return"running"===this.runningStatus}isStopping(){return"stopping"===this.runningStatus}isNew(){return"new"===this.status}isInstalling(){return"installing"===this.status}isInstalled(){return"installed"===this.status}isActivating(){return"activating"===this.status}isActivated(){return"activated"===this.status}isRedundant(){return"redundant"===this.status}get status(){return this.currentState.status}get runningStatus(){return this.currentState.runningStatus}mode(){return this.isNew()||this.isInstalling()?ka.Modes.Installing:this.isInstalled()?ka.Modes.Waiting:this.isActivating()||this.isActivated()?ka.Modes.Active:ka.Modes.Redundant}}!function(e){let t;e.RunningStatus={running:fa(ga.running),starting:fa(ga.starting),stopped:fa(ga.stopped),stopping:fa(ga.stopping)},e.Status={activated:fa(ga.activated),activating:fa(ga.activating),installed:fa(ga.installed),installing:fa(ga.installing),new:fa(ga.new),redundant:fa(ga.redundant)},function(e){e.Installing="installing",e.Waiting="waiting",e.Active="active",e.Redundant="redundant"}(t=e.Modes||(e.Modes={}))}(ka||(ka={}));class Sa{#bd;id;scopeURL;securityOrigin;isDeleted;versions;deleting;errors;constructor(e){this.update(e),this.versions=new Map,this.deleting=!1,this.errors=[]}update(t){this.#bd=Symbol("fingerprint"),this.id=t.registrationId,this.scopeURL=t.scopeURL;const n=new e.ParsedURL.ParsedURL(t.scopeURL);this.securityOrigin=n.securityOrigin(),this.isDeleted=t.isDeleted}fingerprint(){return this.#bd}versionsByMode(){const e=new Map;for(const t of this.versions.values())e.set(t.mode(),t);return e}updateVersion(e){this.#bd=Symbol("fingerprint");let t=this.versions.get(e.versionId);return t?(t.update(e),t):(t=new ka(this,e),this.versions.set(e.versionId,t),t)}isRedundant(){for(const e of this.versions.values())if(!e.isStoppedAndRedundant())return!1;return!0}shouldBeRemoved(){return this.isRedundant()&&(!this.errors.length||this.deleting)}canBeRemoved(){return this.isDeleted||this.deleting}clearErrors(){this.#bd=Symbol("fingerprint"),this.errors=[]}}class wa{#h;#yd;#vd;constructor(e,t){this.#h=e,this.#yd=t,this.#vd=new Map,t.addEventListener(ya.RegistrationUpdated,this.registrationsUpdated,this),t.addEventListener(ya.RegistrationDeleted,this.registrationsUpdated,this),K.instance().addModelListener(Cr,Rr.ExecutionContextCreated,this.executionContextCreated,this)}registrationsUpdated(){this.#vd.clear();const e=this.#yd.registrations().values();for(const t of e)for(const e of t.versions.values())e.targetId&&this.#vd.set(e.targetId,e);this.updateAllContextLabels()}executionContextCreated(e){const t=e.data,n=this.serviceWorkerTargetId(t.target());n&&this.updateContextLabel(t,this.#vd.get(n)||null)}serviceWorkerTargetId(e){return e.parentTarget()!==this.#h||e.type()!==_.ServiceWorker?null:e.id()}updateAllContextLabels(){for(const e of K.instance().targets()){const t=this.serviceWorkerTargetId(e);if(!t)continue;const n=this.#vd.get(t)||null,r=e.model(Cr),s=r?r.executionContexts():[];for(const e of s)this.updateContextLabel(e,n)}}updateContextLabel(t,n){if(!n)return void t.setLabel("");const r=e.ParsedURL.ParsedURL.fromString(t.origin),s=r?r.lastPathComponentWithFragment():t.name,i=ka.Status[n.status];t.setLabel(ma(ga.sSS,{PH1:s,PH2:n.id,PH3:i()}))}}c.register(ba,{capabilities:z.ServiceWorker,autostart:!0});var Ca=Object.freeze({__proto__:null,ServiceWorkerManager:ba,get Events(){return ya},ServiceWorkerVersionState:Ia,get ServiceWorkerVersion(){return ka},ServiceWorkerRegistration:Sa});const Ta=new Map,Ra=new Map;async function xa(e,t){const n=Ta.get(e)?.get(t);if(void 0!==n)return n;const r=K.instance().primaryPageTarget()?.model(Pn);if(!r)return null;const s=(await r.pushNodesByBackendIdsToFrontend(new Set([t])))?.get(t)||null,i=Ta.get(e)||new Map;return i.set(t,s),Ta.set(e,i),s}const Ma=new Map,Pa=new Map;var La=Object.freeze({__proto__:null,_TEST_clearCache:function(){Ta.clear(),Ra.clear(),Ma.clear(),Pa.clear()},domNodeForBackendNodeID:xa,domNodesForMultipleBackendNodeIds:async function(e,t){const n=Ra.get(e)?.get(t);if(n)return n;const r=K.instance().primaryPageTarget()?.model(Pn);if(!r)return new Map;const s=await r.pushNodesByBackendIdsToFrontend(t)||new Map,i=Ra.get(e)||new Map;return i.set(t,s),Ra.set(e,i),s},sourcesForLayoutShift:async function(e,t){const n=Ma.get(e)?.get(t);if(n)return n;const r=t.args.data?.impacted_nodes;if(!r)return[];const s=[];await Promise.all(r.map((async t=>{const n=await xa(e,t.node_id);n&&s.push({previousRect:new DOMRect(t.old_rect[0],t.old_rect[1],t.old_rect[2],t.old_rect[3]),currentRect:new DOMRect(t.new_rect[0],t.new_rect[1],t.new_rect[2],t.new_rect[3]),node:n})})));const i=Ma.get(e)||new Map;return i.set(t,s),Ma.set(e,i),s},normalizedImpactedNodesForLayoutShift:async function(e,t){const n=Pa.get(e)?.get(t);if(n)return n;const r=t.args?.data?.impacted_nodes;if(!r)return[];let s=null;const i=K.instance().primaryPageTarget(),a=await(i?.runtimeAgent().invoke_evaluate({expression:"window.devicePixelRatio"}));if("number"===a?.result.type&&(s=a?.result.value??null),!s)return r;const o=[];for(const e of r){const t={...e};for(let n=0;n{setTimeout((()=>e(void 0)),1e3)}))]):void 0,n=Ts.instance().cpuThrottlingRate(),r=ue.instance().networkConditions(),s="function"==typeof r.title?r.title():r.title;return{source:"DevTools",startTime:e?new Date(e).toJSON():void 0,cpuThrottling:n,networkThrottling:s,hardwareConcurrency:t}}catch{return}}});class Ea extends c{#Id;#kd;#Sd;#wd;#Cd;constructor(e){super(e),this.#Id=e.tracingAgent(),e.registerTracingDispatcher(new Aa(this)),this.#kd=null,this.#Sd=0,this.#wd=0}bufferUsage(e,t,n){this.#Sd=void 0===t?null:t,this.#kd&&this.#kd.tracingBufferUsage(e||n||0)}eventsCollected(e){this.#kd&&(this.#kd.traceEventsCollected(e),this.#wd+=e.length,this.#Sd?(this.#wd>this.#Sd&&(this.#wd=this.#Sd),this.#kd.eventsRetrievalProgress(this.#wd/this.#Sd)):this.#kd.eventsRetrievalProgress(0))}tracingComplete(){this.#Sd=0,this.#wd=0,this.#kd&&(this.#kd.tracingComplete(),this.#kd=null),this.#Cd=!1}async start(e,t,n){if(this.#kd)throw new Error("Tracing is already started");this.#kd=e;const r={bufferUsageReportingInterval:500,categories:t,options:n,transferMode:"ReportEvents"},s=await this.#Id.invoke_start(r);return s.getError()&&(this.#kd=null),s}stop(){if(!this.#kd)throw new Error("Tracing is not started");if(this.#Cd)throw new Error("Tracing is already being stopped");this.#Cd=!0,this.#Id.invoke_end()}}class Aa{#Td;constructor(e){this.#Td=e}bufferUsage({value:e,eventCount:t,percentFull:n}){this.#Td.bufferUsage(e,t,n)}dataCollected({value:e}){this.#Td.eventsCollected(e)}tracingComplete(){this.#Td.tracingComplete()}}c.register(Ea,{capabilities:z.Tracing,autostart:!1});var Oa=Object.freeze({__proto__:null,TracingManager:Ea});class Na extends c{#Ts;constructor(e){super(e),this.#Ts=e.webAuthnAgent(),e.registerWebAuthnDispatcher(new Fa(this))}setVirtualAuthEnvEnabled(e){return e?this.#Ts.invoke_enable({enableUI:!0}):this.#Ts.invoke_disable()}async addAuthenticator(e){return(await this.#Ts.invoke_addVirtualAuthenticator({options:e})).authenticatorId}async removeAuthenticator(e){await this.#Ts.invoke_removeVirtualAuthenticator({authenticatorId:e})}async setAutomaticPresenceSimulation(e,t){await this.#Ts.invoke_setAutomaticPresenceSimulation({authenticatorId:e,enabled:t})}async getCredentials(e){return(await this.#Ts.invoke_getCredentials({authenticatorId:e})).credentials}async removeCredential(e,t){await this.#Ts.invoke_removeCredential({authenticatorId:e,credentialId:t})}credentialAdded(e){this.dispatchEventToListeners("CredentialAdded",e)}credentialAsserted(e){this.dispatchEventToListeners("CredentialAsserted",e)}}class Fa{#$r;constructor(e){this.#$r=e}credentialAdded(e){this.#$r.credentialAdded(e)}credentialAsserted(e){this.#$r.credentialAsserted(e)}}c.register(Na,{capabilities:z.WebAuthn,autostart:!1});var Ba=Object.freeze({__proto__:null,WebAuthnModel:Na});export{Nr as AccessibilityModel,vs as CPUProfileDataModel,ss as CPUProfilerModel,Ms as CPUThrottlingManager,Qe as CSSContainerQuery,ze as CSSFontFace,Je as CSSLayer,wt as CSSMatchedStyles,tt as CSSMedia,E as CSSMetadata,hn as CSSModel,lt as CSSProperty,Fs as CSSPropertyParser,We as CSSQuery,yt as CSSRule,rt as CSSScope,ct as CSSStyleDeclaration,Mt as CSSStyleSheetHeader,it as CSSSupports,Br as CategorizedBreakpoint,Vr as ChildTargetManager,Jr as CompilerSourceMappingContentProvider,jr as Connections,ms as ConsoleModel,U as Cookie,bs as CookieModel,j as CookieParser,$s as DOMDebuggerModel,On as DOMModel,Ir as DebuggerModel,ws as EmulationModel,ni as EventBreakpointsModel,Ci as FilmStripModel,Ti as FrameAssociated,At as FrameManager,wr as HeapProfilerModel,Nt as IOModel,Ai as IsolateManager,Fi as IssuesModel,Bi as LayerTreeBase,as as LogModel,me as NetworkManager,Pe as NetworkRequest,gn as OverlayColorGenerator,Cn as OverlayModel,mn as OverlayPersistentHighlighter,Hi as PageLoad,zt as PageResourceLoader,ji as PaintProfiler,Gi as PerformanceMetricsModel,ta as PreloadingModel,N as ProfileTreeModel,qe as RemoteObject,Bn as Resource,Kn as ResourceTreeModel,Er as RuntimeModel,h as SDKModel,ra as ScreenCaptureModel,tr as Script,Hn as SecurityOriginManager,Ie as ServerTiming,ua as ServiceWorkerCacheModel,Ca as ServiceWorkerManager,Xt as SourceMap,Zt as SourceMapManager,ia as StorageBucketsModel,zn as StorageKeyManager,V as Target,Q as TargetManager,La as TraceSDKServices,Oa as TracingManager,Ii as TracingModel,Ba as WebAuthnModel}; +import*as e from"../common/common.js";import*as t from"../platform/platform.js";import{assertNotNullOrUndefined as n}from"../platform/platform.js";import*as r from"../../models/text_utils/text_utils.js";import*as s from"../i18n/i18n.js";import*as i from"../host/host.js";import*as a from"../protocol_client/protocol_client.js";import*as o from"../root/root.js";import*as l from"../../models/trace/trace.js";const d=new Map;class c extends e.ObjectWrapper.ObjectWrapper{#e;constructor(e){super(),this.#e=e}target(){return this.#e}async preSuspendModel(e){}async suspendModel(e){}async resumeModel(){}async postResumeModel(){}dispose(){}static register(e,t){if(t.early&&!t.autostart)throw new Error(`Error registering model ${e.name}: early models must be autostarted.`);d.set(e,t)}static get registeredModels(){return d}}var h=Object.freeze({__proto__:null,SDKModel:c});const u=[{longhands:["animation-delay-start","animation-delay-end"],name:"-alternative-animation-delay"},{longhands:["animation-duration","animation-timing-function","animation-delay-start","animation-delay-end","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name","animation-timeline","animation-range-start","animation-range-end"],name:"-alternative-animation-with-delay-start-end"},{longhands:["animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name","animation-timeline","animation-range-start","animation-range-end"],name:"-alternative-animation-with-timeline"},{inherited:!0,longhands:["white-space-collapse","text-wrap"],name:"-alternative-white-space"},{inherited:!0,name:"-webkit-border-horizontal-spacing"},{name:"-webkit-border-image"},{inherited:!0,name:"-webkit-border-vertical-spacing"},{keywords:["stretch","start","center","end","baseline"],name:"-webkit-box-align"},{keywords:["slice","clone"],name:"-webkit-box-decoration-break"},{inherited:!0,keywords:["normal","reverse"],name:"-webkit-box-direction"},{name:"-webkit-box-flex"},{name:"-webkit-box-ordinal-group"},{keywords:["horizontal","vertical"],name:"-webkit-box-orient"},{keywords:["start","center","end","justify"],name:"-webkit-box-pack"},{name:"-webkit-box-reflect"},{longhands:["break-after"],name:"-webkit-column-break-after"},{longhands:["break-before"],name:"-webkit-column-break-before"},{longhands:["break-inside"],name:"-webkit-column-break-inside"},{inherited:!0,name:"-webkit-font-smoothing"},{inherited:!0,name:"-webkit-highlight"},{inherited:!0,keywords:["auto","loose","normal","strict","after-white-space","anywhere"],name:"-webkit-line-break"},{name:"-webkit-line-clamp"},{inherited:!0,name:"-webkit-locale"},{longhands:["-webkit-mask-image","-webkit-mask-position-x","-webkit-mask-position-y","-webkit-mask-size","-webkit-mask-repeat-x","-webkit-mask-repeat-y","-webkit-mask-origin","-webkit-mask-clip"],name:"-webkit-mask"},{longhands:["-webkit-mask-box-image-source","-webkit-mask-box-image-slice","-webkit-mask-box-image-width","-webkit-mask-box-image-outset","-webkit-mask-box-image-repeat"],name:"-webkit-mask-box-image"},{name:"-webkit-mask-box-image-outset"},{name:"-webkit-mask-box-image-repeat"},{name:"-webkit-mask-box-image-slice"},{name:"-webkit-mask-box-image-source"},{name:"-webkit-mask-box-image-width"},{name:"-webkit-mask-clip"},{name:"-webkit-mask-composite"},{name:"-webkit-mask-image"},{name:"-webkit-mask-origin"},{longhands:["-webkit-mask-position-x","-webkit-mask-position-y"],name:"-webkit-mask-position"},{name:"-webkit-mask-position-x"},{name:"-webkit-mask-position-y"},{longhands:["-webkit-mask-repeat-x","-webkit-mask-repeat-y"],name:"-webkit-mask-repeat"},{name:"-webkit-mask-repeat-x"},{name:"-webkit-mask-repeat-y"},{name:"-webkit-mask-size"},{name:"-webkit-perspective-origin-x"},{name:"-webkit-perspective-origin-y"},{inherited:!0,keywords:["economy","exact"],name:"-webkit-print-color-adjust"},{inherited:!0,keywords:["logical","visual"],name:"-webkit-rtl-ordering"},{inherited:!0,keywords:["before","after"],name:"-webkit-ruby-position"},{inherited:!0,name:"-webkit-tap-highlight-color"},{inherited:!0,name:"-webkit-text-combine"},{inherited:!0,name:"-webkit-text-decorations-in-effect"},{inherited:!0,name:"-webkit-text-fill-color"},{inherited:!0,name:"-webkit-text-orientation"},{inherited:!0,keywords:["none","disc","circle","square"],name:"-webkit-text-security"},{inherited:!0,longhands:["-webkit-text-stroke-width","-webkit-text-stroke-color"],name:"-webkit-text-stroke"},{inherited:!0,name:"-webkit-text-stroke-color"},{inherited:!0,name:"-webkit-text-stroke-width"},{name:"-webkit-transform-origin-x"},{name:"-webkit-transform-origin-y"},{name:"-webkit-transform-origin-z"},{keywords:["auto","none","element"],name:"-webkit-user-drag"},{inherited:!0,keywords:["read-only","read-write","read-write-plaintext-only"],name:"-webkit-user-modify"},{inherited:!0,name:"-webkit-writing-mode"},{inherited:!0,keywords:["auto","currentcolor"],name:"accent-color"},{name:"additive-symbols"},{name:"align-content"},{name:"align-items"},{name:"align-self"},{keywords:["auto","baseline","alphabetic","ideographic","middle","central","mathematical","before-edge","text-before-edge","after-edge","text-after-edge","hanging"],name:"alignment-baseline"},{name:"all"},{keywords:["none"],name:"anchor-default"},{keywords:["none"],name:"anchor-name"},{keywords:["none"],name:"anchor-scroll"},{longhands:["animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state","animation-name"],name:"animation"},{keywords:["replace","add","accumulate"],name:"animation-composition"},{name:"animation-delay"},{name:"animation-delay-end"},{name:"animation-delay-start"},{keywords:["normal","reverse","alternate","alternate-reverse"],name:"animation-direction"},{name:"animation-duration"},{keywords:["none","forwards","backwards","both"],name:"animation-fill-mode"},{keywords:["infinite"],name:"animation-iteration-count"},{keywords:["none"],name:"animation-name"},{keywords:["running","paused"],name:"animation-play-state"},{longhands:["animation-range-start","animation-range-end"],name:"animation-range"},{name:"animation-range-end"},{name:"animation-range-start"},{keywords:["none","auto"],name:"animation-timeline"},{keywords:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"],name:"animation-timing-function"},{keywords:["none","drag","no-drag"],name:"app-region"},{name:"appearance"},{name:"ascent-override"},{keywords:["auto"],name:"aspect-ratio"},{keywords:["none"],name:"backdrop-filter"},{keywords:["visible","hidden"],name:"backface-visibility"},{longhands:["background-image","background-position-x","background-position-y","background-size","background-repeat-x","background-repeat-y","background-attachment","background-origin","background-clip","background-color"],name:"background"},{keywords:["scroll","fixed","local"],name:"background-attachment"},{keywords:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],name:"background-blend-mode"},{keywords:["border-box","padding-box","content-box"],name:"background-clip"},{keywords:["currentcolor"],name:"background-color"},{keywords:["auto","none"],name:"background-image"},{keywords:["border-box","padding-box","content-box"],name:"background-origin"},{longhands:["background-position-x","background-position-y"],name:"background-position"},{name:"background-position-x"},{name:"background-position-y"},{longhands:["background-repeat-x","background-repeat-y"],name:"background-repeat"},{name:"background-repeat-x"},{name:"background-repeat-y"},{keywords:["auto","cover","contain"],name:"background-size"},{name:"base-palette"},{keywords:["baseline","sub","super"],name:"baseline-shift"},{keywords:["auto","first","last"],name:"baseline-source"},{keywords:["auto"],name:"block-size"},{longhands:["border-top-color","border-top-style","border-top-width","border-right-color","border-right-style","border-right-width","border-bottom-color","border-bottom-style","border-bottom-width","border-left-color","border-left-style","border-left-width","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],name:"border"},{longhands:["border-block-start-color","border-block-start-style","border-block-start-width","border-block-end-color","border-block-end-style","border-block-end-width"],name:"border-block"},{longhands:["border-block-start-color","border-block-end-color"],name:"border-block-color"},{longhands:["border-block-end-width","border-block-end-style","border-block-end-color"],name:"border-block-end"},{name:"border-block-end-color"},{name:"border-block-end-style"},{name:"border-block-end-width"},{longhands:["border-block-start-width","border-block-start-style","border-block-start-color"],name:"border-block-start"},{name:"border-block-start-color"},{name:"border-block-start-style"},{name:"border-block-start-width"},{longhands:["border-block-start-style","border-block-end-style"],name:"border-block-style"},{longhands:["border-block-start-width","border-block-end-width"],name:"border-block-width"},{longhands:["border-bottom-width","border-bottom-style","border-bottom-color"],name:"border-bottom"},{keywords:["currentcolor"],name:"border-bottom-color"},{name:"border-bottom-left-radius"},{name:"border-bottom-right-radius"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-bottom-style"},{keywords:["thin","medium","thick"],name:"border-bottom-width"},{inherited:!0,keywords:["separate","collapse"],name:"border-collapse"},{longhands:["border-top-color","border-right-color","border-bottom-color","border-left-color"],name:"border-color"},{name:"border-end-end-radius"},{name:"border-end-start-radius"},{longhands:["border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],name:"border-image"},{name:"border-image-outset"},{keywords:["stretch","repeat","round","space"],name:"border-image-repeat"},{name:"border-image-slice"},{keywords:["none"],name:"border-image-source"},{keywords:["auto"],name:"border-image-width"},{longhands:["border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-end-color","border-inline-end-style","border-inline-end-width"],name:"border-inline"},{longhands:["border-inline-start-color","border-inline-end-color"],name:"border-inline-color"},{longhands:["border-inline-end-width","border-inline-end-style","border-inline-end-color"],name:"border-inline-end"},{name:"border-inline-end-color"},{name:"border-inline-end-style"},{name:"border-inline-end-width"},{longhands:["border-inline-start-width","border-inline-start-style","border-inline-start-color"],name:"border-inline-start"},{name:"border-inline-start-color"},{name:"border-inline-start-style"},{name:"border-inline-start-width"},{longhands:["border-inline-start-style","border-inline-end-style"],name:"border-inline-style"},{longhands:["border-inline-start-width","border-inline-end-width"],name:"border-inline-width"},{longhands:["border-left-width","border-left-style","border-left-color"],name:"border-left"},{keywords:["currentcolor"],name:"border-left-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-left-style"},{keywords:["thin","medium","thick"],name:"border-left-width"},{longhands:["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],name:"border-radius"},{longhands:["border-right-width","border-right-style","border-right-color"],name:"border-right"},{keywords:["currentcolor"],name:"border-right-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-right-style"},{keywords:["thin","medium","thick"],name:"border-right-width"},{inherited:!0,longhands:["-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing"],name:"border-spacing"},{name:"border-start-end-radius"},{name:"border-start-start-radius"},{keywords:["none"],longhands:["border-top-style","border-right-style","border-bottom-style","border-left-style"],name:"border-style"},{longhands:["border-top-width","border-top-style","border-top-color"],name:"border-top"},{keywords:["currentcolor"],name:"border-top-color"},{name:"border-top-left-radius"},{name:"border-top-right-radius"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"border-top-style"},{keywords:["thin","medium","thick"],name:"border-top-width"},{longhands:["border-top-width","border-right-width","border-bottom-width","border-left-width"],name:"border-width"},{keywords:["auto"],name:"bottom"},{keywords:["none"],name:"box-shadow"},{keywords:["content-box","border-box"],name:"box-sizing"},{keywords:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"],name:"break-after"},{keywords:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"],name:"break-before"},{keywords:["auto","avoid","avoid-column","avoid-page"],name:"break-inside"},{keywords:["auto","dynamic","static"],name:"buffered-rendering"},{inherited:!0,keywords:["top","bottom"],name:"caption-side"},{inherited:!0,keywords:["auto","currentcolor"],name:"caret-color"},{keywords:["none","left","right","both","inline-start","inline-end"],name:"clear"},{keywords:["auto"],name:"clip"},{keywords:["none"],name:"clip-path"},{inherited:!0,keywords:["nonzero","evenodd"],name:"clip-rule"},{inherited:!0,keywords:["currentcolor"],name:"color"},{inherited:!0,keywords:["auto","srgb","linearrgb"],name:"color-interpolation"},{inherited:!0,keywords:["auto","srgb","linearrgb"],name:"color-interpolation-filters"},{inherited:!0,keywords:["auto","optimizespeed","optimizequality"],name:"color-rendering"},{inherited:!0,name:"color-scheme"},{keywords:["auto"],name:"column-count"},{keywords:["balance","auto"],name:"column-fill"},{keywords:["normal"],name:"column-gap"},{longhands:["column-rule-width","column-rule-style","column-rule-color"],name:"column-rule"},{keywords:["currentcolor"],name:"column-rule-color"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"column-rule-style"},{keywords:["thin","medium","thick"],name:"column-rule-width"},{keywords:["none","all"],name:"column-span"},{keywords:["auto"],name:"column-width"},{longhands:["column-width","column-count"],name:"columns"},{keywords:["none","strict","content","size","layout","style","paint","inline-size","block-size"],name:"contain"},{name:"contain-intrinsic-block-size"},{keywords:["auto","none"],name:"contain-intrinsic-height"},{name:"contain-intrinsic-inline-size"},{longhands:["contain-intrinsic-width","contain-intrinsic-height"],name:"contain-intrinsic-size"},{keywords:["auto","none"],name:"contain-intrinsic-width"},{longhands:["container-name","container-type"],name:"container"},{keywords:["none"],name:"container-name"},{keywords:["normal","inline-size","size","sticky"],name:"container-type"},{name:"content"},{keywords:["visible","auto","hidden"],name:"content-visibility"},{keywords:["none"],name:"counter-increment"},{keywords:["none"],name:"counter-reset"},{keywords:["none"],name:"counter-set"},{inherited:!0,keywords:["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","grab","grabbing"],name:"cursor"},{name:"cx"},{name:"cy"},{keywords:["none"],name:"d"},{name:"descent-override"},{inherited:!0,keywords:["ltr","rtl"],name:"direction"},{keywords:["inline","block","list-item","inline-block","table","inline-table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption","-webkit-box","-webkit-inline-box","flex","inline-flex","grid","inline-grid","contents","flow-root","none","flow","math"],name:"display"},{inherited:!0,keywords:["auto","alphabetic","ideographic","middle","central","mathematical","hanging","use-script","no-change","reset-size","text-after-edge","text-before-edge"],name:"dominant-baseline"},{inherited:!0,keywords:["show","hide"],name:"empty-cells"},{name:"fallback"},{inherited:!0,name:"fill"},{inherited:!0,name:"fill-opacity"},{inherited:!0,keywords:["nonzero","evenodd"],name:"fill-rule"},{keywords:["none"],name:"filter"},{longhands:["flex-grow","flex-shrink","flex-basis"],name:"flex"},{keywords:["auto","fit-content","min-content","max-content","content"],name:"flex-basis"},{keywords:["row","row-reverse","column","column-reverse"],name:"flex-direction"},{longhands:["flex-direction","flex-wrap"],name:"flex-flow"},{name:"flex-grow"},{name:"flex-shrink"},{keywords:["nowrap","wrap","wrap-reverse"],name:"flex-wrap"},{keywords:["none","left","right","inline-start","inline-end"],name:"float"},{keywords:["currentcolor"],name:"flood-color"},{name:"flood-opacity"},{inherited:!0,longhands:["font-style","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-variant-alternates","font-variant-position","font-weight","font-stretch","font-size","line-height","font-family","font-optical-sizing","font-size-adjust","font-kerning","font-feature-settings","font-variation-settings"],name:"font"},{name:"font-display"},{inherited:!0,name:"font-family"},{inherited:!0,keywords:["normal"],name:"font-feature-settings"},{inherited:!0,keywords:["auto","normal","none"],name:"font-kerning"},{inherited:!0,keywords:["auto","none"],name:"font-optical-sizing"},{inherited:!0,keywords:["normal","light","dark"],name:"font-palette"},{inherited:!0,keywords:["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller","-webkit-xxx-large"],name:"font-size"},{inherited:!0,keywords:["none","ex-height","cap-height","ch-width","ic-width"],name:"font-size-adjust"},{inherited:!0,keywords:["normal","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"],name:"font-stretch"},{inherited:!0,keywords:["normal","italic","oblique"],name:"font-style"},{inherited:!0,longhands:["font-synthesis-weight","font-synthesis-style","font-synthesis-small-caps"],name:"font-synthesis"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-small-caps"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-style"},{inherited:!0,keywords:["auto","none"],name:"font-synthesis-weight"},{inherited:!0,longhands:["font-variant-ligatures","font-variant-caps","font-variant-alternates","font-variant-numeric","font-variant-east-asian","font-variant-position"],name:"font-variant"},{inherited:!0,keywords:["normal"],name:"font-variant-alternates"},{inherited:!0,keywords:["normal","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps"],name:"font-variant-caps"},{inherited:!0,keywords:["normal","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"],name:"font-variant-east-asian"},{inherited:!0,keywords:["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual"],name:"font-variant-ligatures"},{inherited:!0,keywords:["normal","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero"],name:"font-variant-numeric"},{inherited:!0,keywords:["normal","sub","super"],name:"font-variant-position"},{inherited:!0,keywords:["normal"],name:"font-variation-settings"},{inherited:!0,keywords:["normal","bold","bolder","lighter"],name:"font-weight"},{inherited:!0,keywords:["auto","none","preserve-parent-color"],name:"forced-color-adjust"},{longhands:["row-gap","column-gap"],name:"gap"},{longhands:["grid-template-rows","grid-template-columns","grid-template-areas","grid-auto-flow","grid-auto-rows","grid-auto-columns"],name:"grid"},{longhands:["grid-row-start","grid-column-start","grid-row-end","grid-column-end"],name:"grid-area"},{keywords:["auto","min-content","max-content"],name:"grid-auto-columns"},{keywords:["row","column"],name:"grid-auto-flow"},{keywords:["auto","min-content","max-content"],name:"grid-auto-rows"},{longhands:["grid-column-start","grid-column-end"],name:"grid-column"},{keywords:["auto"],name:"grid-column-end"},{longhands:["column-gap"],name:"grid-column-gap"},{keywords:["auto"],name:"grid-column-start"},{longhands:["row-gap","column-gap"],name:"grid-gap"},{longhands:["grid-row-start","grid-row-end"],name:"grid-row"},{keywords:["auto"],name:"grid-row-end"},{longhands:["row-gap"],name:"grid-row-gap"},{keywords:["auto"],name:"grid-row-start"},{longhands:["grid-template-rows","grid-template-columns","grid-template-areas"],name:"grid-template"},{keywords:["none"],name:"grid-template-areas"},{keywords:["none"],name:"grid-template-columns"},{keywords:["none"],name:"grid-template-rows"},{keywords:["auto","fit-content","min-content","max-content"],name:"height"},{inherited:!0,name:"hyphenate-character"},{inherited:!0,keywords:["auto"],name:"hyphenate-limit-chars"},{inherited:!0,keywords:["none","manual","auto"],name:"hyphens"},{inherited:!0,name:"image-orientation"},{inherited:!0,keywords:["auto","optimizespeed","optimizequality","-webkit-optimize-contrast","pixelated"],name:"image-rendering"},{name:"inherits"},{inherited:!1,keywords:["drop","normal","raise"],name:"initial-letter"},{name:"initial-value"},{keywords:["auto"],name:"inline-size"},{longhands:["top","right","bottom","left"],name:"inset"},{longhands:["inset-block-start","inset-block-end"],name:"inset-block"},{name:"inset-block-end"},{name:"inset-block-start"},{longhands:["inset-inline-start","inset-inline-end"],name:"inset-inline"},{name:"inset-inline-end"},{name:"inset-inline-start"},{keywords:["auto","isolate"],name:"isolation"},{name:"justify-content"},{name:"justify-items"},{name:"justify-self"},{keywords:["auto"],name:"left"},{inherited:!0,keywords:["normal"],name:"letter-spacing"},{keywords:["currentcolor"],name:"lighting-color"},{inherited:!0,keywords:["auto","loose","normal","strict","anywhere"],name:"line-break"},{name:"line-gap-override"},{inherited:!0,keywords:["normal"],name:"line-height"},{inherited:!0,longhands:["list-style-position","list-style-image","list-style-type"],name:"list-style"},{inherited:!0,keywords:["none"],name:"list-style-image"},{inherited:!0,keywords:["outside","inside"],name:"list-style-position"},{inherited:!0,keywords:["disc","circle","square","disclosure-open","disclosure-closed","decimal","none"],name:"list-style-type"},{longhands:["margin-top","margin-right","margin-bottom","margin-left"],name:"margin"},{longhands:["margin-block-start","margin-block-end"],name:"margin-block"},{keywords:["auto"],name:"margin-block-end"},{keywords:["auto"],name:"margin-block-start"},{keywords:["auto"],name:"margin-bottom"},{longhands:["margin-inline-start","margin-inline-end"],name:"margin-inline"},{keywords:["auto"],name:"margin-inline-end"},{keywords:["auto"],name:"margin-inline-start"},{keywords:["auto"],name:"margin-left"},{keywords:["auto"],name:"margin-right"},{keywords:["auto"],name:"margin-top"},{inherited:!0,longhands:["marker-start","marker-mid","marker-end"],name:"marker"},{inherited:!0,keywords:["none"],name:"marker-end"},{inherited:!0,keywords:["none"],name:"marker-mid"},{inherited:!0,keywords:["none"],name:"marker-start"},{name:"mask"},{keywords:["luminance","alpha"],name:"mask-type"},{inherited:!0,name:"math-depth"},{inherited:!0,keywords:["normal","compact"],name:"math-shift"},{inherited:!0,keywords:["normal","compact"],name:"math-style"},{keywords:["none"],name:"max-block-size"},{keywords:["none"],name:"max-height"},{keywords:["none"],name:"max-inline-size"},{keywords:["none"],name:"max-width"},{name:"min-block-size"},{name:"min-height"},{name:"min-inline-size"},{name:"min-width"},{keywords:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],name:"mix-blend-mode"},{name:"negative"},{keywords:["fill","contain","cover","none","scale-down"],name:"object-fit"},{name:"object-position"},{keywords:["none"],name:"object-view-box"},{longhands:["offset-position","offset-path","offset-distance","offset-rotate","offset-anchor"],name:"offset"},{keywords:["auto"],name:"offset-anchor"},{name:"offset-distance"},{keywords:["none"],name:"offset-path"},{keywords:["auto","normal"],name:"offset-position"},{keywords:["auto","reverse"],name:"offset-rotate"},{name:"opacity"},{name:"order"},{keywords:["normal","none"],name:"origin-trial-test-property"},{inherited:!0,name:"orphans"},{longhands:["outline-color","outline-style","outline-width"],name:"outline"},{keywords:["currentcolor"],name:"outline-color"},{name:"outline-offset"},{keywords:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"],name:"outline-style"},{keywords:["thin","medium","thick"],name:"outline-width"},{longhands:["overflow-x","overflow-y"],name:"overflow"},{inherited:!1,keywords:["visible","none","auto"],name:"overflow-anchor"},{name:"overflow-block"},{keywords:["border-box","content-box","padding-box"],name:"overflow-clip-margin"},{name:"overflow-inline"},{inherited:!0,keywords:["normal","break-word","anywhere"],name:"overflow-wrap"},{keywords:["visible","hidden","scroll","auto","overlay","clip"],name:"overflow-x"},{keywords:["visible","hidden","scroll","auto","overlay","clip"],name:"overflow-y"},{keywords:["none","auto"],name:"overlay"},{name:"override-colors"},{longhands:["overscroll-behavior-x","overscroll-behavior-y"],name:"overscroll-behavior"},{name:"overscroll-behavior-block"},{name:"overscroll-behavior-inline"},{keywords:["auto","contain","none"],name:"overscroll-behavior-x"},{keywords:["auto","contain","none"],name:"overscroll-behavior-y"},{name:"pad"},{longhands:["padding-top","padding-right","padding-bottom","padding-left"],name:"padding"},{longhands:["padding-block-start","padding-block-end"],name:"padding-block"},{name:"padding-block-end"},{name:"padding-block-start"},{name:"padding-bottom"},{longhands:["padding-inline-start","padding-inline-end"],name:"padding-inline"},{name:"padding-inline-end"},{name:"padding-inline-start"},{name:"padding-left"},{name:"padding-right"},{name:"padding-top"},{keywords:["auto"],name:"page"},{longhands:["break-after"],name:"page-break-after"},{longhands:["break-before"],name:"page-break-before"},{longhands:["break-inside"],name:"page-break-inside"},{name:"page-orientation"},{inherited:!0,keywords:["normal","fill","stroke","markers"],name:"paint-order"},{keywords:["none"],name:"perspective"},{name:"perspective-origin"},{longhands:["align-content","justify-content"],name:"place-content"},{longhands:["align-items","justify-items"],name:"place-items"},{longhands:["align-self","justify-self"],name:"place-self"},{inherited:!0,keywords:["none","auto","stroke","fill","painted","visible","visiblestroke","visiblefill","visiblepainted","bounding-box","all"],name:"pointer-events"},{name:"popover-hide-delay"},{name:"popover-show-delay"},{keywords:["static","relative","absolute","fixed","sticky"],name:"position"},{keywords:["none"],name:"position-fallback"},{name:"prefix"},{inherited:!0,keywords:["auto","none"],name:"quotes"},{name:"r"},{name:"range"},{keywords:["none","both","horizontal","vertical","block","inline"],name:"resize"},{keywords:["auto"],name:"right"},{name:"rotate"},{keywords:["normal"],name:"row-gap"},{inherited:!0,name:"ruby-position"},{keywords:["auto"],name:"rx"},{keywords:["auto"],name:"ry"},{name:"scale"},{keywords:["auto","smooth"],name:"scroll-behavior"},{name:"scroll-customization"},{longhands:["scroll-margin-top","scroll-margin-right","scroll-margin-bottom","scroll-margin-left"],name:"scroll-margin"},{longhands:["scroll-margin-block-start","scroll-margin-block-end"],name:"scroll-margin-block"},{name:"scroll-margin-block-end"},{name:"scroll-margin-block-start"},{name:"scroll-margin-bottom"},{longhands:["scroll-margin-inline-start","scroll-margin-inline-end"],name:"scroll-margin-inline"},{name:"scroll-margin-inline-end"},{name:"scroll-margin-inline-start"},{name:"scroll-margin-left"},{name:"scroll-margin-right"},{name:"scroll-margin-top"},{longhands:["scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left"],name:"scroll-padding"},{longhands:["scroll-padding-block-start","scroll-padding-block-end"],name:"scroll-padding-block"},{keywords:["auto"],name:"scroll-padding-block-end"},{keywords:["auto"],name:"scroll-padding-block-start"},{keywords:["auto"],name:"scroll-padding-bottom"},{longhands:["scroll-padding-inline-start","scroll-padding-inline-end"],name:"scroll-padding-inline"},{keywords:["auto"],name:"scroll-padding-inline-end"},{keywords:["auto"],name:"scroll-padding-inline-start"},{keywords:["auto"],name:"scroll-padding-left"},{keywords:["auto"],name:"scroll-padding-right"},{keywords:["auto"],name:"scroll-padding-top"},{keywords:["none","start","end","center"],name:"scroll-snap-align"},{keywords:["normal","always"],name:"scroll-snap-stop"},{keywords:["none","x","y","block","inline","both","mandatory","proximity"],name:"scroll-snap-type"},{longhands:["scroll-start-block","scroll-start-inline"],name:"scroll-start"},{keywords:["auto","start","end","center","top","bottom","left","right"],name:"scroll-start-block"},{keywords:["auto","start","end","center","top","bottom","left","right"],name:"scroll-start-inline"},{longhands:["scroll-start-target-block","scroll-start-target-inline"],name:"scroll-start-target"},{keywords:["none","auto"],name:"scroll-start-target-block"},{keywords:["none","auto"],name:"scroll-start-target-inline"},{keywords:["none","auto"],name:"scroll-start-target-x"},{keywords:["none","auto"],name:"scroll-start-target-y"},{name:"scroll-start-x"},{name:"scroll-start-y"},{longhands:["scroll-timeline-name","scroll-timeline-axis","scroll-timeline-attachment"],name:"scroll-timeline"},{name:"scroll-timeline-attachment"},{name:"scroll-timeline-axis"},{name:"scroll-timeline-name"},{inherited:!0,keywords:["auto"],name:"scrollbar-color"},{inherited:!1,keywords:["auto","stable","both-edges"],name:"scrollbar-gutter"},{inherited:!1,keywords:["auto","thin","none"],name:"scrollbar-width"},{name:"shape-image-threshold"},{keywords:["none"],name:"shape-margin"},{keywords:["none"],name:"shape-outside"},{inherited:!0,keywords:["auto","optimizespeed","crispedges","geometricprecision"],name:"shape-rendering"},{name:"size"},{name:"size-adjust"},{inherited:!0,keywords:["none","normal","spell-out","digits","literal-punctuation","no-punctuation"],name:"speak"},{name:"speak-as"},{name:"src"},{keywords:["currentcolor"],name:"stop-color"},{name:"stop-opacity"},{inherited:!0,name:"stroke"},{inherited:!0,keywords:["none"],name:"stroke-dasharray"},{inherited:!0,name:"stroke-dashoffset"},{inherited:!0,keywords:["butt","round","square"],name:"stroke-linecap"},{inherited:!0,keywords:["miter","bevel","round"],name:"stroke-linejoin"},{inherited:!0,name:"stroke-miterlimit"},{inherited:!0,name:"stroke-opacity"},{inherited:!0,name:"stroke-width"},{name:"suffix"},{name:"symbols"},{name:"syntax"},{name:"system"},{inherited:!0,name:"tab-size"},{keywords:["auto","fixed"],name:"table-layout"},{inherited:!0,keywords:["left","right","center","justify","-webkit-left","-webkit-right","-webkit-center","start","end"],name:"text-align"},{inherited:!0,keywords:["auto","start","end","left","right","center","justify"],name:"text-align-last"},{inherited:!0,keywords:["start","middle","end"],name:"text-anchor"},{keywords:["none","start","end","both"],name:"text-box-trim"},{inherited:!0,keywords:["none","all"],name:"text-combine-upright"},{longhands:["text-decoration-line","text-decoration-thickness","text-decoration-style","text-decoration-color"],name:"text-decoration"},{keywords:["currentcolor"],name:"text-decoration-color"},{keywords:["none","underline","overline","line-through","blink","spelling-error","grammar-error"],name:"text-decoration-line"},{inherited:!0,keywords:["none","auto"],name:"text-decoration-skip-ink"},{keywords:["solid","double","dotted","dashed","wavy"],name:"text-decoration-style"},{inherited:!0,keywords:["auto","from-font"],name:"text-decoration-thickness"},{inherited:!0,longhands:["text-emphasis-style","text-emphasis-color"],name:"text-emphasis"},{inherited:!0,keywords:["currentcolor"],name:"text-emphasis-color"},{inherited:!0,name:"text-emphasis-position"},{inherited:!0,name:"text-emphasis-style"},{inherited:!0,name:"text-indent"},{inherited:!0,keywords:["sideways","mixed","upright"],name:"text-orientation"},{keywords:["clip","ellipsis"],name:"text-overflow"},{inherited:!0,keywords:["auto","optimizespeed","optimizelegibility","geometricprecision"],name:"text-rendering"},{inherited:!0,keywords:["none"],name:"text-shadow"},{inherited:!0,keywords:["none","auto"],name:"text-size-adjust"},{inherited:!0,keywords:["capitalize","uppercase","lowercase","none","math-auto"],name:"text-transform"},{inherited:!0,keywords:["auto"],name:"text-underline-offset"},{inherited:!0,keywords:["auto","from-font","under","left","right"],name:"text-underline-position"},{inherited:!0,keywords:["wrap","nowrap","balance","pretty"],name:"text-wrap"},{name:"timeline-scope"},{longhands:["toggle-root","toggle-trigger"],name:"toggle"},{keywords:["none"],name:"toggle-group"},{keywords:["none"],name:"toggle-root"},{keywords:["none"],name:"toggle-trigger"},{keywords:["normal"],name:"toggle-visibility"},{keywords:["auto"],name:"top"},{keywords:["auto","none","pan-x","pan-left","pan-right","pan-y","pan-up","pan-down","pinch-zoom","manipulation"],name:"touch-action"},{keywords:["none"],name:"transform"},{keywords:["fill-box","view-box"],name:"transform-box"},{name:"transform-origin"},{keywords:["flat","preserve-3d"],name:"transform-style"},{longhands:["transition-property","transition-duration","transition-timing-function","transition-delay"],name:"transition"},{name:"transition-delay"},{name:"transition-duration"},{keywords:["none"],name:"transition-property"},{keywords:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"],name:"transition-timing-function"},{name:"translate"},{keywords:["normal","embed","bidi-override","isolate","plaintext","isolate-override"],name:"unicode-bidi"},{name:"unicode-range"},{inherited:!0,keywords:["auto","none","text","all","contain"],name:"user-select"},{keywords:["none","non-scaling-stroke"],name:"vector-effect"},{keywords:["baseline","sub","super","text-top","text-bottom","middle"],name:"vertical-align"},{longhands:["view-timeline-name","view-timeline-axis","view-timeline-attachment"],name:"view-timeline"},{name:"view-timeline-attachment"},{name:"view-timeline-axis"},{name:"view-timeline-inset"},{name:"view-timeline-name"},{keywords:["none"],name:"view-transition-name"},{inherited:!0,keywords:["visible","hidden","collapse"],name:"visibility"},{inherited:!0,keywords:["normal","pre","pre-wrap","pre-line","nowrap","break-spaces"],name:"white-space"},{inherited:!0,keywords:["collapse","preserve","preserve-breaks","break-spaces"],name:"white-space-collapse"},{inherited:!0,name:"widows"},{keywords:["auto","fit-content","min-content","max-content"],name:"width"},{keywords:["auto"],name:"will-change"},{inherited:!0,keywords:["normal"],name:"word-boundary-detection"},{inherited:!0,keywords:["normal","break-all","keep-all","break-word"],name:"word-break"},{inherited:!0,keywords:["normal"],name:"word-spacing"},{inherited:!0,keywords:["horizontal-tb","vertical-rl","vertical-lr"],name:"writing-mode"},{name:"x"},{name:"y"},{keywords:["auto"],name:"z-index"},{name:"zoom"}],g={"-webkit-box-align":{values:["stretch","start","center","end","baseline"]},"-webkit-box-decoration-break":{values:["slice","clone"]},"-webkit-box-direction":{values:["normal","reverse"]},"-webkit-box-orient":{values:["horizontal","vertical"]},"-webkit-box-pack":{values:["start","center","end","justify"]},"-webkit-line-break":{values:["auto","loose","normal","strict","after-white-space","anywhere"]},"-webkit-print-color-adjust":{values:["economy","exact"]},"-webkit-rtl-ordering":{values:["logical","visual"]},"-webkit-ruby-position":{values:["before","after"]},"-webkit-text-security":{values:["none","disc","circle","square"]},"-webkit-user-drag":{values:["auto","none","element"]},"-webkit-user-modify":{values:["read-only","read-write","read-write-plaintext-only"]},"accent-color":{values:["auto","currentcolor"]},"alignment-baseline":{values:["auto","baseline","alphabetic","ideographic","middle","central","mathematical","before-edge","text-before-edge","after-edge","text-after-edge","hanging"]},"anchor-default":{values:["none"]},"anchor-name":{values:["none"]},"anchor-scroll":{values:["none"]},"animation-composition":{values:["replace","add","accumulate"]},"animation-direction":{values:["normal","reverse","alternate","alternate-reverse"]},"animation-fill-mode":{values:["none","forwards","backwards","both"]},"animation-iteration-count":{values:["infinite"]},"animation-name":{values:["none"]},"animation-play-state":{values:["running","paused"]},"animation-timeline":{values:["none","auto"]},"animation-timing-function":{values:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"]},"app-region":{values:["none","drag","no-drag"]},"aspect-ratio":{values:["auto"]},"backdrop-filter":{values:["none"]},"backface-visibility":{values:["visible","hidden"]},"background-attachment":{values:["scroll","fixed","local"]},"background-blend-mode":{values:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]},"background-clip":{values:["border-box","padding-box","content-box"]},"background-color":{values:["currentcolor"]},"background-image":{values:["auto","none"]},"background-origin":{values:["border-box","padding-box","content-box"]},"background-size":{values:["auto","cover","contain"]},"baseline-shift":{values:["baseline","sub","super"]},"baseline-source":{values:["auto","first","last"]},"block-size":{values:["auto"]},"border-bottom-color":{values:["currentcolor"]},"border-bottom-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-bottom-width":{values:["thin","medium","thick"]},"border-collapse":{values:["separate","collapse"]},"border-image-repeat":{values:["stretch","repeat","round","space"]},"border-image-source":{values:["none"]},"border-image-width":{values:["auto"]},"border-left-color":{values:["currentcolor"]},"border-left-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-left-width":{values:["thin","medium","thick"]},"border-right-color":{values:["currentcolor"]},"border-right-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-right-width":{values:["thin","medium","thick"]},"border-style":{values:["none"]},"border-top-color":{values:["currentcolor"]},"border-top-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"border-top-width":{values:["thin","medium","thick"]},bottom:{values:["auto"]},"box-shadow":{values:["none"]},"box-sizing":{values:["content-box","border-box"]},"break-after":{values:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"]},"break-before":{values:["auto","avoid","avoid-column","avoid-page","column","left","page","recto","right","verso"]},"break-inside":{values:["auto","avoid","avoid-column","avoid-page"]},"buffered-rendering":{values:["auto","dynamic","static"]},"caption-side":{values:["top","bottom"]},"caret-color":{values:["auto","currentcolor"]},clear:{values:["none","left","right","both","inline-start","inline-end"]},clip:{values:["auto"]},"clip-path":{values:["none"]},"clip-rule":{values:["nonzero","evenodd"]},color:{values:["currentcolor"]},"color-interpolation":{values:["auto","srgb","linearrgb"]},"color-interpolation-filters":{values:["auto","srgb","linearrgb"]},"color-rendering":{values:["auto","optimizespeed","optimizequality"]},"column-count":{values:["auto"]},"column-fill":{values:["balance","auto"]},"column-gap":{values:["normal"]},"column-rule-color":{values:["currentcolor"]},"column-rule-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"column-rule-width":{values:["thin","medium","thick"]},"column-span":{values:["none","all"]},"column-width":{values:["auto"]},contain:{values:["none","strict","content","size","layout","style","paint","inline-size","block-size"]},"contain-intrinsic-height":{values:["auto","none"]},"contain-intrinsic-width":{values:["auto","none"]},"container-name":{values:["none"]},"container-type":{values:["normal","inline-size","size","sticky"]},"content-visibility":{values:["visible","auto","hidden"]},"counter-increment":{values:["none"]},"counter-reset":{values:["none"]},"counter-set":{values:["none"]},cursor:{values:["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","grab","grabbing"]},d:{values:["none"]},direction:{values:["ltr","rtl"]},display:{values:["inline","block","list-item","inline-block","table","inline-table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption","-webkit-box","-webkit-inline-box","flex","inline-flex","grid","inline-grid","contents","flow-root","none","flow","math"]},"dominant-baseline":{values:["auto","alphabetic","ideographic","middle","central","mathematical","hanging","use-script","no-change","reset-size","text-after-edge","text-before-edge"]},"empty-cells":{values:["show","hide"]},"fill-rule":{values:["nonzero","evenodd"]},filter:{values:["none"]},"flex-basis":{values:["auto","fit-content","min-content","max-content","content"]},"flex-direction":{values:["row","row-reverse","column","column-reverse"]},"flex-wrap":{values:["nowrap","wrap","wrap-reverse"]},float:{values:["none","left","right","inline-start","inline-end"]},"flood-color":{values:["currentcolor"]},"font-feature-settings":{values:["normal"]},"font-kerning":{values:["auto","normal","none"]},"font-optical-sizing":{values:["auto","none"]},"font-palette":{values:["normal","light","dark"]},"font-size":{values:["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller","-webkit-xxx-large"]},"font-size-adjust":{values:["none","ex-height","cap-height","ch-width","ic-width"]},"font-stretch":{values:["normal","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"]},"font-style":{values:["normal","italic","oblique"]},"font-synthesis-small-caps":{values:["auto","none"]},"font-synthesis-style":{values:["auto","none"]},"font-synthesis-weight":{values:["auto","none"]},"font-variant-alternates":{values:["normal"]},"font-variant-caps":{values:["normal","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps"]},"font-variant-east-asian":{values:["normal","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"]},"font-variant-ligatures":{values:["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual"]},"font-variant-numeric":{values:["normal","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero"]},"font-variant-position":{values:["normal","sub","super"]},"font-variation-settings":{values:["normal"]},"font-weight":{values:["normal","bold","bolder","lighter"]},"forced-color-adjust":{values:["auto","none","preserve-parent-color"]},"grid-auto-columns":{values:["auto","min-content","max-content"]},"grid-auto-flow":{values:["row","column"]},"grid-auto-rows":{values:["auto","min-content","max-content"]},"grid-column-end":{values:["auto"]},"grid-column-start":{values:["auto"]},"grid-row-end":{values:["auto"]},"grid-row-start":{values:["auto"]},"grid-template-areas":{values:["none"]},"grid-template-columns":{values:["none"]},"grid-template-rows":{values:["none"]},height:{values:["auto","fit-content","min-content","max-content"]},"hyphenate-limit-chars":{values:["auto"]},hyphens:{values:["none","manual","auto"]},"image-rendering":{values:["auto","optimizespeed","optimizequality","-webkit-optimize-contrast","pixelated"]},"initial-letter":{values:["drop","normal","raise"]},"inline-size":{values:["auto"]},isolation:{values:["auto","isolate"]},left:{values:["auto"]},"letter-spacing":{values:["normal"]},"lighting-color":{values:["currentcolor"]},"line-break":{values:["auto","loose","normal","strict","anywhere"]},"line-height":{values:["normal"]},"list-style-image":{values:["none"]},"list-style-position":{values:["outside","inside"]},"list-style-type":{values:["disc","circle","square","disclosure-open","disclosure-closed","decimal","none"]},"margin-block-end":{values:["auto"]},"margin-block-start":{values:["auto"]},"margin-bottom":{values:["auto"]},"margin-inline-end":{values:["auto"]},"margin-inline-start":{values:["auto"]},"margin-left":{values:["auto"]},"margin-right":{values:["auto"]},"margin-top":{values:["auto"]},"marker-end":{values:["none"]},"marker-mid":{values:["none"]},"marker-start":{values:["none"]},"mask-type":{values:["luminance","alpha"]},"math-shift":{values:["normal","compact"]},"math-style":{values:["normal","compact"]},"max-block-size":{values:["none"]},"max-height":{values:["none"]},"max-inline-size":{values:["none"]},"max-width":{values:["none"]},"mix-blend-mode":{values:["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"]},"object-fit":{values:["fill","contain","cover","none","scale-down"]},"object-view-box":{values:["none"]},"offset-anchor":{values:["auto"]},"offset-path":{values:["none"]},"offset-position":{values:["auto","normal"]},"offset-rotate":{values:["auto","reverse"]},"origin-trial-test-property":{values:["normal","none"]},"outline-color":{values:["currentcolor"]},"outline-style":{values:["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"outline-width":{values:["thin","medium","thick"]},"overflow-anchor":{values:["visible","none","auto"]},"overflow-clip-margin":{values:["border-box","content-box","padding-box"]},"overflow-wrap":{values:["normal","break-word","anywhere"]},"overflow-x":{values:["visible","hidden","scroll","auto","overlay","clip"]},"overflow-y":{values:["visible","hidden","scroll","auto","overlay","clip"]},overlay:{values:["none","auto"]},"overscroll-behavior-x":{values:["auto","contain","none"]},"overscroll-behavior-y":{values:["auto","contain","none"]},page:{values:["auto"]},"paint-order":{values:["normal","fill","stroke","markers"]},perspective:{values:["none"]},"pointer-events":{values:["none","auto","stroke","fill","painted","visible","visiblestroke","visiblefill","visiblepainted","bounding-box","all"]},position:{values:["static","relative","absolute","fixed","sticky"]},"position-fallback":{values:["none"]},quotes:{values:["auto","none"]},resize:{values:["none","both","horizontal","vertical","block","inline"]},right:{values:["auto"]},"row-gap":{values:["normal"]},rx:{values:["auto"]},ry:{values:["auto"]},"scroll-behavior":{values:["auto","smooth"]},"scroll-padding-block-end":{values:["auto"]},"scroll-padding-block-start":{values:["auto"]},"scroll-padding-bottom":{values:["auto"]},"scroll-padding-inline-end":{values:["auto"]},"scroll-padding-inline-start":{values:["auto"]},"scroll-padding-left":{values:["auto"]},"scroll-padding-right":{values:["auto"]},"scroll-padding-top":{values:["auto"]},"scroll-snap-align":{values:["none","start","end","center"]},"scroll-snap-stop":{values:["normal","always"]},"scroll-snap-type":{values:["none","x","y","block","inline","both","mandatory","proximity"]},"scroll-start-block":{values:["auto","start","end","center","top","bottom","left","right"]},"scroll-start-inline":{values:["auto","start","end","center","top","bottom","left","right"]},"scroll-start-target-block":{values:["none","auto"]},"scroll-start-target-inline":{values:["none","auto"]},"scroll-start-target-x":{values:["none","auto"]},"scroll-start-target-y":{values:["none","auto"]},"scrollbar-color":{values:["auto"]},"scrollbar-gutter":{values:["auto","stable","both-edges"]},"scrollbar-width":{values:["auto","thin","none"]},"shape-margin":{values:["none"]},"shape-outside":{values:["none"]},"shape-rendering":{values:["auto","optimizespeed","crispedges","geometricprecision"]},speak:{values:["none","normal","spell-out","digits","literal-punctuation","no-punctuation"]},"stop-color":{values:["currentcolor"]},"stroke-dasharray":{values:["none"]},"stroke-linecap":{values:["butt","round","square"]},"stroke-linejoin":{values:["miter","bevel","round"]},"table-layout":{values:["auto","fixed"]},"text-align":{values:["left","right","center","justify","-webkit-left","-webkit-right","-webkit-center","start","end"]},"text-align-last":{values:["auto","start","end","left","right","center","justify"]},"text-anchor":{values:["start","middle","end"]},"text-box-trim":{values:["none","start","end","both"]},"text-combine-upright":{values:["none","all"]},"text-decoration-color":{values:["currentcolor"]},"text-decoration-line":{values:["none","underline","overline","line-through","blink","spelling-error","grammar-error"]},"text-decoration-skip-ink":{values:["none","auto"]},"text-decoration-style":{values:["solid","double","dotted","dashed","wavy"]},"text-decoration-thickness":{values:["auto","from-font"]},"text-emphasis-color":{values:["currentcolor"]},"text-orientation":{values:["sideways","mixed","upright"]},"text-overflow":{values:["clip","ellipsis"]},"text-rendering":{values:["auto","optimizespeed","optimizelegibility","geometricprecision"]},"text-shadow":{values:["none"]},"text-size-adjust":{values:["none","auto"]},"text-transform":{values:["capitalize","uppercase","lowercase","none","math-auto"]},"text-underline-offset":{values:["auto"]},"text-underline-position":{values:["auto","from-font","under","left","right"]},"text-wrap":{values:["wrap","nowrap","balance","pretty"]},"toggle-group":{values:["none"]},"toggle-root":{values:["none"]},"toggle-trigger":{values:["none"]},"toggle-visibility":{values:["normal"]},top:{values:["auto"]},"touch-action":{values:["auto","none","pan-x","pan-left","pan-right","pan-y","pan-up","pan-down","pinch-zoom","manipulation"]},transform:{values:["none"]},"transform-box":{values:["fill-box","view-box"]},"transform-style":{values:["flat","preserve-3d"]},"transition-property":{values:["none"]},"transition-timing-function":{values:["linear","ease","ease-in","ease-out","ease-in-out","jump-both","jump-end","jump-none","jump-start","step-start","step-end"]},"unicode-bidi":{values:["normal","embed","bidi-override","isolate","plaintext","isolate-override"]},"user-select":{values:["auto","none","text","all","contain"]},"vector-effect":{values:["none","non-scaling-stroke"]},"vertical-align":{values:["baseline","sub","super","text-top","text-bottom","middle"]},"view-transition-name":{values:["none"]},visibility:{values:["visible","hidden","collapse"]},"white-space":{values:["normal","pre","pre-wrap","pre-line","nowrap","break-spaces"]},"white-space-collapse":{values:["collapse","preserve","preserve-breaks","break-spaces"]},width:{values:["auto","fit-content","min-content","max-content"]},"will-change":{values:["auto"]},"word-boundary-detection":{values:["normal"]},"word-break":{values:["normal","break-all","keep-all","break-word"]},"word-spacing":{values:["normal"]},"writing-mode":{values:["horizontal-tb","vertical-rl","vertical-lr"]},"z-index":{values:["auto"]}},p=new Map([["-epub-caption-side","caption-side"],["-epub-text-combine","-webkit-text-combine"],["-epub-text-emphasis","text-emphasis"],["-epub-text-emphasis-color","text-emphasis-color"],["-epub-text-emphasis-style","text-emphasis-style"],["-epub-text-orientation","-webkit-text-orientation"],["-epub-text-transform","text-transform"],["-epub-word-break","word-break"],["-epub-writing-mode","-webkit-writing-mode"],["-webkit-align-content","align-content"],["-webkit-align-items","align-items"],["-webkit-align-self","align-self"],["-webkit-alternative-animation-delay","-alternative-animation-delay"],["-webkit-alternative-animation-with-delay-start-end","-alternative-animation-with-delay-start-end"],["-webkit-alternative-animation-with-timeline","-alternative-animation-with-timeline"],["-webkit-animation","animation"],["-webkit-animation-delay","animation-delay"],["-webkit-animation-direction","animation-direction"],["-webkit-animation-duration","animation-duration"],["-webkit-animation-fill-mode","animation-fill-mode"],["-webkit-animation-iteration-count","animation-iteration-count"],["-webkit-animation-name","animation-name"],["-webkit-animation-play-state","animation-play-state"],["-webkit-animation-timing-function","animation-timing-function"],["-webkit-app-region","app-region"],["-webkit-appearance","appearance"],["-webkit-backface-visibility","backface-visibility"],["-webkit-background-clip","background-clip"],["-webkit-background-origin","background-origin"],["-webkit-background-size","background-size"],["-webkit-border-after","border-block-end"],["-webkit-border-after-color","border-block-end-color"],["-webkit-border-after-style","border-block-end-style"],["-webkit-border-after-width","border-block-end-width"],["-webkit-border-before","border-block-start"],["-webkit-border-before-color","border-block-start-color"],["-webkit-border-before-style","border-block-start-style"],["-webkit-border-before-width","border-block-start-width"],["-webkit-border-bottom-left-radius","border-bottom-left-radius"],["-webkit-border-bottom-right-radius","border-bottom-right-radius"],["-webkit-border-end","border-inline-end"],["-webkit-border-end-color","border-inline-end-color"],["-webkit-border-end-style","border-inline-end-style"],["-webkit-border-end-width","border-inline-end-width"],["-webkit-border-radius","border-radius"],["-webkit-border-start","border-inline-start"],["-webkit-border-start-color","border-inline-start-color"],["-webkit-border-start-style","border-inline-start-style"],["-webkit-border-start-width","border-inline-start-width"],["-webkit-border-top-left-radius","border-top-left-radius"],["-webkit-border-top-right-radius","border-top-right-radius"],["-webkit-box-shadow","box-shadow"],["-webkit-box-sizing","box-sizing"],["-webkit-clip-path","clip-path"],["-webkit-column-count","column-count"],["-webkit-column-gap","column-gap"],["-webkit-column-rule","column-rule"],["-webkit-column-rule-color","column-rule-color"],["-webkit-column-rule-style","column-rule-style"],["-webkit-column-rule-width","column-rule-width"],["-webkit-column-span","column-span"],["-webkit-column-width","column-width"],["-webkit-columns","columns"],["-webkit-filter","filter"],["-webkit-flex","flex"],["-webkit-flex-basis","flex-basis"],["-webkit-flex-direction","flex-direction"],["-webkit-flex-flow","flex-flow"],["-webkit-flex-grow","flex-grow"],["-webkit-flex-shrink","flex-shrink"],["-webkit-flex-wrap","flex-wrap"],["-webkit-font-feature-settings","font-feature-settings"],["-webkit-hyphenate-character","hyphenate-character"],["-webkit-justify-content","justify-content"],["-webkit-logical-height","block-size"],["-webkit-logical-width","inline-size"],["-webkit-margin-after","margin-block-end"],["-webkit-margin-before","margin-block-start"],["-webkit-margin-end","margin-inline-end"],["-webkit-margin-start","margin-inline-start"],["-webkit-max-logical-height","max-block-size"],["-webkit-max-logical-width","max-inline-size"],["-webkit-min-logical-height","min-block-size"],["-webkit-min-logical-width","min-inline-size"],["-webkit-opacity","opacity"],["-webkit-order","order"],["-webkit-padding-after","padding-block-end"],["-webkit-padding-before","padding-block-start"],["-webkit-padding-end","padding-inline-end"],["-webkit-padding-start","padding-inline-start"],["-webkit-perspective","perspective"],["-webkit-perspective-origin","perspective-origin"],["-webkit-shape-image-threshold","shape-image-threshold"],["-webkit-shape-margin","shape-margin"],["-webkit-shape-outside","shape-outside"],["-webkit-text-emphasis","text-emphasis"],["-webkit-text-emphasis-color","text-emphasis-color"],["-webkit-text-emphasis-position","text-emphasis-position"],["-webkit-text-emphasis-style","text-emphasis-style"],["-webkit-text-size-adjust","text-size-adjust"],["-webkit-transform","transform"],["-webkit-transform-origin","transform-origin"],["-webkit-transform-style","transform-style"],["-webkit-transition","transition"],["-webkit-transition-delay","transition-delay"],["-webkit-transition-duration","transition-duration"],["-webkit-transition-property","transition-property"],["-webkit-transition-timing-function","transition-timing-function"],["-webkit-user-select","user-select"],["word-wrap","overflow-wrap"]]);class m{#t;#n;#r;#s;#i;#a;#o;#l;#d;#c;constructor(e,n){this.#t=[],this.#n=new Map,this.#r=new Map,this.#s=new Set,this.#i=new Set,this.#a=new Map,this.#o=n;for(let t=0;tCSS.supports(e,t))).sort(m.sortPrefixesToEnd).map((t=>`${e}: ${t}`));this.isSVGProperty(e)||this.#d.push(...t),this.#c.push(...t)}}static sortPrefixesToEnd(e,t){const n=e.startsWith("-webkit-"),r=t.startsWith("-webkit-");return n&&!r?1:!n&&r||et?1:0}allProperties(){return this.#t}aliasesFor(){return this.#o}nameValuePresets(e){return e?this.#c:this.#d}isSVGProperty(e){return e=e.toLowerCase(),this.#i.has(e)}getLonghands(e){return this.#n.get(e)||null}getShorthands(e){return this.#r.get(e)||null}isColorAwareProperty(e){return R.has(e.toLowerCase())||this.isCustomProperty(e.toLowerCase())}isFontFamilyProperty(e){return"font-family"===e.toLowerCase()}isAngleAwareProperty(e){const t=e.toLowerCase();return R.has(t)||x.has(t)}isGridAreaDefiningProperty(e){return"grid"===(e=e.toLowerCase())||"grid-template"===e||"grid-template-areas"===e}isLengthProperty(e){return"line-height"!==(e=e.toLowerCase())&&(w.has(e)||e.startsWith("margin")||e.startsWith("padding")||-1!==e.indexOf("width")||-1!==e.indexOf("height"))}isBezierAwareProperty(e){return e=e.toLowerCase(),C.has(e)||this.isCustomProperty(e)}isFontAwareProperty(e){return e=e.toLowerCase(),T.has(e)||this.isCustomProperty(e)}isCustomProperty(e){return e.startsWith("--")}isShadowProperty(e){return"box-shadow"===(e=e.toLowerCase())||"text-shadow"===e||"-webkit-box-shadow"===e}isStringProperty(e){return"content"===(e=e.toLowerCase())}canonicalPropertyName(e){if(this.isCustomProperty(e))return e;e=e.toLowerCase();const t=this.#o.get(e);if(t)return t;if(!e||e.length<9||"-"!==e.charAt(0))return e;const n=e.match(/(?:-webkit-)(.+)/);return n&&this.#l.has(n[1])?n[1]:e}isCSSPropertyName(e){return!!((e=e.toLowerCase()).startsWith("--")&&e.length>2||e.startsWith("-moz-")||e.startsWith("-ms-")||e.startsWith("-o-")||e.startsWith("-webkit-"))||this.#l.has(e)}isPropertyInherited(e){return(e=e.toLowerCase()).startsWith("--")||this.#s.has(this.canonicalPropertyName(e))||this.#s.has(e)}specificPropertyValues(e){const t=e.replace(/^-webkit-/,""),n=this.#a;let r=n.get(e)||n.get(t);if(!r){r=[];for(const t of L)CSS.supports(e,t)&&r.push(t);n.set(e,r)}return r}getPropertyValues(t){const n=["inherit","initial","revert","unset"];if(t=t.toLowerCase(),n.push(...this.specificPropertyValues(t)),this.isColorAwareProperty(t)){n.push("currentColor");for(const t of e.Color.Nicknames.keys())n.push(t)}return n.sort(m.sortPrefixesToEnd)}propertyUsageWeight(e){return P.get(e)||P.get(this.canonicalPropertyName(e))||0}getValuePreset(e,t){const n=S.get(e);let r=n?n.get(t):null;if(!r)return null;let s=r.length,i=r.length;return r&&(s=r.indexOf("|"),i=r.lastIndexOf("|"),i=s===i?i:i-1,r=r.replace(/\|/g,"")),{text:r,startColumn:s,endColumn:i}}isHighlightPseudoType(e){return"highlight"===e||"selection"===e||"target-text"===e||"grammar-error"===e||"spelling-error"===e}}const f=/(var\(\s*--.*?\))/g,b=/((?:\[[\w\- ]+\]\s*)*(?:"[^"]+"|'[^']+'))[^'"\[]*\[?[^'"\[]*/;let y=null;function v(){if(!y){y=new m(u,p)}return y}const I=new Map([["linear-gradient","linear-gradient(|45deg, black, transparent|)"],["radial-gradient","radial-gradient(|black, transparent|)"],["repeating-linear-gradient","repeating-linear-gradient(|45deg, black, transparent 100px|)"],["repeating-radial-gradient","repeating-radial-gradient(|black, transparent 100px|)"],["url","url(||)"]]),k=new Map([["blur","blur(|1px|)"],["brightness","brightness(|0.5|)"],["contrast","contrast(|0.5|)"],["drop-shadow","drop-shadow(|2px 4px 6px black|)"],["grayscale","grayscale(|1|)"],["hue-rotate","hue-rotate(|45deg|)"],["invert","invert(|1|)"],["opacity","opacity(|0.5|)"],["saturate","saturate(|0.5|)"],["sepia","sepia(|1|)"],["url","url(||)"]]),S=new Map([["filter",k],["backdrop-filter",k],["background",I],["background-image",I],["-webkit-mask-image",I],["transform",new Map([["scale","scale(|1.5|)"],["scaleX","scaleX(|1.5|)"],["scaleY","scaleY(|1.5|)"],["scale3d","scale3d(|1.5, 1.5, 1.5|)"],["rotate","rotate(|45deg|)"],["rotateX","rotateX(|45deg|)"],["rotateY","rotateY(|45deg|)"],["rotateZ","rotateZ(|45deg|)"],["rotate3d","rotate3d(|1, 1, 1, 45deg|)"],["skew","skew(|10deg, 10deg|)"],["skewX","skewX(|10deg|)"],["skewY","skewY(|10deg|)"],["translate","translate(|10px, 10px|)"],["translateX","translateX(|10px|)"],["translateY","translateY(|10px|)"],["translateZ","translateZ(|10px|)"],["translate3d","translate3d(|10px, 10px, 10px|)"],["matrix","matrix(|1, 0, 0, 1, 0, 0|)"],["matrix3d","matrix3d(|1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1|)"],["perspective","perspective(|10px|)"]])]]),w=new Set(["background-position","border-spacing","bottom","font-size","height","left","letter-spacing","max-height","max-width","min-height","min-width","right","text-indent","top","width","word-spacing","grid-row-gap","grid-column-gap","row-gap"]),C=new Set(["animation","animation-timing-function","transition","transition-timing-function","-webkit-animation","-webkit-animation-timing-function","-webkit-transition","-webkit-transition-timing-function"]),T=new Set(["font-size","line-height","font-weight","font-family","letter-spacing"]),R=new Set(["accent-color","background","background-color","background-image","border","border-color","border-image","border-image-source","border-bottom","border-bottom-color","border-left","border-left-color","border-right","border-right-color","border-top","border-top-color","box-shadow","caret-color","color","column-rule","column-rule-color","content","fill","list-style-image","outline","outline-color","stop-color","stroke","text-decoration-color","text-shadow","-webkit-border-after","-webkit-border-after-color","-webkit-border-before","-webkit-border-before-color","-webkit-border-end","-webkit-border-end-color","-webkit-border-start","-webkit-border-start-color","-webkit-box-reflect","-webkit-box-shadow","-webkit-column-rule-color","-webkit-mask","-webkit-mask-box-image","-webkit-mask-box-image-source","-webkit-mask-image","-webkit-tap-highlight-color","-webkit-text-decoration-color","-webkit-text-emphasis","-webkit-text-emphasis-color","-webkit-text-fill-color","-webkit-text-stroke","-webkit-text-stroke-color"]),x=new Set(["-webkit-border-image","transform","-webkit-transform","rotate","filter","-webkit-filter","backdrop-filter","offset","offset-rotate","font-style"]),M={"background-repeat":{values:["repeat","repeat-x","repeat-y","no-repeat","space","round"]},content:{values:["normal","close-quote","no-close-quote","no-open-quote","open-quote"]},"baseline-shift":{values:["baseline"]},"max-height":{values:["min-content","max-content","-webkit-fill-available","fit-content"]},color:{values:["black"]},"background-color":{values:["white"]},"box-shadow":{values:["inset"]},"text-shadow":{values:["0 0 black"]},"-webkit-writing-mode":{values:["horizontal-tb","vertical-rl","vertical-lr"]},"writing-mode":{values:["lr","rl","tb","lr-tb","rl-tb","tb-rl"]},"page-break-inside":{values:["avoid"]},cursor:{values:["-webkit-zoom-in","-webkit-zoom-out","-webkit-grab","-webkit-grabbing"]},"border-width":{values:["medium","thick","thin"]},"border-style":{values:["hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"]},size:{values:["a3","a4","a5","b4","b5","landscape","ledger","legal","letter","portrait"]},overflow:{values:["hidden","visible","overlay","scroll"]},"overscroll-behavior":{values:["contain"]},"text-rendering":{values:["optimizeSpeed","optimizeLegibility","geometricPrecision"]},"text-align":{values:["-webkit-auto","-webkit-match-parent"]},"clip-path":{values:["circle","ellipse","inset","polygon","url"]},"color-interpolation":{values:["sRGB","linearRGB"]},"word-wrap":{values:["normal","break-word"]},"font-weight":{values:["100","200","300","400","500","600","700","800","900"]},"-webkit-text-emphasis":{values:["circle","filled","open","dot","double-circle","triangle","sesame"]},"color-rendering":{values:["optimizeSpeed","optimizeQuality"]},"-webkit-text-combine":{values:["horizontal"]},"text-orientation":{values:["sideways-right"]},outline:{values:["inset","groove","ridge","outset","dotted","dashed","solid","double","medium","thick","thin"]},font:{values:["caption","icon","menu","message-box","small-caption","-webkit-mini-control","-webkit-small-control","-webkit-control","status-bar"]},"dominant-baseline":{values:["text-before-edge","text-after-edge","use-script","no-change","reset-size"]},"-webkit-text-emphasis-position":{values:["over","under"]},"alignment-baseline":{values:["before-edge","after-edge","text-before-edge","text-after-edge","hanging"]},"page-break-before":{values:["left","right","always","avoid"]},"border-image":{values:["repeat","stretch","space","round"]},"text-decoration":{values:["blink","line-through","overline","underline","wavy","double","solid","dashed","dotted"]},"font-family":{values:["serif","sans-serif","cursive","fantasy","monospace","system-ui","emoji","math","fangsong","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","-webkit-body"]},zoom:{values:["normal"]},"max-width":{values:["min-content","max-content","-webkit-fill-available","fit-content"]},"-webkit-font-smoothing":{values:["antialiased","subpixel-antialiased"]},border:{values:["hidden","inset","groove","ridge","outset","dotted","dashed","solid","double","medium","thick","thin"]},"font-variant":{values:["small-caps","normal","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby"]},"vertical-align":{values:["top","bottom","-webkit-baseline-middle"]},"page-break-after":{values:["left","right","always","avoid"]},"-webkit-text-emphasis-style":{values:["circle","filled","open","dot","double-circle","triangle","sesame"]},transform:{values:["scale","scaleX","scaleY","scale3d","rotate","rotateX","rotateY","rotateZ","rotate3d","skew","skewX","skewY","translate","translateX","translateY","translateZ","translate3d","matrix","matrix3d","perspective"]},"align-content":{values:["normal","baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end"]},"justify-content":{values:["normal","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right"]},"place-content":{values:["normal","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","baseline"]},"align-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"justify-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","legacy"]},"place-items":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"align-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"justify-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right"]},"place-self":{values:["normal","stretch","baseline","center","start","end","self-start","self-end","flex-start","flex-end"]},"perspective-origin":{values:["left","center","right","top","bottom"]},"transform-origin":{values:["left","center","right","top","bottom"]},"transition-timing-function":{values:["cubic-bezier","steps"]},"animation-timing-function":{values:["cubic-bezier","steps"]},"-webkit-backface-visibility":{values:["visible","hidden"]},"-webkit-column-break-after":{values:["always","avoid"]},"-webkit-column-break-before":{values:["always","avoid"]},"-webkit-column-break-inside":{values:["avoid"]},"-webkit-column-span":{values:["all"]},"-webkit-column-gap":{values:["normal"]},filter:{values:["url","blur","brightness","contrast","drop-shadow","grayscale","hue-rotate","invert","opacity","saturate","sepia"]},"backdrop-filter":{values:["url","blur","brightness","contrast","drop-shadow","grayscale","hue-rotate","invert","opacity","saturate","sepia"]},"mix-blend-mode":{values:["unset"]},"background-blend-mode":{values:["unset"]},"grid-template-columns":{values:["min-content","max-content"]},"grid-template-rows":{values:["min-content","max-content"]},"grid-auto-flow":{values:["dense"]},background:{values:["repeat","repeat-x","repeat-y","no-repeat","top","bottom","left","right","center","fixed","local","scroll","space","round","border-box","content-box","padding-box","linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"background-image":{values:["linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"background-position":{values:["top","bottom","left","right","center"]},"background-position-x":{values:["left","right","center"]},"background-position-y":{values:["top","bottom","center"]},"background-repeat-x":{values:["repeat","no-repeat"]},"background-repeat-y":{values:["repeat","no-repeat"]},"border-bottom":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-left":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-right":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"border-top":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"buffered-rendering":{values:["static","dynamic"]},"color-interpolation-filters":{values:["srgb","linearrgb"]},"column-rule":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"flex-flow":{values:["nowrap","row","row-reverse","column","column-reverse","wrap","wrap-reverse"]},height:{values:["-webkit-fill-available"]},"inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"list-style":{values:["outside","inside","disc","circle","square","decimal","decimal-leading-zero","arabic-indic","bengali","cambodian","khmer","devanagari","gujarati","gurmukhi","kannada","lao","malayalam","mongolian","myanmar","oriya","persian","urdu","telugu","tibetan","thai","lower-roman","upper-roman","lower-greek","lower-alpha","lower-latin","upper-alpha","upper-latin","cjk-earthly-branch","cjk-heavenly-stem","ethiopic-halehame","ethiopic-halehame-am","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","hangul","hangul-consonant","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","hebrew","armenian","lower-armenian","upper-armenian","georgian","cjk-ideographic","simp-chinese-formal","simp-chinese-informal","trad-chinese-formal","trad-chinese-informal","hiragana","katakana","hiragana-iroha","katakana-iroha"]},"max-block-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"max-inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-block-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-inline-size":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"min-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"object-position":{values:["top","bottom","left","right","center"]},"shape-outside":{values:["border-box","content-box","padding-box","margin-box"]},"-webkit-appearance":{values:["checkbox","radio","push-button","square-button","button","inner-spin-button","listbox","media-slider","media-sliderthumb","media-volume-slider","media-volume-sliderthumb","menulist","menulist-button","meter","progress-bar","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","searchfield","searchfield-cancel-button","textfield","textarea"]},"-webkit-border-after":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-after-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-after-width":{values:["medium","thick","thin"]},"-webkit-border-before":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-before-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-before-width":{values:["medium","thick","thin"]},"-webkit-border-end":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-end-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-end-width":{values:["medium","thick","thin"]},"-webkit-border-start":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double","medium","thick","thin"]},"-webkit-border-start-style":{values:["hidden","inset","groove","outset","ridge","dotted","dashed","solid","double"]},"-webkit-border-start-width":{values:["medium","thick","thin"]},"-webkit-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-margin-collapse":{values:["collapse","separate","discard"]},"-webkit-mask-box-image":{values:["repeat","stretch","space","round"]},"-webkit-mask-box-image-repeat":{values:["repeat","stretch","space","round"]},"-webkit-mask-clip":{values:["text","border","border-box","content","content-box","padding","padding-box"]},"-webkit-mask-composite":{values:["clear","copy","source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","xor","plus-lighter"]},"-webkit-mask-image":{values:["linear-gradient","radial-gradient","repeating-linear-gradient","repeating-radial-gradient","url"]},"-webkit-mask-origin":{values:["border","border-box","content","content-box","padding","padding-box"]},"-webkit-mask-position":{values:["top","bottom","left","right","center"]},"-webkit-mask-position-x":{values:["left","right","center"]},"-webkit-mask-position-y":{values:["top","bottom","center"]},"-webkit-mask-repeat":{values:["repeat","repeat-x","repeat-y","no-repeat","space","round"]},"-webkit-mask-size":{values:["contain","cover"]},"-webkit-max-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-max-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-min-logical-height":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-min-logical-width":{values:["-webkit-fill-available","min-content","max-content","fit-content"]},"-webkit-perspective-origin-x":{values:["left","right","center"]},"-webkit-perspective-origin-y":{values:["top","bottom","center"]},"-webkit-text-decorations-in-effect":{values:["blink","line-through","overline","underline"]},"-webkit-text-stroke":{values:["medium","thick","thin"]},"-webkit-text-stroke-width":{values:["medium","thick","thin"]},"-webkit-transform-origin-x":{values:["left","right","center"]},"-webkit-transform-origin-y":{values:["top","bottom","center"]},width:{values:["-webkit-fill-available"]}},P=new Map([["align-content",57],["align-items",129],["align-self",55],["animation",175],["animation-delay",114],["animation-direction",113],["animation-duration",137],["animation-fill-mode",132],["animation-iteration-count",124],["animation-name",139],["animation-play-state",104],["animation-timing-function",141],["backface-visibility",123],["background",260],["background-attachment",119],["background-clip",165],["background-color",259],["background-image",246],["background-origin",107],["background-position",237],["background-position-x",108],["background-position-y",93],["background-repeat",234],["background-size",203],["border",263],["border-bottom",233],["border-bottom-color",190],["border-bottom-left-radius",186],["border-bottom-right-radius",185],["border-bottom-style",150],["border-bottom-width",179],["border-collapse",209],["border-color",226],["border-image",89],["border-image-outset",50],["border-image-repeat",49],["border-image-slice",58],["border-image-source",32],["border-image-width",52],["border-left",221],["border-left-color",174],["border-left-style",142],["border-left-width",172],["border-radius",224],["border-right",223],["border-right-color",182],["border-right-style",130],["border-right-width",178],["border-spacing",198],["border-style",206],["border-top",231],["border-top-color",192],["border-top-left-radius",187],["border-top-right-radius",189],["border-top-style",152],["border-top-width",180],["border-width",214],["bottom",227],["box-shadow",213],["box-sizing",216],["caption-side",96],["clear",229],["clip",173],["clip-rule",5],["color",256],["content",219],["counter-increment",111],["counter-reset",110],["cursor",250],["direction",176],["display",262],["empty-cells",99],["fill",140],["fill-opacity",82],["fill-rule",22],["filter",160],["flex",133],["flex-basis",66],["flex-direction",85],["flex-flow",94],["flex-grow",112],["flex-shrink",61],["flex-wrap",68],["float",252],["font",211],["font-family",254],["font-kerning",18],["font-size",264],["font-stretch",77],["font-style",220],["font-variant",161],["font-weight",257],["height",266],["image-rendering",90],["justify-content",127],["left",248],["letter-spacing",188],["line-height",244],["list-style",215],["list-style-image",145],["list-style-position",149],["list-style-type",199],["margin",267],["margin-bottom",241],["margin-left",243],["margin-right",238],["margin-top",253],["mask",20],["max-height",205],["max-width",225],["min-height",217],["min-width",218],["object-fit",33],["opacity",251],["order",117],["orphans",146],["outline",222],["outline-color",153],["outline-offset",147],["outline-style",151],["outline-width",148],["overflow",255],["overflow-wrap",105],["overflow-x",184],["overflow-y",196],["padding",265],["padding-bottom",230],["padding-left",235],["padding-right",232],["padding-top",240],["page",8],["page-break-after",120],["page-break-before",69],["page-break-inside",121],["perspective",92],["perspective-origin",103],["pointer-events",183],["position",261],["quotes",158],["resize",168],["right",245],["shape-rendering",38],["size",64],["speak",118],["src",170],["stop-color",42],["stop-opacity",31],["stroke",98],["stroke-dasharray",36],["stroke-dashoffset",3],["stroke-linecap",30],["stroke-linejoin",21],["stroke-miterlimit",12],["stroke-opacity",34],["stroke-width",87],["table-layout",171],["tab-size",46],["text-align",260],["text-anchor",35],["text-decoration",247],["text-indent",207],["text-overflow",204],["text-rendering",155],["text-shadow",208],["text-transform",202],["top",258],["touch-action",80],["transform",181],["transform-origin",162],["transform-style",86],["transition",193],["transition-delay",134],["transition-duration",135],["transition-property",131],["transition-timing-function",122],["unicode-bidi",156],["unicode-range",136],["vertical-align",236],["visibility",242],["-webkit-appearance",191],["-webkit-backface-visibility",154],["-webkit-background-clip",164],["-webkit-background-origin",40],["-webkit-background-size",163],["-webkit-border-end",9],["-webkit-border-horizontal-spacing",81],["-webkit-border-image",75],["-webkit-border-radius",212],["-webkit-border-start",10],["-webkit-border-start-color",16],["-webkit-border-start-width",13],["-webkit-border-vertical-spacing",43],["-webkit-box-align",101],["-webkit-box-direction",51],["-webkit-box-flex",128],["-webkit-box-ordinal-group",91],["-webkit-box-orient",144],["-webkit-box-pack",106],["-webkit-box-reflect",39],["-webkit-box-shadow",210],["-webkit-column-break-inside",60],["-webkit-column-count",84],["-webkit-column-gap",76],["-webkit-column-rule",25],["-webkit-column-rule-color",23],["-webkit-columns",44],["-webkit-column-span",29],["-webkit-column-width",47],["-webkit-filter",159],["-webkit-font-feature-settings",59],["-webkit-font-smoothing",177],["-webkit-highlight",1],["-webkit-line-break",45],["-webkit-line-clamp",126],["-webkit-margin-after",67],["-webkit-margin-before",70],["-webkit-margin-collapse",14],["-webkit-margin-end",65],["-webkit-margin-start",100],["-webkit-margin-top-collapse",78],["-webkit-mask",19],["-webkit-mask-box-image",72],["-webkit-mask-image",88],["-webkit-mask-position",54],["-webkit-mask-repeat",63],["-webkit-mask-size",79],["-webkit-padding-after",15],["-webkit-padding-before",28],["-webkit-padding-end",48],["-webkit-padding-start",73],["-webkit-print-color-adjust",83],["-webkit-rtl-ordering",7],["-webkit-tap-highlight-color",169],["-webkit-text-emphasis-color",11],["-webkit-text-fill-color",71],["-webkit-text-security",17],["-webkit-text-stroke",56],["-webkit-text-stroke-color",37],["-webkit-text-stroke-width",53],["-webkit-user-drag",95],["-webkit-user-modify",62],["-webkit-user-select",194],["-webkit-writing-mode",4],["white-space",228],["widows",115],["width",268],["will-change",74],["word-break",166],["word-spacing",157],["word-wrap",197],["writing-mode",41],["z-index",239],["zoom",200]]),L=["auto","none"];var E=Object.freeze({__proto__:null,CSSMetadata:m,VariableRegex:f,CustomVariableRegex:/(var\(*--[\w\d]+-([\w]+-[\w]+)\))/g,URLRegex:/url\(\s*('.+?'|".+?"|[^)]+)\s*\)/g,GridAreaRowRegex:b,cssMetadata:v});class A{callFrame;callUID;self;total;id;parent;children;functionName;depth;deoptReason;#h;constructor(e,t){this.callFrame=e,this.callUID=`${e.functionName}@${e.scriptId}:${e.lineNumber}:${e.columnNumber}`,this.self=0,this.total=0,this.id=0,this.functionName=e.functionName,this.parent=null,this.children=[],this.#h=t}get scriptId(){return String(this.callFrame.scriptId)}get url(){return this.callFrame.url}get lineNumber(){return this.callFrame.lineNumber}get columnNumber(){return this.callFrame.columnNumber}setFunctionName(e){null!==e&&(this.functionName=e)}target(){return this.#h}}class O{#e;root;total;maxDepth;constructor(e){this.#e=e||null}initialize(e){this.root=e,this.assignDepthsAndParents(),this.total=this.calculateTotals(this.root)}assignDepthsAndParents(){const e=this.root;e.depth=-1,e.parent=null,this.maxDepth=0;const t=[e];for(;t.length;){const e=t.pop(),n=e.depth+1;n>this.maxDepth&&(this.maxDepth=n);const r=e.children;for(const s of r)s.depth=n,s.parent=e,s.children.length&&t.push(s)}}calculateTotals(e){const t=[e],n=[];for(;t.length;){const e=t.pop();e.total=e.self,n.push(e),t.push(...e.children)}for(;n.length>1;){const e=n.pop();e.parent&&(e.parent.total+=e.total)}return e.total}target(){return this.#e}}var N=Object.freeze({__proto__:null,ProfileNode:A,ProfileTreeModel:O});class F{#u;#g;#p;#m;#f;#b;#y;constructor(e,t,n,r){this.#u=e,this.#g=t,this.#p=n,this.#m={},this.#f=0,this.#b=r||"Medium",this.#y=null}static fromProtocolCookie(e){const t=new F(e.name,e.value,null,e.priority);return t.addAttribute("domain",e.domain),t.addAttribute("path",e.path),e.expires&&t.addAttribute("expires",1e3*e.expires),e.httpOnly&&t.addAttribute("httpOnly"),e.secure&&t.addAttribute("secure"),e.sameSite&&t.addAttribute("sameSite",e.sameSite),"sourcePort"in e&&t.addAttribute("sourcePort",e.sourcePort),"sourceScheme"in e&&t.addAttribute("sourceScheme",e.sourceScheme),"partitionKey"in e&&t.addAttribute("partitionKey",e.partitionKey),"partitionKeyOpaque"in e&&t.addAttribute("partitionKey",""),t.setSize(e.size),t}key(){return(this.domain()||"-")+" "+this.name()+" "+(this.path()||"-")}name(){return this.#u}value(){return this.#g}type(){return this.#p}httpOnly(){return"httponly"in this.#m}secure(){return"secure"in this.#m}sameSite(){return this.#m.samesite}partitionKey(){return this.#m.partitionkey}setPartitionKey(e){this.addAttribute("partitionKey",e)}partitionKeyOpaque(){return""===this.#m.partitionkey}setPartitionKeyOpaque(){this.addAttribute("partitionKey","")}priority(){return this.#b}session(){return!("expires"in this.#m||"max-age"in this.#m)}path(){return this.#m.path}domain(){return this.#m.domain}expires(){return this.#m.expires}maxAge(){return this.#m["max-age"]}sourcePort(){return this.#m.sourceport}sourceScheme(){return this.#m.sourcescheme}size(){return this.#f}url(){if(!this.domain()||!this.path())return null;let e="";const t=this.sourcePort();return t&&80!==t&&443!==t&&(e=`:${this.sourcePort()}`),(this.secure()?"https://":"http://")+this.domain()+e+this.path()}setSize(e){this.#f=e}expiresDate(e){return this.maxAge()?new Date(e.getTime()+1e3*this.maxAge()):this.expires()?new Date(this.expires()):null}addAttribute(e,t){const n=e.toLowerCase();if("priority"===n)this.#b=t;else this.#m[n]=t}setCookieLine(e){this.#y=e}getCookieLine(){return this.#y}matchesSecurityOrigin(e){const t=new URL(e).hostname;return F.isDomainMatch(this.domain(),t)}static isDomainMatch(e,t){return t===e||!(!e||"."!==e[0])&&(e.substr(1)===t||t.length>e.length&&t.endsWith(e))}}var B,D;!function(e){e[e.Request=0]="Request",e[e.Response=1]="Response"}(B||(B={})),function(e){e.Name="name",e.Value="value",e.Size="size",e.Domain="domain",e.Path="path",e.Expires="expires",e.HttpOnly="httpOnly",e.Secure="secure",e.SameSite="sameSite",e.SourceScheme="sourceScheme",e.SourcePort="sourcePort",e.Priority="priority",e.PartitionKey="partitionKey"}(D||(D={}));var U=Object.freeze({__proto__:null,Cookie:F,get Type(){return B},get Attributes(){return D}});class H{#v;#I;#k;#S;#w;#C;#T;constructor(e){e&&(this.#v=e.toLowerCase().replace(/^\./,"")),this.#I=[],this.#S=0}static parseSetCookie(e,t){return new H(t).parseSetCookie(e)}cookies(){return this.#I}parseSetCookie(e){if(!this.initialize(e))return null;for(let e=this.extractKeyValue();e;e=this.extractKeyValue())this.#w?this.#w.addAttribute(e.key,e.value):this.addCookie(e,B.Response),this.advanceAndCheckCookieDelimiter()&&this.flushCookie();return this.flushCookie(),this.#I}initialize(e){return this.#k=e,"string"==typeof e&&(this.#I=[],this.#w=null,this.#C="",this.#S=this.#k.length,!0)}flushCookie(){this.#w&&(this.#w.setSize(this.#S-this.#k.length-this.#T),this.#w.setCookieLine(this.#C.replace("\n",""))),this.#w=null,this.#C=""}extractKeyValue(){if(!this.#k||!this.#k.length)return null;const e=/^[ \t]*([^=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this.#k);if(!e)return console.error("Failed parsing cookie header before: "+this.#k),null;const t=new q(e[1]&&e[1].trim(),e[2]&&e[2].trim(),this.#S-this.#k.length);return this.#C+=e[0],this.#k=this.#k.slice(e[0].length),t}advanceAndCheckCookieDelimiter(){if(!this.#k)return!1;const e=/^\s*[\n;]\s*/.exec(this.#k);return!!e&&(this.#C+=e[0],this.#k=this.#k.slice(e[0].length),null!==e[0].match("\n"))}addCookie(e,t){this.#w&&this.#w.setSize(e.position-this.#T),this.#w="string"==typeof e.value?new F(e.key,e.value,t):new F("",e.key,t),this.#v&&this.#w.addAttribute("domain",this.#v),this.#T=e.position,this.#I.push(this.#w)}}class q{key;value;position;constructor(e,t,n){this.key=e,this.value=t,this.position=n}}var _,z,j=Object.freeze({__proto__:null,CookieParser:H});class W extends a.InspectorBackend.TargetBase{#R;#u;#x;#M;#P;#p;#L;#E;#A;#O;#N;#F;constructor(e,n,r,s,i,a,o,l,d){switch(super(s===_.Node,i,a,l),this.#R=e,this.#u=r,this.#x=t.DevToolsPath.EmptyUrlString,this.#M="",this.#P=0,s){case _.Frame:this.#P=z.Browser|z.Storage|z.DOM|z.JS|z.Log|z.Network|z.Target|z.Tracing|z.Emulation|z.Input|z.Inspector|z.Audits|z.WebAuthn|z.IO|z.Media,i?.type()!==_.Frame&&(this.#P|=z.DeviceEmulation|z.ScreenCapture|z.Security|z.ServiceWorker,d?.url.startsWith("chrome-extension://")&&(this.#P&=~z.Security));break;case _.ServiceWorker:this.#P=z.JS|z.Log|z.Network|z.Target|z.Inspector|z.IO,i?.type()!==_.Frame&&(this.#P|=z.Browser);break;case _.SharedWorker:this.#P=z.JS|z.Log|z.Network|z.Target|z.IO|z.Media|z.Inspector;break;case _.Worker:this.#P=z.JS|z.Log|z.Network|z.Target|z.IO|z.Media|z.Emulation;break;case _.Node:this.#P=z.JS;break;case _.AuctionWorklet:this.#P=z.JS|z.EventBreakpoints;break;case _.Browser:this.#P=z.Target|z.IO;break;case _.Tab:this.#P=z.Target}this.#p=s,this.#L=i,this.#E=n,this.#A=new Map,this.#O=o,this.#N=d}createModels(e){this.#F=!0;const t=Array.from(c.registeredModels.entries());for(const[e,n]of t)n.early&&this.model(e);for(const[n,r]of t)(r.autostart||e.has(n))&&this.model(n);this.#F=!1}id(){return this.#E}name(){return this.#u||this.#M}setName(e){this.#u!==e&&(this.#u=e,this.#R.onNameChange(this))}type(){return this.#p}markAsNodeJSForTest(){super.markAsNodeJSForTest(),this.#p=_.Node}targetManager(){return this.#R}hasAllCapabilities(e){return(this.#P&e)===e}decorateLabel(e){return this.#p===_.Worker||this.#p===_.ServiceWorker?"⚙ "+e:e}parentTarget(){return this.#L}outermostTarget(){let e=null,t=this;do{t.type()!==_.Tab&&t.type()!==_.Browser&&(e=t),t=t.parentTarget()}while(t);return e}dispose(e){super.dispose(e),this.#R.removeTarget(this);for(const e of this.#A.values())e.dispose()}model(e){if(!this.#A.get(e)){const t=c.registeredModels.get(e);if(void 0===t)throw"Model class is not registered @"+(new Error).stack;if((this.#P&t.capabilities)===t.capabilities){const t=new e(this);this.#A.set(e,t),this.#F||this.#R.modelAdded(this,e,t,this.#R.isInScope(this))}}return this.#A.get(e)||null}models(){return this.#A}inspectedURL(){return this.#x}setInspectedURL(n){this.#x=n;const r=e.ParsedURL.ParsedURL.fromString(n);this.#M=r?r.lastPathComponentWithFragment():"#"+this.#E,this.parentTarget()?.type()!==_.Frame&&i.InspectorFrontendHost.InspectorFrontendHostInstance.inspectedURLChanged(n||t.DevToolsPath.EmptyUrlString),this.#R.onInspectedURLChange(this),this.#u||this.#R.onNameChange(this)}async suspend(e){this.#O||(this.#O=!0,await Promise.all(Array.from(this.models().values(),(t=>t.preSuspendModel(e)))),await Promise.all(Array.from(this.models().values(),(t=>t.suspendModel(e)))))}async resume(){this.#O&&(this.#O=!1,await Promise.all(Array.from(this.models().values(),(e=>e.resumeModel()))),await Promise.all(Array.from(this.models().values(),(e=>e.postResumeModel()))))}suspended(){return this.#O}updateTargetInfo(e){this.#N=e}targetInfo(){return this.#N}}!function(e){e.Frame="frame",e.ServiceWorker="service-worker",e.Worker="worker",e.SharedWorker="shared-worker",e.Node="node",e.Browser="browser",e.AuctionWorklet="auction-worklet",e.Tab="tab"}(_||(_={})),function(e){e[e.Browser=1]="Browser",e[e.DOM=2]="DOM",e[e.JS=4]="JS",e[e.Log=8]="Log",e[e.Network=16]="Network",e[e.Target=32]="Target",e[e.ScreenCapture=64]="ScreenCapture",e[e.Tracing=128]="Tracing",e[e.Emulation=256]="Emulation",e[e.Security=512]="Security",e[e.Input=1024]="Input",e[e.Inspector=2048]="Inspector",e[e.DeviceEmulation=4096]="DeviceEmulation",e[e.Storage=8192]="Storage",e[e.ServiceWorker=16384]="ServiceWorker",e[e.Audits=32768]="Audits",e[e.WebAuthn=65536]="WebAuthn",e[e.IO=131072]="IO",e[e.Media=262144]="Media",e[e.EventBreakpoints=524288]="EventBreakpoints",e[e.None=0]="None"}(z||(z={}));var V=Object.freeze({__proto__:null,Target:W,get Type(){return _},get Capability(){return z}});let G;class K extends e.ObjectWrapper.ObjectWrapper{#B;#D;#U;#H;#q;#O;#_;#z;#j;#W;constructor(){super(),this.#B=new Set,this.#D=new Set,this.#U=new t.MapUtilities.Multimap,this.#H=new t.MapUtilities.Multimap,this.#O=!1,this.#_=null,this.#z=null,this.#q=new WeakSet,this.#j=!1,this.#W=new Set}static instance({forceNew:e}={forceNew:!1}){return G&&!e||(G=new K),G}static removeInstance(){G=void 0}onInspectedURLChange(e){this.dispatchEventToListeners($.InspectedURLChanged,e)}onNameChange(e){this.dispatchEventToListeners($.NameChanged,e)}async suspendAllTargets(e){if(this.#O)return;this.#O=!0,this.dispatchEventToListeners($.SuspendStateChanged);const t=Array.from(this.#B.values(),(t=>t.suspend(e)));await Promise.all(t)}async resumeAllTargets(){if(!this.#O)return;this.#O=!1,this.dispatchEventToListeners($.SuspendStateChanged);const e=Array.from(this.#B.values(),(e=>e.resume()));await Promise.all(e)}allTargetsSuspended(){return this.#O}models(e,t){const n=[];for(const r of this.#B){if(t?.scoped&&!this.isInScope(r))continue;const s=r.model(e);s&&n.push(s)}return n}inspectedURL(){const e=this.primaryPageTarget();return e?e.inspectedURL():""}observeModels(e,t,n){const r=this.models(e,n);this.#H.set(e,t),n?.scoped&&this.#q.add(t);for(const e of r)t.modelAdded(e)}unobserveModels(e,t){this.#H.delete(e,t),this.#q.delete(t)}modelAdded(e,t,n,r){for(const e of this.#H.get(t).values())this.#q.has(e)&&!r||e.modelAdded(n)}modelRemoved(e,t,n,r){for(const e of this.#H.get(t).values())this.#q.has(e)&&!r||e.modelRemoved(n)}addModelListener(e,t,n,r,s){const i=e=>{s?.scoped&&!this.isInScope(e)||n.call(r,e)};for(const n of this.models(e))n.addEventListener(t,i);this.#U.set(t,{modelClass:e,thisObject:r,listener:n,wrappedListener:i})}removeModelListener(e,t,n,r){if(!this.#U.has(t))return;let s=null;for(const i of this.#U.get(t))i.modelClass===e&&i.listener===n&&i.thisObject===r&&(s=i.wrappedListener,this.#U.delete(t,i));if(s)for(const n of this.models(e))n.removeEventListener(t,s)}observeTargets(e,t){if(this.#D.has(e))throw new Error("Observer can only be registered once");t?.scoped&&this.#q.add(e);for(const n of this.#B)t?.scoped&&!this.isInScope(n)||e.targetAdded(n);this.#D.add(e)}unobserveTargets(e){this.#D.delete(e),this.#q.delete(e)}createTarget(e,t,n,r,s,i,a,o){const l=new W(this,e,t,n,r,s||"",this.#O,a||null,o);i&&l.pageAgent().invoke_waitForDebugger(),l.createModels(new Set(this.#H.keysArray())),this.#B.add(l);const d=this.isInScope(l);for(const e of[...this.#D])this.#q.has(e)&&!d||e.targetAdded(l);for(const[e,t]of l.models().entries())this.modelAdded(l,e,t,d);for(const e of this.#U.keysArray())for(const t of this.#U.get(e)){const n=l.model(t.modelClass);n&&n.addEventListener(e,t.wrappedListener)}return l!==l.outermostTarget()||l.type()===_.Frame&&l!==this.primaryPageTarget()||this.#j||this.setScopeTarget(l),l}removeTarget(e){if(!this.#B.has(e))return;const t=this.isInScope(e);this.#B.delete(e);for(const r of e.models().keys()){const s=e.models().get(r);n(s),this.modelRemoved(e,r,s,t)}for(const n of[...this.#D])this.#q.has(n)&&!t||n.targetRemoved(e);for(const t of this.#U.keysArray())for(const n of this.#U.get(t)){const r=e.model(n.modelClass);r&&r.removeEventListener(t,n.wrappedListener)}}targets(){return[...this.#B]}targetById(e){return this.targets().find((t=>t.id()===e))||null}rootTarget(){return this.#B.size?this.#B.values().next().value:null}primaryPageTarget(){let e=this.rootTarget();return e?.type()===_.Tab&&(e=this.targets().find((t=>t.parentTarget()===e&&t.type()===_.Frame&&!t.targetInfo()?.subtype?.length))||null),e}browserTarget(){return this.#_}async maybeAttachInitialTarget(){if(!Boolean(o.Runtime.Runtime.queryParam("browserConnection")))return!1;this.#_||(this.#_=new W(this,"main","browser",_.Browser,null,"",!1,null,void 0),this.#_.createModels(new Set(this.#H.keysArray())));const e=await i.InspectorFrontendHost.InspectorFrontendHostInstance.initialTargetId();return this.#_.targetAgent().invoke_autoAttachRelated({targetId:e,waitForDebuggerOnStart:!0}),!0}clearAllTargetsForTest(){this.#B.clear()}isInScope(e){if(!e)return!1;for(function(e){return"source"in e&&e.source instanceof c}(e)&&(e=e.source),e instanceof c&&(e=e.target());e&&e!==this.#z;)e=e.parentTarget();return Boolean(e)&&e===this.#z}setScopeTarget(e){if(e!==this.#z){for(const e of this.targets())if(this.isInScope(e)){for(const t of this.#H.keysArray()){const n=e.models().get(t);if(n)for(const e of[...this.#H.get(t)].filter((e=>this.#q.has(e))))e.modelRemoved(n)}for(const t of[...this.#D].filter((e=>this.#q.has(e))))t.targetRemoved(e)}this.#z=e;for(const e of this.targets())if(this.isInScope(e)){for(const t of[...this.#D].filter((e=>this.#q.has(e))))t.targetAdded(e);for(const[t,n]of e.models().entries())for(const e of[...this.#H.get(t)].filter((e=>this.#q.has(e))))e.modelAdded(n)}for(const e of this.#W)e()}}addScopeChangeListener(e){this.#W.add(e)}removeScopeChangeListener(e){this.#W.delete(e)}scopeTarget(){return this.#z}}var $;!function(e){e.AvailableTargetsChanged="AvailableTargetsChanged",e.InspectedURLChanged="InspectedURLChanged",e.NameChanged="NameChanged",e.SuspendStateChanged="SuspendStateChanged"}($||($={}));var Q=Object.freeze({__proto__:null,TargetManager:K,get Events(){return $},Observer:class{targetAdded(e){}targetRemoved(e){}},SDKModelObserver:class{modelAdded(e){}modelRemoved(e){}}});const X={noContentForWebSocket:"Content for WebSockets is currently not supported",noContentForRedirect:"No content available because this request was redirected",noContentForPreflight:"No content available for preflight request",noThrottling:"No throttling",offline:"Offline",slowG:"Slow 3G",fastG:"Fast 3G",requestWasBlockedByDevtoolsS:'Request was blocked by DevTools: "{PH1}"',crossoriginReadBlockingCorb:"Cross-Origin Read Blocking (CORB) blocked cross-origin response {PH1} with MIME type {PH2}. See https://www.chromestatus.com/feature/5629709824032768 for more details.",sFailedLoadingSS:'{PH1} failed loading: {PH2} "{PH3}".',sFinishedLoadingSS:'{PH1} finished loading: {PH2} "{PH3}".'},J=s.i18n.registerUIStrings("core/sdk/NetworkManager.ts",X),Y=s.i18n.getLocalizedString.bind(void 0,J),Z=s.i18n.getLazilyComputedLocalizedString.bind(void 0,J),ee=new WeakMap,te=new Map([["2g","cellular2g"],["3g","cellular3g"],["4g","cellular4g"],["bluetooth","bluetooth"],["wifi","wifi"],["wimax","wimax"]]);class ne extends c{dispatcher;fetchDispatcher;#V;#G;constructor(t){super(t),this.dispatcher=new ce(this),this.fetchDispatcher=new de(t.fetchAgent(),this),this.#V=t.networkAgent(),t.registerNetworkDispatcher(this.dispatcher),t.registerFetchDispatcher(this.fetchDispatcher),e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()&&this.#V.invoke_setCacheDisabled({cacheDisabled:!0}),this.#V.invoke_enable({maxPostDataSize:le}),this.#V.invoke_setAttachDebugStack({enabled:!0}),this.#G=e.Settings.Settings.instance().createSetting("bypassServiceWorker",!1),this.#G.get()&&this.bypassServiceWorkerChanged(),this.#G.addChangeListener(this.bypassServiceWorkerChanged,this),e.Settings.Settings.instance().moduleSetting("cacheDisabled").addChangeListener(this.cacheDisabledSettingChanged,this)}static forRequest(e){return ee.get(e)||null}static canReplayRequest(t){return Boolean(ee.get(t))&&Boolean(t.backendRequestId())&&!t.isRedirect()&&t.resourceType()===e.ResourceType.resourceTypes.XHR}static replayRequest(e){const t=ee.get(e),n=e.backendRequestId();t&&n&&!e.isRedirect()&&t.#V.invoke_replayXHR({requestId:n})}static async searchInRequest(e,t,n,r){const s=ne.forRequest(e),i=e.backendRequestId();if(!s||!i||e.isRedirect())return[];return(await s.#V.invoke_searchInResponseBody({requestId:i,query:t,caseSensitive:n,isRegex:r})).result||[]}static async requestContentData(t){if(t.resourceType()===e.ResourceType.resourceTypes.WebSocket)return{error:Y(X.noContentForWebSocket),content:null,encoded:!1};if(t.finished||await t.once(Te.FinishedLoading),t.isRedirect())return{error:Y(X.noContentForRedirect),content:null,encoded:!1};if(t.isPreflightRequest())return{error:Y(X.noContentForPreflight),content:null,encoded:!1};const n=ne.forRequest(t);if(!n)return{error:"No network manager for request",content:null,encoded:!1};const r=t.backendRequestId();if(!r)return{error:"No backend request id for request",content:null,encoded:!1};const s=await n.#V.invoke_getResponseBody({requestId:r}),i=s.getError()||null;return{error:i,content:i?null:s.body,encoded:s.base64Encoded}}static async requestPostData(e){const t=ne.forRequest(e);if(!t)return console.error("No network manager for request"),null;const n=e.backendRequestId();if(!n)return console.error("No backend request id for request"),null;try{const{postData:e}=await t.#V.invoke_getRequestPostData({requestId:n});return e}catch(e){return e.message}}static connectionType(e){if(!e.download&&!e.upload)return"none";const t="function"==typeof e.title?e.title().toLowerCase():e.title.toLowerCase();for(const[e,n]of te)if(t.includes(e))return n;return"other"}static lowercaseHeaders(e){const t={};for(const n in e)t[n.toLowerCase()]=e[n];return t}requestForURL(e){return this.dispatcher.requestForURL(e)}requestForId(e){return this.dispatcher.requestForId(e)}requestForLoaderId(e){return this.dispatcher.requestForLoaderId(e)}cacheDisabledSettingChanged({data:e}){this.#V.invoke_setCacheDisabled({cacheDisabled:e})}dispose(){e.Settings.Settings.instance().moduleSetting("cacheDisabled").removeChangeListener(this.cacheDisabledSettingChanged,this)}bypassServiceWorkerChanged(){this.#V.invoke_setBypassServiceWorker({bypass:this.#G.get()})}async getSecurityIsolationStatus(e){const t=await this.#V.invoke_getSecurityIsolationStatus({frameId:e??void 0});return t.getError()?null:t.status}async enableReportingApi(e=!0){return this.#V.invoke_enableReportingApi({enable:e})}async loadNetworkResource(e,t,n){const r=await this.#V.invoke_loadNetworkResource({frameId:e??void 0,url:t,options:n});if(r.getError())throw new Error(r.getError());return r.resource}clearRequests(){this.dispatcher.clearRequests()}}var re;!function(e){e.RequestStarted="RequestStarted",e.RequestUpdated="RequestUpdated",e.RequestFinished="RequestFinished",e.RequestUpdateDropped="RequestUpdateDropped",e.ResponseReceived="ResponseReceived",e.MessageGenerated="MessageGenerated",e.RequestRedirected="RequestRedirected",e.LoadingFinished="LoadingFinished",e.ReportingApiReportAdded="ReportingApiReportAdded",e.ReportingApiReportUpdated="ReportingApiReportUpdated",e.ReportingApiEndpointsChangedForOrigin="ReportingApiEndpointsChangedForOrigin"}(re||(re={}));const se={title:Z(X.noThrottling),i18nTitleKey:X.noThrottling,download:-1,upload:-1,latency:0},ie={title:Z(X.offline),i18nTitleKey:X.offline,download:0,upload:0,latency:0},ae={title:Z(X.slowG),i18nTitleKey:X.slowG,download:5e4,upload:5e4,latency:2e3},oe={title:Z(X.fastG),i18nTitleKey:X.fastG,download:18e4,upload:84375,latency:562.5},le=65536;class de{#K;#$;constructor(e,t){this.#K=e,this.#$=t}requestPaused({requestId:e,request:t,resourceType:n,responseStatusCode:r,responseHeaders:s,networkId:i}){const a=i?this.#$.requestForId(i):null;0===a?.originalResponseHeaders.length&&s&&(a.originalResponseHeaders=s),ue.instance().requestIntercepted(new ge(this.#K,t,n,e,a,r,s))}authRequired({}){}}class ce{#$;#Q;#X;#J;#Y;#Z;constructor(e){this.#$=e,this.#Q=new Map,this.#X=new Map,this.#J=new Map,this.#Y=new Map,this.#Z=new Map,ue.instance().addEventListener(ue.Events.RequestIntercepted,this.#ee.bind(this))}#ee(e){const t=this.requestForId(e.data);t&&t.setWasIntercepted(!0)}headersMapToHeadersArray(e){const t=[];for(const n in e){const r=e[n].split("\n");for(let e=0;e=0&&t.setTransferSize(n.encodedDataLength),n.requestHeaders&&!t.hasExtraRequestInfo()&&(t.setRequestHeaders(this.headersMapToHeadersArray(n.requestHeaders)),t.setRequestHeadersText(n.requestHeadersText||"")),t.connectionReused=n.connectionReused,t.connectionId=String(n.connectionId),n.remoteIPAddress&&t.setRemoteAddress(n.remoteIPAddress,n.remotePort||-1),n.fromServiceWorker&&(t.fetchedViaServiceWorker=!0),n.fromDiskCache&&t.setFromDiskCache(),n.fromPrefetchCache&&t.setFromPrefetchCache(),n.cacheStorageCacheName&&t.setResponseCacheStorageCacheName(n.cacheStorageCacheName),n.responseTime&&t.setResponseRetrievalTime(new Date(n.responseTime)),t.timing=n.timing,t.protocol=n.protocol||"",t.alternateProtocolUsage=n.alternateProtocolUsage,n.serviceWorkerResponseSource&&t.setServiceWorkerResponseSource(n.serviceWorkerResponseSource),t.setSecurityState(n.securityState),n.securityDetails&&t.setSecurityDetails(n.securityDetails);const r=e.ResourceType.ResourceType.fromMimeTypeOverride(t.mimeType);r&&t.setResourceType(r)}requestForId(e){return this.#Q.get(e)||null}requestForURL(e){return this.#X.get(e)||null}requestForLoaderId(e){return this.#J.get(e)||null}resourceChangedPriority({requestId:e,newPriority:t}){const n=this.#Q.get(e);n&&n.setPriority(t)}signedExchangeReceived({requestId:t,info:n}){let r=this.#Q.get(t);(r||(r=this.#X.get(n.outerResponse.url),r))&&(r.setSignedExchangeInfo(n),r.setResourceType(e.ResourceType.resourceTypes.SignedExchange),this.updateNetworkRequestWithResponse(r,n.outerResponse),this.updateNetworkRequest(r),this.#$.dispatchEventToListeners(re.ResponseReceived,{request:r,response:n.outerResponse}))}requestWillBeSent({requestId:t,loaderId:n,documentURL:r,request:s,timestamp:i,wallTime:a,initiator:o,redirectResponse:l,type:d,frameId:c,hasUserGesture:h}){let u=this.#Q.get(t);if(u){if(!l)return;u.signedExchangeInfo()||this.responseReceived({requestId:t,loaderId:n,timestamp:i,type:d||"Other",response:l,hasExtraInfo:!1,frameId:c}),u=this.appendRedirect(t,i,s.url),this.#$.dispatchEventToListeners(re.RequestRedirected,u)}else u=Me.create(t,s.url,r,c??null,n,o,h),ee.set(u,this.#$);u.hasNetworkData=!0,this.updateNetworkRequestWithRequest(u,s),u.setIssueTime(i,a),u.setResourceType(d?e.ResourceType.resourceTypes[d]:e.ResourceType.resourceTypes.Other),s.trustTokenParams&&u.setTrustTokenParams(s.trustTokenParams);const g=this.#Z.get(t);g&&(u.setTrustTokenOperationDoneEvent(g),this.#Z.delete(t)),this.getExtraInfoBuilder(t).addRequest(u),this.startNetworkRequest(u,s)}requestServedFromCache({requestId:e}){const t=this.#Q.get(e);t&&t.setFromMemoryCache()}responseReceived({requestId:t,loaderId:n,timestamp:r,type:s,response:i,frameId:a}){const o=this.#Q.get(t),l=ne.lowercaseHeaders(i.headers);if(o)o.responseReceivedTime=r,o.setResourceType(e.ResourceType.resourceTypes[s]),this.updateNetworkRequestWithResponse(o,i),this.updateNetworkRequest(o),this.#$.dispatchEventToListeners(re.ResponseReceived,{request:o,response:i});else{const e=l["last-modified"],t={url:i.url,frameId:a??null,loaderId:n,resourceType:s,mimeType:i.mimeType,lastModified:e?new Date(e):null};this.#$.dispatchEventToListeners(re.RequestUpdateDropped,t)}}dataReceived({requestId:e,timestamp:t,dataLength:n,encodedDataLength:r}){let s=this.#Q.get(e);s||(s=this.maybeAdoptMainResourceRequest(e)),s&&(s.resourceSize+=n,-1!==r&&s.increaseTransferSize(r),s.endTime=t,this.updateNetworkRequest(s))}loadingFinished({requestId:e,timestamp:t,encodedDataLength:n,shouldReportCorbBlocking:r}){let s=this.#Q.get(e);s||(s=this.maybeAdoptMainResourceRequest(e)),s&&(this.getExtraInfoBuilder(e).finished(),this.finishNetworkRequest(s,t,n,r),this.#$.dispatchEventToListeners(re.LoadingFinished,s))}loadingFailed({requestId:t,timestamp:n,type:r,errorText:s,canceled:i,blockedReason:a,corsErrorStatus:o}){const l=this.#Q.get(t);if(l){if(l.failed=!0,l.setResourceType(e.ResourceType.resourceTypes[r]),l.canceled=Boolean(i),a&&(l.setBlockedReason(a),"inspector"===a)){const e=Y(X.requestWasBlockedByDevtoolsS,{PH1:l.url()});this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t,warning:!0})}o&&l.setCorsErrorStatus(o),l.localizedFailDescription=s,this.getExtraInfoBuilder(t).finished(),this.finishNetworkRequest(l,n,-1)}}webSocketCreated({requestId:t,url:n,initiator:r}){const s=Me.createForWebSocket(t,n,r);ee.set(s,this.#$),s.setResourceType(e.ResourceType.resourceTypes.WebSocket),this.startNetworkRequest(s,null)}webSocketWillSendHandshakeRequest({requestId:e,timestamp:t,wallTime:n,request:r}){const s=this.#Q.get(e);s&&(s.requestMethod="GET",s.setRequestHeaders(this.headersMapToHeadersArray(r.headers)),s.setIssueTime(t,n),this.updateNetworkRequest(s))}webSocketHandshakeResponseReceived({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.statusCode=n.status,r.statusText=n.statusText,r.responseHeaders=this.headersMapToHeadersArray(n.headers),r.responseHeadersText=n.headersText||"",n.requestHeaders&&r.setRequestHeaders(this.headersMapToHeadersArray(n.requestHeaders)),n.requestHeadersText&&r.setRequestHeadersText(n.requestHeadersText),r.responseReceivedTime=t,r.protocol="websocket",this.updateNetworkRequest(r))}webSocketFrameReceived({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrame(n,t,!1),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketFrameSent({requestId:e,timestamp:t,response:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrame(n,t,!0),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketFrameError({requestId:e,timestamp:t,errorMessage:n}){const r=this.#Q.get(e);r&&(r.addProtocolFrameError(n,t),r.responseReceivedTime=t,this.updateNetworkRequest(r))}webSocketClosed({requestId:e,timestamp:t}){const n=this.#Q.get(e);n&&this.finishNetworkRequest(n,t,-1)}eventSourceMessageReceived({requestId:e,timestamp:t,eventName:n,eventId:r,data:s}){const i=this.#Q.get(e);i&&i.addEventSourceMessage(t,n,r,s)}requestIntercepted({}){}requestWillBeSentExtraInfo({requestId:e,associatedCookies:t,headers:n,clientSecurityState:r,connectTiming:s,siteHasCookieInOtherPartition:i}){const a=[],o=[];for(const{blockedReasons:e,cookie:n}of t)0===e.length?o.push(F.fromProtocolCookie(n)):a.push({blockedReasons:e,cookie:F.fromProtocolCookie(n)});const l={blockedRequestCookies:a,includedRequestCookies:o,requestHeaders:this.headersMapToHeadersArray(n),clientSecurityState:r,connectTiming:s,siteHasCookieInOtherPartition:i};this.getExtraInfoBuilder(e).addRequestExtraInfo(l)}responseReceivedExtraInfo({requestId:e,blockedCookies:t,headers:n,headersText:r,resourceIPAddressSpace:s,statusCode:i,cookiePartitionKey:a,cookiePartitionKeyOpaque:o}){const l={blockedResponseCookies:t.map((e=>({blockedReasons:e.blockedReasons,cookieLine:e.cookieLine,cookie:e.cookie?F.fromProtocolCookie(e.cookie):null}))),responseHeaders:this.headersMapToHeadersArray(n),responseHeadersText:r,resourceIPAddressSpace:s,statusCode:i,cookiePartitionKey:a,cookiePartitionKeyOpaque:o};this.getExtraInfoBuilder(e).addResponseExtraInfo(l)}getExtraInfoBuilder(e){let t;return this.#Y.has(e)?t=this.#Y.get(e):(t=new pe,this.#Y.set(e,t)),t}appendRedirect(e,t,n){const r=this.#Q.get(e);if(!r)throw new Error(`Could not find original network request for ${e}`);let s=0;for(let e=r.redirectSource();e;e=e.redirectSource())s++;r.markAsRedirect(s),this.finishNetworkRequest(r,t,-1);const i=Me.create(e,n,r.documentURL,r.frameId,r.loaderId,r.initiator(),r.hasUserGesture()??void 0);return ee.set(i,this.#$),i.setRedirectSource(r),r.setRedirectDestination(i),i}maybeAdoptMainResourceRequest(e){const t=ue.instance().inflightMainResourceRequests.get(e);if(!t)return null;const n=ne.forRequest(t).dispatcher;n.#Q.delete(e),n.#X.delete(t.url());const r=t.loaderId;r&&n.#J.delete(r);const s=n.#Y.get(e);return n.#Y.delete(e),this.#Q.set(e,t),this.#X.set(t.url(),t),r&&this.#J.set(r,t),s&&this.#Y.set(e,s),ee.set(t,this.#$),t}startNetworkRequest(e,t){this.#Q.set(e.requestId(),e),this.#X.set(e.url(),e);const n=e.loaderId;n&&this.#J.set(n,e),e.loaderId===e.requestId()&&ue.instance().inflightMainResourceRequests.set(e.requestId(),e),this.#$.dispatchEventToListeners(re.RequestStarted,{request:e,originalRequest:t})}updateNetworkRequest(e){this.#$.dispatchEventToListeners(re.RequestUpdated,e)}finishNetworkRequest(t,n,r,s){if(t.endTime=n,t.finished=!0,r>=0){const e=t.redirectSource();e&&e.signedExchangeInfo()?(t.setTransferSize(0),e.setTransferSize(r),this.updateNetworkRequest(e)):t.setTransferSize(r)}if(this.#$.dispatchEventToListeners(re.RequestFinished,t),ue.instance().inflightMainResourceRequests.delete(t.requestId()),s){const e=Y(X.crossoriginReadBlockingCorb,{PH1:t.url(),PH2:t.mimeType});this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t.requestId(),warning:!0})}if(e.Settings.Settings.instance().moduleSetting("monitoringXHREnabled").get()&&t.resourceType().category()===e.ResourceType.resourceCategories.XHR){let e;const n=t.failed||t.hasErrorStatusCode();e=Y(n?X.sFailedLoadingSS:X.sFinishedLoadingSS,{PH1:t.resourceType().title(),PH2:t.requestMethod,PH3:t.url()}),this.#$.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:t.requestId(),warning:!1})}}clearRequests(){for(const[e,t]of this.#Q)t.finished&&this.#Q.delete(e);for(const[e,t]of this.#X)t.finished&&this.#X.delete(e);for(const[e,t]of this.#J)t.finished&&this.#J.delete(e);for(const[e,t]of this.#Y)t.isFinished()&&this.#Y.delete(e)}webTransportCreated({transportId:t,url:n,timestamp:r,initiator:s}){const i=Me.createForWebSocket(t,n,s);i.hasNetworkData=!0,ee.set(i,this.#$),i.setResourceType(e.ResourceType.resourceTypes.WebTransport),i.setIssueTime(r,0),this.startNetworkRequest(i,null)}webTransportConnectionEstablished({transportId:e,timestamp:t}){const n=this.#Q.get(e);n&&(n.responseReceivedTime=t,n.endTime=t+.001,this.updateNetworkRequest(n))}webTransportClosed({transportId:e,timestamp:t}){const n=this.#Q.get(e);n&&(n.endTime=t,this.finishNetworkRequest(n,t,0))}trustTokenOperationDone(e){const t=this.#Q.get(e.requestId);t?t.setTrustTokenOperationDoneEvent(e):this.#Z.set(e.requestId,e)}subresourceWebBundleMetadataReceived({requestId:e,urls:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInfo({resourceUrls:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleMetadataError({requestId:e,errorMessage:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInfo({errorMessage:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleInnerResponseParsed({innerRequestId:e,bundleRequestId:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInnerRequestInfo({bundleRequestId:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}subresourceWebBundleInnerResponseError({innerRequestId:e,errorMessage:t}){const n=this.getExtraInfoBuilder(e);n.setWebBundleInnerRequestInfo({errorMessage:t});const r=n.finalRequest();r&&this.updateNetworkRequest(r)}reportingApiReportAdded(e){this.#$.dispatchEventToListeners(re.ReportingApiReportAdded,e.report)}reportingApiReportUpdated(e){this.#$.dispatchEventToListeners(re.ReportingApiReportUpdated,e.report)}reportingApiEndpointsChangedForOrigin(e){this.#$.dispatchEventToListeners(re.ReportingApiEndpointsChangedForOrigin,e)}createNetworkRequest(e,t,n,r,s,i){const a=Me.create(e,r,s,t,n,i);return ee.set(a,this.#$),a}}let he;class ue extends e.ObjectWrapper.ObjectWrapper{#te;#ne;#re;#se;#ie;inflightMainResourceRequests;#ae;#oe;#le;#de;#ce;#he;#ue;#ge;constructor(){super(),this.#te="",this.#ne=null,this.#re=null,this.#se=new Set,this.#ie=new Set,this.inflightMainResourceRequests=new Map,this.#ae=se,this.#oe=null,this.#le=e.Settings.Settings.instance().moduleSetting("requestBlockingEnabled"),this.#de=e.Settings.Settings.instance().createSetting("networkBlockedPatterns",[]),this.#ce=[],this.updateBlockedPatterns(),this.#he=new t.MapUtilities.Multimap,K.instance().observeModels(ne,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return he&&!t||(he=new ue),he}static dispose(){he=null}static getChromeVersion(){const e=navigator.userAgent.match(/(?:^|\W)(?:Chrome|HeadlessChrome)\/(\S+)/);return e&&e.length>1?e[1]:""}static patchUserAgentWithChromeVersion(e){const n=ue.getChromeVersion();if(n.length>0){const r=n.split(".",1)[0]+".0.100.0";return t.StringUtilities.sprintf(e,n,r)}return e}static patchUserAgentMetadataWithChromeVersion(e){if(!e.brands)return;const n=ue.getChromeVersion();if(0===n.length)return;const r=n.split(".",1)[0];for(const n of e.brands)n.version.includes("%s")&&(n.version=t.StringUtilities.sprintf(n.version,r));e.fullVersion&&e.fullVersion.includes("%s")&&(e.fullVersion=t.StringUtilities.sprintf(e.fullVersion,n))}modelAdded(e){const t=e.target().networkAgent(),n=e.target().fetchAgent();this.#ue&&t.invoke_setExtraHTTPHeaders({headers:this.#ue}),this.currentUserAgent()&&t.invoke_setUserAgentOverride({userAgent:this.currentUserAgent(),userAgentMetadata:this.#ne||void 0}),this.#ce.length&&t.invoke_setBlockedURLs({urls:this.#ce}),this.isIntercepting()&&n.invoke_enable({patterns:this.#he.valuesArray()}),null===this.#re?t.invoke_clearAcceptedEncodingsOverride():t.invoke_setAcceptedEncodings({encodings:this.#re}),this.#se.add(t),this.#ie.add(n),this.isThrottling()&&this.updateNetworkConditions(t)}modelRemoved(e){for(const t of this.inflightMainResourceRequests){ne.forRequest(t[1])===e&&this.inflightMainResourceRequests.delete(t[0])}this.#se.delete(e.target().networkAgent()),this.#ie.delete(e.target().fetchAgent())}isThrottling(){return this.#ae.download>=0||this.#ae.upload>=0||this.#ae.latency>0}isOffline(){return!this.#ae.download&&!this.#ae.upload}setNetworkConditions(e){this.#ae=e;for(const e of this.#se)this.updateNetworkConditions(e);this.dispatchEventToListeners(ue.Events.ConditionsChanged)}networkConditions(){return this.#ae}updateNetworkConditions(e){const t=this.#ae;this.isThrottling()?e.invoke_emulateNetworkConditions({offline:this.isOffline(),latency:t.latency,downloadThroughput:t.download<0?0:t.download,uploadThroughput:t.upload<0?0:t.upload,connectionType:ne.connectionType(t)}):e.invoke_emulateNetworkConditions({offline:!1,latency:0,downloadThroughput:0,uploadThroughput:0})}setExtraHTTPHeaders(e){this.#ue=e;for(const e of this.#se)e.invoke_setExtraHTTPHeaders({headers:this.#ue})}currentUserAgent(){return this.#ge?this.#ge:this.#te}updateUserAgentOverride(){const e=this.currentUserAgent();for(const t of this.#se)t.invoke_setUserAgentOverride({userAgent:e,userAgentMetadata:this.#ne||void 0})}setUserAgentOverride(e,t){const n=this.#te!==e;this.#te=e,this.#ge?this.#ne=null:(this.#ne=t,this.updateUserAgentOverride()),n&&this.dispatchEventToListeners(ue.Events.UserAgentChanged)}userAgentOverride(){return this.#te}setCustomUserAgentOverride(e,t=null){this.#ge=e,this.#ne=t,this.updateUserAgentOverride()}setCustomAcceptedEncodingsOverride(e){this.#re=e,this.updateAcceptedEncodingsOverride(),this.dispatchEventToListeners(ue.Events.AcceptedEncodingsChanged)}clearCustomAcceptedEncodingsOverride(){this.#re=null,this.updateAcceptedEncodingsOverride(),this.dispatchEventToListeners(ue.Events.AcceptedEncodingsChanged)}isAcceptedEncodingOverrideSet(){return null!==this.#re}updateAcceptedEncodingsOverride(){const e=this.#re;for(const t of this.#se)null===e?t.invoke_clearAcceptedEncodingsOverride():t.invoke_setAcceptedEncodings({encodings:e})}blockedPatterns(){return this.#de.get().slice()}blockingEnabled(){return this.#le.get()}isBlocking(){return Boolean(this.#ce.length)}setBlockedPatterns(e){this.#de.set(e),this.updateBlockedPatterns(),this.dispatchEventToListeners(ue.Events.BlockedPatternsChanged)}setBlockingEnabled(e){this.#le.get()!==e&&(this.#le.set(e),this.updateBlockedPatterns(),this.dispatchEventToListeners(ue.Events.BlockedPatternsChanged))}updateBlockedPatterns(){const e=[];if(this.#le.get())for(const t of this.#de.get())t.enabled&&e.push(t.url);if(e.length||this.#ce.length){this.#ce=e;for(const e of this.#se)e.invoke_setBlockedURLs({urls:this.#ce})}}isIntercepting(){return Boolean(this.#he.size)}setInterceptionHandlerForPatterns(e,t){this.#he.deleteAll(t);for(const n of e)this.#he.set(t,n);return this.updateInterceptionPatternsOnNextTick()}updateInterceptionPatternsOnNextTick(){return this.#oe||(this.#oe=Promise.resolve().then(this.updateInterceptionPatterns.bind(this))),this.#oe}async updateInterceptionPatterns(){e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()||e.Settings.Settings.instance().moduleSetting("cacheDisabled").set(!0),this.#oe=null;const t=[];for(const e of this.#ie)t.push(e.invoke_enable({patterns:this.#he.valuesArray()}));this.dispatchEventToListeners(ue.Events.InterceptorsChanged),await Promise.all(t)}async requestIntercepted(e){for(const t of this.#he.keysArray())if(await t(e),e.hasResponded()&&e.networkRequest)return void this.dispatchEventToListeners(ue.Events.RequestIntercepted,e.networkRequest.requestId());e.hasResponded()||e.continueRequestWithoutChange()}clearBrowserCache(){for(const e of this.#se)e.invoke_clearBrowserCache()}clearBrowserCookies(){for(const e of this.#se)e.invoke_clearBrowserCookies()}async getCertificate(e){const t=K.instance().primaryPageTarget();if(!t)return[];const n=await t.networkAgent().invoke_getCertificate({origin:e});return n?n.tableNames:[]}async loadResource(t){const n={},r=this.currentUserAgent();r&&(n["User-Agent"]=r),e.Settings.Settings.instance().moduleSetting("cacheDisabled").get()&&(n["Cache-Control"]="no-cache");const s=e.Settings.Settings.instance().moduleSetting("network.enable-remote-file-loading").get();return new Promise((e=>i.ResourceLoader.load(t,n,((t,n,r,s)=>{e({success:t,content:r,errorDescription:s})}),s)))}}!function(e){let t;!function(e){e.BlockedPatternsChanged="BlockedPatternsChanged",e.ConditionsChanged="ConditionsChanged",e.UserAgentChanged="UserAgentChanged",e.InterceptorsChanged="InterceptorsChanged",e.AcceptedEncodingsChanged="AcceptedEncodingsChanged",e.RequestIntercepted="RequestIntercepted",e.RequestFulfilled="RequestFulfilled"}(t=e.Events||(e.Events={}))}(ue||(ue={}));class ge{#K;#pe;request;resourceType;responseStatusCode;responseHeaders;requestId;networkRequest;constructor(e,t,n,r,s,i,a){this.#K=e,this.#pe=!1,this.request=t,this.resourceType=n,this.responseStatusCode=i,this.responseHeaders=a,this.requestId=r,this.networkRequest=s}hasResponded(){return this.#pe}static mergeSetCookieHeaders(e,t){const n=e=>{const t=new Map;for(const n of e){const e=n.value.match(/^([a-zA-Z0-9!#$%&'*+.^_`|~-]+=)(.*)$/);e?t.has(e[1])?t.get(e[1])?.push(n.value):t.set(e[1],[n.value]):t.has(n.value)?t.get(n.value)?.push(n.value):t.set(n.value,[n.value])}return t},r=n(e),s=n(t),i=[];for(const[e,t]of r)if(s.has(e))for(const t of s.get(e)||[])i.push({name:"set-cookie",value:t});else for(const e of t)i.push({name:"set-cookie",value:e});for(const[e,t]of s)if(!r.has(e))for(const e of t)i.push({name:"set-cookie",value:e});return i}async continueRequestWithContent(e,t,n,r){this.#pe=!0;const s=t?await e.text():await async function(e){const t=new FileReader,n=new Promise((e=>{t.onloadend=e}));if(t.readAsDataURL(e),await n,t.error)return console.error("Could not convert blob to base64.",t.error),"";const r=t.result;if(null==r||"string"!=typeof r)return console.error("Could not convert blob to base64."),"";return r.substring(r.indexOf(",")+1)}(e),i=r?200:this.responseStatusCode||200;if(this.networkRequest){const e=this.networkRequest?.originalResponseHeaders.filter((e=>"set-cookie"===e.name))||[],t=n.filter((e=>"set-cookie"===e.name));this.networkRequest.setCookieHeaders=ge.mergeSetCookieHeaders(e,t)}this.#K.invoke_fulfillRequest({requestId:this.requestId,responseCode:i,body:s,responseHeaders:n}),ue.instance().dispatchEventToListeners(ue.Events.RequestFulfilled,this.request.url)}continueRequestWithoutChange(){console.assert(!this.#pe),this.#pe=!0,this.#K.invoke_continueRequest({requestId:this.requestId})}continueRequestWithError(e){console.assert(!this.#pe),this.#pe=!0,this.#K.invoke_failRequest({requestId:this.requestId,errorReason:e})}async responseBody(){const e=await this.#K.invoke_getResponseBody({requestId:this.requestId}),t=e.getError()||null;return{error:t,content:t?null:e.body,encoded:e.base64Encoded}}isRedirect(){return void 0!==this.responseStatusCode&&this.responseStatusCode>=300&&this.responseStatusCode<400}}class pe{#me;#fe;#be;#ye;#ve;#Ie;constructor(){this.#me=[],this.#fe=[],this.#be=[],this.#ye=!1,this.#ve=null,this.#Ie=null}addRequest(e){this.#me.push(e),this.sync(this.#me.length-1)}addRequestExtraInfo(e){this.#fe.push(e),this.sync(this.#fe.length-1)}addResponseExtraInfo(e){this.#be.push(e),this.sync(this.#be.length-1)}setWebBundleInfo(e){this.#ve=e,this.updateFinalRequest()}setWebBundleInnerRequestInfo(e){this.#Ie=e,this.updateFinalRequest()}finished(){this.#ye=!0,this.updateFinalRequest()}isFinished(){return this.#ye}sync(e){const t=this.#me[e];if(!t)return;const n=this.#fe[e];n&&(t.addExtraRequestInfo(n),this.#fe[e]=null);const r=this.#be[e];r&&(t.addExtraResponseInfo(r),this.#be[e]=null)}finalRequest(){return this.#ye&&this.#me[this.#me.length-1]||null}updateFinalRequest(){if(!this.#ye)return;const e=this.finalRequest();e?.setWebBundleInfo(this.#ve),e?.setWebBundleInnerRequestInfo(this.#Ie)}}c.register(ne,{capabilities:z.Network,autostart:!0});var me=Object.freeze({__proto__:null,NetworkManager:ne,get Events(){return re},NoThrottlingConditions:se,OfflineConditions:ie,Slow3GConditions:ae,Fast3GConditions:oe,FetchDispatcher:de,NetworkDispatcher:ce,get MultitargetNetworkManager(){return ue},InterceptedRequest:ge,ConditionsSerializer:class{stringify(e){const t=e;return JSON.stringify({...t,title:"function"==typeof t.title?t.title():t.title})}parse(e){const t=JSON.parse(e);return{...t,title:t.i18nTitleKey?Z(t.i18nTitleKey):t.title}}},networkConditionsEqual:function(e,t){const n="function"==typeof e.title?e.title():e.title,r="function"==typeof t.title?t.title():t.title;return t.download===e.download&&t.upload===e.upload&&t.latency===e.latency&&r===n}});const fe={deprecatedSyntaxFoundPleaseUse:"Deprecated syntax found. Please use: ;dur=;desc=",duplicateParameterSIgnored:'Duplicate parameter "{PH1}" ignored.',noValueFoundForParameterS:'No value found for parameter "{PH1}".',unrecognizedParameterS:'Unrecognized parameter "{PH1}".',extraneousTrailingCharacters:"Extraneous trailing characters.",unableToParseSValueS:'Unable to parse "{PH1}" value "{PH2}".'},be=s.i18n.registerUIStrings("core/sdk/ServerTiming.ts",fe),ye=s.i18n.getLocalizedString.bind(void 0,be);class ve{metric;value;description;constructor(e,t,n){this.metric=e,this.value=t,this.description=n}static parseHeaders(e){const n=e.filter((e=>"server-timing"===e.name.toLowerCase()));if(!n.length)return null;const r=n.reduce(((e,t)=>{const n=this.createFromHeaderValue(t.value);return e.push(...n.map((function(e){return new ve(e.name,e.hasOwnProperty("dur")?e.dur:null,e.hasOwnProperty("desc")?e.desc:"")}))),e}),[]);return r.sort(((e,n)=>t.StringUtilities.compare(e.metric.toLowerCase(),n.metric.toLowerCase()))),r}static createFromHeaderValue(e){function t(){e=e.replace(/^\s*/,"")}function n(n){return console.assert(1===n.length),t(),e.charAt(0)===n&&(e=e.substring(1),!0)}function r(){const t=/^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(e);return t?(e=t[2],t[1]):null}function s(){return t(),'"'===e.charAt(0)?function(){console.assert('"'===e.charAt(0)),e=e.substring(1);let t="";for(;e.length;){const n=/^([^"\\]*)(.*)/.exec(e);if(!n)return null;if(t+=n[1],'"'===n[2].charAt(0))return e=n[2].substring(1),t;console.assert("\\"===n[2].charAt(0)),t+=n[2].charAt(1),e=n[2].substring(2)}return null}():r()}function i(){const t=/([,;].*)/.exec(e);t&&(e=t[1])}const a=[];let o;for(;null!==(o=r());){const t={name:o};for("="===e.charAt(0)&&this.showWarning(ye(fe.deprecatedSyntaxFoundPleaseUse));n(";");){let e;if(null===(e=r()))continue;e=e.toLowerCase();const a=this.getParserForParameter(e);let o=null;if(n("=")&&(o=s(),i()),a){if(t.hasOwnProperty(e)){this.showWarning(ye(fe.duplicateParameterSIgnored,{PH1:e}));continue}null===o&&this.showWarning(ye(fe.noValueFoundForParameterS,{PH1:e})),a.call(this,t,o)}else this.showWarning(ye(fe.unrecognizedParameterS,{PH1:e}))}if(a.push(t),!n(","))break}return e.length&&this.showWarning(ye(fe.extraneousTrailingCharacters)),a}static getParserForParameter(e){switch(e){case"dur":{function t(t,n){if(t.dur=0,null!==n){const r=parseFloat(n);if(isNaN(r))return void ve.showWarning(ye(fe.unableToParseSValueS,{PH1:e,PH2:n}));t.dur=r}}return t}case"desc":{function e(e,t){e.desc=t||""}return e}default:return null}}static showWarning(t){e.Console.Console.instance().warn(`ServerTiming: ${t}`)}}var Ie=Object.freeze({__proto__:null,ServerTiming:ve});const ke={binary:"(binary)",secureOnly:'This cookie was blocked because it had the "`Secure`" attribute and the connection was not secure.',notOnPath:"This cookie was blocked because its path was not an exact match for or a superdirectory of the request url's path.",domainMismatch:"This cookie was blocked because neither did the request URL's domain exactly match the cookie's domain, nor was the request URL's domain a subdomain of the cookie's Domain attribute value.",sameSiteStrict:'This cookie was blocked because it had the "`SameSite=Strict`" attribute and the request was made from a different site. This includes top-level navigation requests initiated by other sites.',sameSiteLax:'This cookie was blocked because it had the "`SameSite=Lax`" attribute and the request was made from a different site and was not initiated by a top-level navigation.',sameSiteUnspecifiedTreatedAsLax:'This cookie didn\'t specify a "`SameSite`" attribute when it was stored and was defaulted to "SameSite=Lax," and was blocked because the request was made from a different site and was not initiated by a top-level navigation. The cookie had to have been set with "`SameSite=None`" to enable cross-site usage.',sameSiteNoneInsecure:'This cookie was blocked because it had the "`SameSite=None`" attribute but was not marked "Secure". Cookies without SameSite restrictions must be marked "Secure" and sent over a secure connection.',userPreferences:"This cookie was blocked due to user preferences.",unknownError:"An unknown error was encountered when trying to send this cookie.",schemefulSameSiteStrict:'This cookie was blocked because it had the "`SameSite=Strict`" attribute but the request was cross-site. This includes top-level navigation requests initiated by other sites. This request is considered cross-site because the URL has a different scheme than the current site.',schemefulSameSiteLax:'This cookie was blocked because it had the "`SameSite=Lax`" attribute but the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',schemefulSameSiteUnspecifiedTreatedAsLax:'This cookie didn\'t specify a "`SameSite`" attribute when it was stored, was defaulted to "`SameSite=Lax"`, and was blocked because the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',samePartyFromCrossPartyContext:"This cookie was blocked because it had the \"`SameParty`\" attribute but the request was cross-party. The request was considered cross-party because the domain of the resource's URL and the domains of the resource's enclosing frames/documents are neither owners nor members in the same First-Party Set.",nameValuePairExceedsMaxSize:"This cookie was blocked because it was too large. The combined size of the name and value must be less than or equal to 4096 characters.",thisSetcookieWasBlockedDueToUser:"This attempt to set a cookie via a `Set-Cookie` header was blocked due to user preferences.",thisSetcookieHadInvalidSyntax:"This `Set-Cookie` header had invalid syntax.",theSchemeOfThisConnectionIsNot:"The scheme of this connection is not allowed to store cookies.",anUnknownErrorWasEncounteredWhenTrying:"An unknown error was encountered when trying to store this cookie.",thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',thisSetcookieDidntSpecifyASamesite:'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute, was defaulted to "`SameSite=Lax"`, and was blocked because it came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',thisSetcookieWasBlockedBecauseItHadTheSameparty:"This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the \"`SameParty`\" attribute but the request was cross-party. The request was considered cross-party because the domain of the resource's URL and the domains of the resource's enclosing frames/documents are neither owners nor members in the same First-Party Set.",thisSetcookieWasBlockedBecauseItHadTheSamepartyAttribute:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "`SameParty`" attribute but also had other conflicting attributes. Chrome requires cookies that use the "`SameParty`" attribute to also have the "Secure" attribute, and to not be restricted to "`SameSite=Strict`".',blockedReasonSecureOnly:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "Secure" attribute but was not received over a secure connection.',blockedReasonSameSiteStrictLax:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation.',blockedReasonSameSiteUnspecifiedTreatedAsLax:'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute and was defaulted to "`SameSite=Lax,`" and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The `Set-Cookie` had to have been set with "`SameSite=None`" to enable cross-site usage.',blockedReasonSameSiteNoneInsecure:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "`SameSite=None`" attribute but did not have the "Secure" attribute, which is required in order to use "`SameSite=None`".',blockedReasonOverwriteSecure:"This attempt to set a cookie via a `Set-Cookie` header was blocked because it was not sent over a secure connection and would have overwritten a cookie with the Secure attribute.",blockedReasonInvalidDomain:"This attempt to set a cookie via a `Set-Cookie` header was blocked because its Domain attribute was invalid with regards to the current host url.",blockedReasonInvalidPrefix:'This attempt to set a cookie via a `Set-Cookie` header was blocked because it used the "`__Secure-`" or "`__Host-`" prefix in its name and broke the additional rules applied to cookies with these prefixes as defined in `https://tools.ietf.org/html/draft-west-cookie-prefixes-05`.',thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize:"This attempt to set a cookie via a `Set-Cookie` header was blocked because the cookie was too large. The combined size of the name and value must be less than or equal to 4096 characters.",setcookieHeaderIsIgnoredIn:"Set-Cookie header is ignored in response from url: {PH1}. The combined size of the name and value must be less than or equal to 4096 characters."},Se=s.i18n.registerUIStrings("core/sdk/NetworkRequest.ts",ke),we=s.i18n.getLocalizedString.bind(void 0,Se);var Ce,Te,Re,xe;!function(e){e.HTML="text/html",e.XML="text/xml",e.PLAIN="text/plain",e.XHTML="application/xhtml+xml",e.SVG="image/svg+xml",e.CSS="text/css",e.XSL="text/xsl",e.VTT="text/vtt",e.PDF="application/pdf",e.EVENTSTREAM="text/event-stream"}(Ce||(Ce={}));class Me extends e.ObjectWrapper.ObjectWrapper{#ke;#Se;#we;#Ce;#Te;#Re;#xe;#Me;#Pe;#Le;#Ee;#Ae;#Oe;#Ne;#Fe;#Be;#De;statusCode;statusText;requestMethod;requestTime;protocol;alternateProtocolUsage;mixedContentType;#Ue;#He;#qe;#_e;#ze;#je;#We;#Ve;#Ge;#Ke;#$e;#Qe;#Xe;#Je;#Ye;#Ze;#et;#tt;#nt;#rt;#st;connectionId;connectionReused;hasNetworkData;#it;#at;#ot;#lt;#dt;#ct;#ht;#ut;#gt;#pt;localizedFailDescription;#mt;#ft;#bt;#ye;#yt;#vt;#It;#kt;#St;#u;#wt;#Ct;#Tt;#Rt;#xt;#Mt;#Pt;#Lt;#Et;#At;#Ot;#Nt;#Ft;#Bt;#Dt;#Ut;#Ht;#qt;#_t;#zt;#jt;#Wt;#Vt;#Gt;#Kt=new Map;constructor(t,n,r,s,i,a,o,l){super(),this.#ke=t,this.#Se=n,this.setUrl(r),this.#we=s,this.#Ce=i,this.#Te=a,this.#Re=o,this.#xe=l,this.#Me=null,this.#Pe=null,this.#Le=null,this.#Ee=!1,this.#Ae=null,this.#Oe=-1,this.#Ne=-1,this.#Fe=-1,this.#Be=void 0,this.#De=void 0,this.statusCode=0,this.statusText="",this.requestMethod="",this.requestTime=0,this.protocol="",this.alternateProtocolUsage=void 0,this.mixedContentType="none",this.#Ue=null,this.#He=null,this.#qe=null,this.#_e=null,this.#ze=null,this.#je=e.ResourceType.resourceTypes.Other,this.#We=null,this.#Ve=[],this.#Ge=[],this.#Ke={},this.#$e="",this.#Qe=[],this.#Je=[],this.#Ye=[],this.#Ze={},this.#et="",this.#tt="Unknown",this.#nt=null,this.#rt="unknown",this.#st=null,this.connectionId="0",this.connectionReused=!1,this.hasNetworkData=!1,this.#it=null,this.#at=Promise.resolve(null),this.#ot=!1,this.#lt=!1,this.#dt=[],this.#ct=[],this.#ht=[],this.#pt=!1,this.#ut=null,this.#gt=null,this.localizedFailDescription=null,this.#Vt=null,this.#Gt=!1}static create(e,t,n,r,s,i,a){return new Me(e,e,t,n,r,s,i,a)}static createForWebSocket(e,n,r){return new Me(e,e,n,t.DevToolsPath.EmptyUrlString,null,null,r||null)}static createWithoutBackendRequest(e,t,n,r){return new Me(e,void 0,t,n,null,null,r)}identityCompare(e){const t=this.requestId(),n=e.requestId();return t>n?1:te&&(this.#ft=e)),this.dispatchEventToListeners(Te.TimingChanged,this)}get duration(){return-1===this.#Fe||-1===this.#Ne?-1:this.#Fe-this.#Ne}get latency(){return-1===this.#ft||-1===this.#Ne?-1:this.#ft-this.#Ne}get resourceSize(){return this.#Et||0}set resourceSize(e){this.#Et=e}get transferSize(){return this.#bt||0}increaseTransferSize(e){this.#bt=(this.#bt||0)+e}setTransferSize(e){this.#bt=e}get finished(){return this.#ye}set finished(e){this.#ye!==e&&(this.#ye=e,e&&this.dispatchEventToListeners(Te.FinishedLoading,this))}get failed(){return this.#yt}set failed(e){this.#yt=e}get canceled(){return this.#vt}set canceled(e){this.#vt=e}get preserved(){return this.#It}set preserved(e){this.#It=e}blockedReason(){return this.#Be}setBlockedReason(e){this.#Be=e}corsErrorStatus(){return this.#De}setCorsErrorStatus(e){this.#De=e}wasBlocked(){return Boolean(this.#Be)}cached(){return(Boolean(this.#At)||Boolean(this.#Ot))&&!this.#bt}cachedInMemory(){return Boolean(this.#At)&&!this.#bt}fromPrefetchCache(){return Boolean(this.#Nt)}setFromMemoryCache(){this.#At=!0,this.#Bt=void 0}get fromDiskCache(){return this.#Ot}setFromDiskCache(){this.#Ot=!0}setFromPrefetchCache(){this.#Nt=!0}get fetchedViaServiceWorker(){return Boolean(this.#Ft)}set fetchedViaServiceWorker(e){this.#Ft=e}initiatedByServiceWorker(){const e=ne.forRequest(this);return!!e&&e.target().type()===_.ServiceWorker}get timing(){return this.#Bt}set timing(e){if(!e||this.#At)return;this.#Ne=e.requestTime;const t=e.requestTime+e.receiveHeadersEnd/1e3;((this.#ft||-1)<0||this.#ft>t)&&(this.#ft=t),this.#Ne>this.#ft&&(this.#ft=this.#Ne),this.#Bt=e,this.dispatchEventToListeners(Te.TimingChanged,this)}setConnectTimingFromExtraInfo(e){this.#Ne=e.requestTime,this.dispatchEventToListeners(Te.TimingChanged,this)}get mimeType(){return this.#kt}set mimeType(e){this.#kt=e}get displayName(){return this.#St.displayName}name(){return this.#u||this.parseNameAndPathFromURL(),this.#u}path(){return this.#wt||this.parseNameAndPathFromURL(),this.#wt}parseNameAndPathFromURL(){if(this.#St.isDataURL())this.#u=this.#St.dataURLDisplayName(),this.#wt="";else if(this.#St.isBlobURL())this.#u=this.#St.url,this.#wt="";else if(this.#St.isAboutBlank())this.#u=this.#St.url,this.#wt="";else{this.#wt=this.#St.host+this.#St.folderPathComponents;const n=ne.forRequest(this),r=n?e.ParsedURL.ParsedURL.fromString(n.target().inspectedURL()):null;this.#wt=t.StringUtilities.trimURL(this.#wt,r?r.host:""),this.#St.lastPathComponent||this.#St.queryParams?this.#u=this.#St.lastPathComponent+(this.#St.queryParams?"?"+this.#St.queryParams:""):this.#St.folderPathComponents?(this.#u=this.#St.folderPathComponents.substring(this.#St.folderPathComponents.lastIndexOf("/")+1)+"/",this.#wt=this.#wt.substring(0,this.#wt.lastIndexOf("/"))):(this.#u=this.#St.host,this.#wt="")}}get folder(){let e=this.#St.path;const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const n=e.lastIndexOf("/");return-1!==n?e.substring(0,n):""}get pathname(){return this.#St.path}resourceType(){return this.#je}setResourceType(e){this.#je=e}get domain(){return this.#St.host}get scheme(){return this.#St.scheme}redirectSource(){return this.#Me}setRedirectSource(e){this.#Me=e}preflightRequest(){return this.#Pe}setPreflightRequest(e){this.#Pe=e}preflightInitiatorRequest(){return this.#Le}setPreflightInitiatorRequest(e){this.#Le=e}isPreflightRequest(){return null!==this.#Re&&void 0!==this.#Re&&"preflight"===this.#Re.type}redirectDestination(){return this.#Ae}setRedirectDestination(e){this.#Ae=e}requestHeaders(){return this.#Ye}setRequestHeaders(e){this.#Ye=e,this.dispatchEventToListeners(Te.RequestHeadersChanged)}requestHeadersText(){return this.#Dt}setRequestHeadersText(e){this.#Dt=e,this.dispatchEventToListeners(Te.RequestHeadersChanged)}requestHeaderValue(e){return this.#Ze[e]||(this.#Ze[e]=this.computeHeaderValue(this.requestHeaders(),e)),this.#Ze[e]}requestFormData(){return this.#at||(this.#at=ne.requestPostData(this)),this.#at}setRequestFormData(e,t){this.#at=e&&null===t?null:Promise.resolve(t),this.#it=null}filteredProtocolName(){const e=this.protocol.toLowerCase();return"h2"===e?"http/2.0":e.replace(/^http\/2(\.0)?\+/,"http/2.0+")}requestHttpVersion(){const e=this.requestHeadersText();if(!e){const e=this.requestHeaderValue("version")||this.requestHeaderValue(":version");return e||this.filteredProtocolName()}const t=e.split(/\r\n/)[0].match(/(HTTP\/\d+\.\d+)$/);return t?t[1]:"HTTP/0.9"}get responseHeaders(){return this.#Ut||[]}set responseHeaders(e){this.#Ut=e,this.#Ht=void 0,this.#_t=void 0,this.#qt=void 0,this.#Ke={},this.dispatchEventToListeners(Te.ResponseHeadersChanged)}get originalResponseHeaders(){return this.#Qe}set originalResponseHeaders(e){this.#Qe=e,this.#Xe=void 0}get setCookieHeaders(){return this.#Je}set setCookieHeaders(e){this.#Je=e}get responseHeadersText(){return this.#$e}set responseHeadersText(e){this.#$e=e,this.dispatchEventToListeners(Te.ResponseHeadersChanged)}get sortedResponseHeaders(){return void 0!==this.#Ht?this.#Ht:(this.#Ht=this.responseHeaders.slice(),this.#Ht.sort((function(e,n){return t.StringUtilities.compare(e.name.toLowerCase(),n.name.toLowerCase())||t.StringUtilities.compare(e.value,n.value)})))}get sortedOriginalResponseHeaders(){return void 0!==this.#Xe?this.#Xe:(this.#Xe=this.originalResponseHeaders.slice(),this.#Xe.sort((function(e,n){return t.StringUtilities.compare(e.name.toLowerCase(),n.name.toLowerCase())||t.StringUtilities.compare(e.value,n.value)})))}hasOverriddenHeaders(){if(!this.#Qe.length)return!1;const e=this.sortedResponseHeaders,t=this.sortedOriginalResponseHeaders;if(t.length!==e.length)return!0;for(let n=0;ne.cookie)),...this.blockedResponseCookies().map((e=>e.cookie))].filter((e=>Boolean(e)))}get serverTimings(){return void 0===this.#_t&&(this.#_t=ve.parseHeaders(this.responseHeaders)),this.#_t}queryString(){if(void 0!==this.#zt)return this.#zt;let e=null;const t=this.url(),n=t.indexOf("?");if(-1!==n){e=t.substring(n+1);const r=e.indexOf("#");-1!==r&&(e=e.substring(0,r))}return this.#zt=e,this.#zt}get queryParameters(){if(this.#jt)return this.#jt;const e=this.queryString();return e?(this.#jt=this.parseParameters(e),this.#jt):null}async parseFormParameters(){const e=this.requestContentType();if(!e)return null;if(e.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){const e=await this.requestFormData();return e?this.parseParameters(e):null}const t=e.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/);if(!t)return null;const n=t[1];if(!n)return null;const r=await this.requestFormData();return r?this.parseMultipartFormDataParameters(r,n):null}formParameters(){return this.#it||(this.#it=this.parseFormParameters()),this.#it}responseHttpVersion(){const e=this.#$e;if(!e){const e=this.responseHeaderValue("version")||this.responseHeaderValue(":version");return e||this.filteredProtocolName()}const t=e.split(/\r\n/)[0].match(/^(HTTP\/\d+\.\d+)/);return t?t[1]:"HTTP/0.9"}parseParameters(e){return e.split("&").map((function(e){const t=e.indexOf("=");return-1===t?{name:e,value:""}:{name:e.substring(0,t),value:e.substring(t+1)}}))}parseMultipartFormDataParameters(e,n){const r=t.StringUtilities.escapeForRegExp(n),s=new RegExp('^\\r\\ncontent-disposition\\s*:\\s*form-data\\s*;\\s*name="([^"]*)"(?:\\s*;\\s*filename="([^"]*)")?(?:\\r\\ncontent-type\\s*:\\s*([^\\r\\n]*))?\\r\\n\\r\\n(.*)\\r\\n$',"is");return e.split(new RegExp(`--${r}(?:--s*$)?`,"g")).reduce((function(e,t){const[n,r,i,a,o]=t.match(s)||[];if(!n)return e;const l=i||a?we(ke.binary):o;return e.push({name:r,value:l}),e}),[])}computeHeaderValue(e,t){t=t.toLowerCase();const n=[];for(let r=0;r=400}setInitialPriority(e){this.#Ue=e}initialPriority(){return this.#Ue}setPriority(e){this.#He=e}priority(){return this.#He||this.#Ue||null}setSignedExchangeInfo(e){this.#qe=e}signedExchangeInfo(){return this.#qe}setWebBundleInfo(e){this.#_e=e}webBundleInfo(){return this.#_e}setWebBundleInnerRequestInfo(e){this.#ze=e}webBundleInnerRequestInfo(){return this.#ze}async populateImageSource(e){const{content:t,encoded:n}=await this.contentData();let s=r.ContentProvider.contentAsDataURL(t,this.#kt,n);if(null===s&&!this.#yt){(this.responseHeaderValue("cache-control")||"").includes("no-cache")||(s=this.#mt)}null!==s&&(e.src=s)}initiator(){return this.#Re||null}hasUserGesture(){return this.#xe??null}frames(){return this.#Ve}addProtocolFrameError(e,t){this.addFrame({type:xe.Error,text:e,time:this.pseudoWallTime(t),opCode:-1,mask:!1})}addProtocolFrame(e,t,n){const r=n?xe.Send:xe.Receive;this.addFrame({type:r,text:e.payloadData,time:this.pseudoWallTime(t),opCode:e.opcode,mask:e.mask})}addFrame(e){this.#Ve.push(e),this.dispatchEventToListeners(Te.WebsocketFrameAdded,e)}eventSourceMessages(){return this.#Ge}addEventSourceMessage(e,t,n,r){const s={time:this.pseudoWallTime(e),eventName:t,eventId:n,data:r};this.#Ge.push(s),this.dispatchEventToListeners(Te.EventSourceMessageAdded,s)}markAsRedirect(e){this.#Ee=!0,this.#ke=`${this.#Se}:redirected.${e}`}isRedirect(){return this.#Ee}setRequestIdForTest(e){this.#Se=e,this.#ke=e}charset(){const e=this.responseHeaderValue("content-type");if(!e)return null;const t=e.replace(/ /g,"").split(";").filter((e=>e.toLowerCase().startsWith("charset="))).map((e=>e.slice("charset=".length)));return t.length?t[0]:null}addExtraRequestInfo(e){this.#dt=e.blockedRequestCookies,this.#ct=e.includedRequestCookies,this.setRequestHeaders(e.requestHeaders),this.#ot=!0,this.setRequestHeadersText(""),this.#Ct=e.clientSecurityState,this.setConnectTimingFromExtraInfo(e.connectTiming),this.#pt=e.siteHasCookieInOtherPartition??!1}hasExtraRequestInfo(){return this.#ot}blockedRequestCookies(){return this.#dt}includedRequestCookies(){return this.#ct}hasRequestCookies(){return this.#ct.length>0||this.#dt.length>0}siteHasCookieInOtherPartition(){return this.#pt}static parseStatusTextFromResponseHeadersText(e){return e.split("\r")[0].split(" ").slice(2).join(" ")}addExtraResponseInfo(e){if(this.#ht=e.blockedResponseCookies,this.#ut=e.cookiePartitionKey||null,this.#gt=e.cookiePartitionKeyOpaque||null,this.responseHeaders=e.responseHeaders,this.originalResponseHeaders=e.responseHeaders.map((e=>({...e}))),e.responseHeadersText){if(this.responseHeadersText=e.responseHeadersText,!this.requestHeadersText()){let e=`${this.requestMethod} ${this.parsedURL.path}`;this.parsedURL.queryParams&&(e+=`?${this.parsedURL.queryParams}`),e+=" HTTP/1.1\r\n";for(const{name:t,value:n}of this.requestHeaders())e+=`${t}: ${n}\r\n`;this.setRequestHeadersText(e)}this.statusText=Me.parseStatusTextFromResponseHeadersText(e.responseHeadersText)}this.#tt=e.resourceIPAddressSpace,e.statusCode&&(this.statusCode=e.statusCode),this.#lt=!0;const t=ne.forRequest(this);if(t)for(const e of this.#ht)if(e.blockedReasons.includes("NameValuePairExceedsMaxSize")){const e=we(ke.setcookieHeaderIsIgnoredIn,{PH1:this.url()});t.dispatchEventToListeners(re.MessageGenerated,{message:e,requestId:this.#ke,warning:!0})}}hasExtraResponseInfo(){return this.#lt}blockedResponseCookies(){return this.#ht}responseCookiesPartitionKey(){return this.#ut}responseCookiesPartitionKeyOpaque(){return this.#gt}redirectSourceSignedExchangeInfoHasNoErrors(){return null!==this.#Me&&null!==this.#Me.#qe&&!this.#Me.#qe.errors}clientSecurityState(){return this.#Ct}setTrustTokenParams(e){this.#Tt=e}trustTokenParams(){return this.#Tt}setTrustTokenOperationDoneEvent(e){this.#Rt=e,this.dispatchEventToListeners(Te.TrustTokenResultAdded)}trustTokenOperationDoneEvent(){return this.#Rt}setIsSameSite(e){this.#Vt=e}isSameSite(){return this.#Vt}getAssociatedData(e){return this.#Kt.get(e)||null}setAssociatedData(e,t){this.#Kt.set(e,t)}deleteAssociatedData(e){this.#Kt.delete(e)}}!function(e){e.FinishedLoading="FinishedLoading",e.TimingChanged="TimingChanged",e.RemoteAddressChanged="RemoteAddressChanged",e.RequestHeadersChanged="RequestHeadersChanged",e.ResponseHeadersChanged="ResponseHeadersChanged",e.WebsocketFrameAdded="WebsocketFrameAdded",e.EventSourceMessageAdded="EventSourceMessageAdded",e.TrustTokenResultAdded="TrustTokenResultAdded"}(Te||(Te={})),function(e){e.Other="other",e.Parser="parser",e.Redirect="redirect",e.Script="script",e.Preload="preload",e.SignedExchange="signedExchange",e.Preflight="preflight"}(Re||(Re={})),function(e){e.Send="send",e.Receive="receive",e.Error="error"}(xe||(xe={}));var Pe=Object.freeze({__proto__:null,get MIME_TYPE(){return Ce},NetworkRequest:Me,get Events(){return Te},get InitiatorType(){return Re},get WebSocketFrameType(){return xe},cookieBlockedReasonToUiString:function(e){switch(e){case"SecureOnly":return we(ke.secureOnly);case"NotOnPath":return we(ke.notOnPath);case"DomainMismatch":return we(ke.domainMismatch);case"SameSiteStrict":return we(ke.sameSiteStrict);case"SameSiteLax":return we(ke.sameSiteLax);case"SameSiteUnspecifiedTreatedAsLax":return we(ke.sameSiteUnspecifiedTreatedAsLax);case"SameSiteNoneInsecure":return we(ke.sameSiteNoneInsecure);case"UserPreferences":return we(ke.userPreferences);case"UnknownError":return we(ke.unknownError);case"SchemefulSameSiteStrict":return we(ke.schemefulSameSiteStrict);case"SchemefulSameSiteLax":return we(ke.schemefulSameSiteLax);case"SchemefulSameSiteUnspecifiedTreatedAsLax":return we(ke.schemefulSameSiteUnspecifiedTreatedAsLax);case"SamePartyFromCrossPartyContext":return we(ke.samePartyFromCrossPartyContext);case"NameValuePairExceedsMaxSize":return we(ke.nameValuePairExceedsMaxSize)}return""},setCookieBlockedReasonToUiString:function(e){switch(e){case"SecureOnly":return we(ke.blockedReasonSecureOnly);case"SameSiteStrict":return we(ke.blockedReasonSameSiteStrictLax,{PH1:"SameSite=Strict"});case"SameSiteLax":return we(ke.blockedReasonSameSiteStrictLax,{PH1:"SameSite=Lax"});case"SameSiteUnspecifiedTreatedAsLax":return we(ke.blockedReasonSameSiteUnspecifiedTreatedAsLax);case"SameSiteNoneInsecure":return we(ke.blockedReasonSameSiteNoneInsecure);case"UserPreferences":return we(ke.thisSetcookieWasBlockedDueToUser);case"SyntaxError":return we(ke.thisSetcookieHadInvalidSyntax);case"SchemeNotSupported":return we(ke.theSchemeOfThisConnectionIsNot);case"OverwriteSecure":return we(ke.blockedReasonOverwriteSecure);case"InvalidDomain":return we(ke.blockedReasonInvalidDomain);case"InvalidPrefix":return we(ke.blockedReasonInvalidPrefix);case"UnknownError":return we(ke.anUnknownErrorWasEncounteredWhenTrying);case"SchemefulSameSiteStrict":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax,{PH1:"SameSite=Strict"});case"SchemefulSameSiteLax":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax,{PH1:"SameSite=Lax"});case"SchemefulSameSiteUnspecifiedTreatedAsLax":return we(ke.thisSetcookieDidntSpecifyASamesite);case"SamePartyFromCrossPartyContext":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSameparty);case"SamePartyConflictsWithOtherAttributes":return we(ke.thisSetcookieWasBlockedBecauseItHadTheSamepartyAttribute);case"NameValuePairExceedsMaxSize":return we(ke.thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize)}return""},cookieBlockedReasonToAttribute:function(e){switch(e){case"SecureOnly":return D.Secure;case"NotOnPath":return D.Path;case"DomainMismatch":return D.Domain;case"SameSiteStrict":case"SameSiteLax":case"SameSiteUnspecifiedTreatedAsLax":case"SameSiteNoneInsecure":case"SchemefulSameSiteStrict":case"SchemefulSameSiteLax":case"SchemefulSameSiteUnspecifiedTreatedAsLax":return D.SameSite;case"SamePartyFromCrossPartyContext":case"NameValuePairExceedsMaxSize":case"UserPreferences":case"UnknownError":return null}return null},setCookieBlockedReasonToAttribute:function(e){switch(e){case"SecureOnly":case"OverwriteSecure":return D.Secure;case"SameSiteStrict":case"SameSiteLax":case"SameSiteUnspecifiedTreatedAsLax":case"SameSiteNoneInsecure":case"SchemefulSameSiteStrict":case"SchemefulSameSiteLax":case"SchemefulSameSiteUnspecifiedTreatedAsLax":return D.SameSite;case"InvalidDomain":return D.Domain;case"InvalidPrefix":return D.Name;case"SamePartyConflictsWithOtherAttributes":case"SamePartyFromCrossPartyContext":case"NameValuePairExceedsMaxSize":case"UserPreferences":case"SyntaxError":case"SchemeNotSupported":case"UnknownError":return null}return null}});class Le{static fromLocalObject(e){return new Fe(e)}static type(e){if(null===e)return"null";const t=typeof e;return"object"!==t&&"function"!==t?t:e.type}static isNullOrUndefined(e){if(void 0===e)return!0;switch(e.type){case"object":return"null"===e.subtype;case"undefined":return!0;default:return!1}}static arrayNameFromDescription(e){return e.replace(Ue,"").replace(He,"")}static arrayLength(e){if("array"!==e.subtype&&"typedarray"!==e.subtype)return 0;const t=e.description&&e.description.match(Ue),n=e.description&&e.description.match(He);return t?parseInt(t[1],10):n?parseInt(n[1],10):0}static arrayBufferByteLength(e){if("arraybuffer"!==e.subtype)return 0;const t=e.description&&e.description.match(Ue);return t?parseInt(t[1],10):0}static unserializableDescription(e){const t=typeof e;if("number"===t){const t=String(e);if(0===e&&1/e<0)return"-0";if("NaN"===t||"Infinity"===t||"-Infinity"===t)return t}return"bigint"===t?e+"n":null}static toCallArgument(e){const t=typeof e;if("undefined"===t)return{};const n=Le.unserializableDescription(e);if("number"===t)return null!==n?{unserializableValue:n}:{value:e};if("bigint"===t)return{unserializableValue:n};if("string"===t||"boolean"===t)return{value:e};if(!e)return{value:null};const r=e;if(e instanceof Le){const t=e.unserializableValue();if(void 0!==t)return{unserializableValue:t}}else if(void 0!==r.unserializableValue)return{unserializableValue:r.unserializableValue};return void 0!==r.objectId?{objectId:r.objectId}:{value:r.value}}static async loadFromObjectPerProto(e,t,n=!1){const r=await Promise.all([e.getAllProperties(!0,t,n),e.getOwnProperties(t,n)]),s=r[0].properties,i=r[1].properties,a=r[1].internalProperties;if(!i||!s)return{properties:null,internalProperties:null};const o=new Map,l=[];for(let e=0;e100){r+=",…";break}e&&(r+=", "),r+=t}return r+=t,r}get type(){return typeof this.valueInternal}get subtype(){return null===this.valueInternal?"null":Array.isArray(this.valueInternal)?"array":this.valueInternal instanceof Date?"date":void 0}get hasChildren(){return"object"==typeof this.valueInternal&&null!==this.valueInternal&&Boolean(Object.keys(this.valueInternal).length)}async getOwnProperties(e,t=!1){let n=this.children();return t&&(n=n.filter((e=>!function(e){const t=Number(e)>>>0;return String(t)===e}(e.name)))),{properties:n,internalProperties:null}}async getAllProperties(e,t,n=!1){return e?{properties:[],internalProperties:null}:await this.getOwnProperties(t,n)}children(){if(!this.hasChildren)return[];const e=this.valueInternal;return this.#in||(this.#in=Object.keys(e).map((function(t){let n=e[t];return n instanceof Le||(n=Le.fromLocalObject(n)),new Ne(t,n)}))),this.#in}arrayLength(){return Array.isArray(this.valueInternal)?this.valueInternal.length:0}async callFunction(e,t){const n=this.valueInternal,r=t?t.map((e=>e.value)):[];let s,i=!1;try{s=e.apply(n,r)}catch(e){i=!0}return{object:Le.fromLocalObject(s),wasThrown:i}}async callFunctionJSON(e,t){const n=this.valueInternal,r=t?t.map((e=>e.value)):[];let s;try{s=e.apply(n,r)}catch(e){s=null}return s}}class Be{#an;constructor(e){this.#an=e}static objectAsArray(e){if(!e||"object"!==e.type||"array"!==e.subtype&&"typedarray"!==e.subtype)throw new Error("Object is empty or not an array");return new Be(e)}static createFromRemoteObjects(e){if(!e.length)throw new Error("Input array is empty");const t=[];for(let n=0;n1)return new Array(arguments);return[arguments[0]]}),t).then((function(e){if(e.wasThrown||!e.object)throw new Error("Call function throws exceptions or returns empty value");return Be.objectAsArray(e.object)}))}at(e){if(e<0||e>this.#an.arrayLength())throw new Error("Out of range");return this.#an.callFunction((function(e){return this[e]}),[Le.toCallArgument(e)]).then((function(e){if(e.wasThrown||!e.object)throw new Error("Exception in callFunction or result value is empty");return e.object}))}length(){return this.#an.arrayLength()}map(e){const t=[];for(let n=0;n=this.byteLength())throw new RangeError("start is out of range");if(tthis.byteLength())throw new RangeError("end is out of range");return await this.#an.callFunctionJSON((function(e,t){return[...new Uint8Array(this,e,t)]}),[{value:e},{value:t-e}])}object(){return this.#an}},RemoteArray:Be,RemoteFunction:De});class _e{#on;#ln;#dn;#cn;#hn;constructor(e){this.#on=e.fontFamily,this.#ln=e.fontVariationAxes||[],this.#dn=new Map,this.#cn=e.src,this.#hn=e.fontDisplay;for(const e of this.#ln)this.#dn.set(e.tag,e)}getFontFamily(){return this.#on}getSrc(){return this.#cn}getFontDisplay(){return this.#hn}getVariationAxisByTag(e){return this.#dn.get(e)}}var ze=Object.freeze({__proto__:null,CSSFontFace:_e});class je{text="";range;styleSheetId;cssModel;constructor(e){this.cssModel=e}rebase(e){this.styleSheetId===e.styleSheetId&&this.range&&(e.oldRange.equal(this.range)?this.reinitialize(e.payload):this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}equal(e){return!!(this.styleSheetId&&this.range&&e.range)&&(this.styleSheetId===e.styleSheetId&&this.range.equal(e.range))}lineNumberInSource(){if(this.range)return this.header()?.lineNumberInSource(this.range.startLine)}columnNumberInSource(){if(this.range)return this.header()?.columnNumberInSource(this.range.startLine,this.range.startColumn)}header(){return this.styleSheetId?this.cssModel.styleSheetHeaderForId(this.styleSheetId):null}rawLocation(){const e=this.header();if(!e||void 0===this.lineNumberInSource())return null;const t=Number(this.lineNumberInSource());return new rn(e,t,this.columnNumberInSource())}}var We=Object.freeze({__proto__:null,CSSQuery:je});class Ve extends je{name;physicalAxes;logicalAxes;static parseContainerQueriesPayload(e,t){return t.map((t=>new Ve(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.name=e.name,this.physicalAxes=e.physicalAxes,this.logicalAxes=e.logicalAxes}active(){return!0}async getContainerForNode(e){const t=await this.cssModel.domModel().getContainerForNode(e,this.name,this.physicalAxes,this.logicalAxes);if(t)return new Ge(t)}}class Ge{containerNode;constructor(e){this.containerNode=e}async getContainerSizeDetails(){const e=await this.containerNode.domModel().cssModel().getComputedStyle(this.containerNode.id);if(!e)return;const t=e.get("container-type"),n=e.get("contain"),r=e.get("writing-mode");if(!t||!n||!r)return;const s=Ke(`${t} ${n}`),i=$e(s,r);let a,o;return"Both"!==i&&"Horizontal"!==i||(a=e.get("width")),"Both"!==i&&"Vertical"!==i||(o=e.get("height")),{queryAxis:s,physicalAxis:i,width:a,height:o}}}const Ke=e=>{const t=e.split(" ");let n=!1,r=!1;for(const e of t){if("size"===e)return"size";n=n||"inline-size"===e,r=r||"block-size"===e}return n&&r?"size":n?"inline-size":r?"block-size":""},$e=(e,t)=>{const n=t.startsWith("vertical");switch(e){case"":return"";case"size":return"Both";case"inline-size":return n?"Vertical":"Horizontal";case"block-size":return n?"Horizontal":"Vertical"}};var Qe=Object.freeze({__proto__:null,CSSContainerQuery:Ve,CSSContainerQueryContainer:Ge,getQueryAxis:Ke,getPhysicalAxisFromQueryAxis:$e});class Xe extends je{static parseLayerPayload(e,t){return t.map((t=>new Xe(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId}active(){return!0}}var Je=Object.freeze({__proto__:null,CSSLayer:Xe});class Ye{#un;#gn;constructor(e){this.#un=e.active,this.#gn=[];for(let t=0;tnew et(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){if(this.text=e.text,this.source=e.source,this.sourceURL=e.sourceURL||"",this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.mediaList=null,e.mediaList){this.mediaList=[];for(let t=0;tnew nt(e,t)))}constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId}active(){return!0}}var rt=Object.freeze({__proto__:null,CSSScope:nt});class st extends je{static parseSupportsPayload(e,t){return t.map((t=>new st(e,t)))}#yn=!0;constructor(e,t){super(e),this.reinitialize(t)}reinitialize(e){this.text=e.text,this.range=e.range?r.TextRange.TextRange.fromObject(e.range):null,this.styleSheetId=e.styleSheetId,this.#yn=e.active}active(){return this.#yn}}var it=Object.freeze({__proto__:null,CSSSupports:st});class at{ownerStyle;index;name;value;important;disabled;parsedOk;implicit;text;range;#yn;#vn;#fn;#In;#kn=[];constructor(e,t,n,s,i,a,o,l,d,c,h){if(this.ownerStyle=e,this.index=t,this.name=n,this.value=s,this.important=i,this.disabled=a,this.parsedOk=o,this.implicit=l,this.text=d,this.range=c?r.TextRange.TextRange.fromObject(c):null,this.#yn=!0,this.#vn=null,this.#fn=null,h&&h.length>0)for(const n of h)this.#kn.push(new at(e,++t,n.name,n.value,i,a,o,!0));else{const r=v().getLonghands(n);for(const n of r||[])this.#kn.push(new at(e,++t,n,"",i,a,o,!0))}}static parsePayload(e,t,n){return new at(e,t,n.name,n.value,n.important||!1,n.disabled||!1,!("parsedOk"in n)||Boolean(n.parsedOk),Boolean(n.implicit),n.text,n.range,n.longhandProperties)}ensureRanges(){if(this.#vn&&this.#fn)return;const e=this.range,t=this.text?new r.Text.Text(this.text):null;if(!e||!t)return;const n=t.value().indexOf(this.name),s=t.value().lastIndexOf(this.value);if(-1===n||-1===s||n>s)return;const i=new r.TextRange.SourceRange(n,this.name.length),a=new r.TextRange.SourceRange(s,this.value.length);function o(e,t,n){return 0===e.startLine&&(e.startColumn+=n,e.endColumn+=n),e.startLine+=t,e.endLine+=t,e}this.#vn=o(t.toTextRange(i),e.startLine,e.startColumn),this.#fn=o(t.toTextRange(a),e.startLine,e.startColumn)}nameRange(){return this.ensureRanges(),this.#vn}valueRange(){return this.ensureRanges(),this.#fn}rebase(e){this.ownerStyle.styleSheetId===e.styleSheetId&&this.range&&(this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}setActive(e){this.#yn=e}get propertyText(){return void 0!==this.text?this.text:""===this.name?"":this.name+": "+this.value+(this.important?" !important":"")+";"}activeInStyle(){return this.#yn}trimmedValueWithoutImportant(){const e="!important";return this.value.endsWith(e)?this.value.slice(0,-e.length).trim():this.value.trim()}async setText(n,s,a){if(!this.ownerStyle)throw new Error("No ownerStyle for property");if(!this.ownerStyle.styleSheetId)throw new Error("No owner style id");if(!this.range||!this.ownerStyle.range)throw new Error("Style not editable");if(s&&(i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited),this.name.startsWith("--")&&i.userMetrics.actionTaken(i.UserMetrics.Action.CustomPropertyEdited)),a&&n===this.propertyText)return this.ownerStyle.cssModel().domModel().markUndoableState(!s),!0;const o=this.range.relativeTo(this.ownerStyle.range.startLine,this.ownerStyle.range.startColumn),l=this.ownerStyle.cssText?this.detectIndentation(this.ownerStyle.cssText):e.Settings.Settings.instance().moduleSetting("textEditorIndent").get(),d=this.ownerStyle.cssText?l.substring(0,this.ownerStyle.range.endColumn):"",c=new r.Text.Text(this.ownerStyle.cssText||"").replaceRange(o,t.StringUtilities.sprintf(";%s;",n)),h=await at.formatStyle(c,l,d);return this.ownerStyle.setText(h,s)}static async formatStyle(e,t,n){const s=t.substring(n.length)+t;t&&(t="\n"+t);let i="",a="",o="",l=!1,d=!1;const c=r.CodeMirrorUtils.createCssTokenizer();return await c("*{"+e+"}",(function(e,n){if(!l){const r=n?.includes("comment")&&function(e){const t=e.indexOf(":");if(-1===t)return!1;const n=e.substring(2,t).trim();return v().isCSSPropertyName(n)}(e),s=n?.includes("string")||n?.includes("meta")||n?.includes("property")||n?.includes("variableName")&&"variableName.function"!==n;return r?i=i.trimEnd()+t+e:s?(l=!0,o=e):(";"!==e||d)&&(i+=e,e.trim()&&!n?.includes("comment")&&(d=";"!==e)),void("{"!==e||n||(d=!1))}if("}"===e||";"===e){const n=o.trim();return i=i.trimEnd()+t+n+(n.endsWith(":")?" ":"")+e,d=!1,l=!1,void(a="")}if(v().isGridAreaDefiningProperty(a)){const t=b.exec(e);t&&0===t.index&&!o.trimEnd().endsWith("]")&&(o=o.trimEnd()+"\n"+s)}a||":"!==e||(a=o);o+=e})),l&&(i+=o),i=i.substring(2,i.length-1).trimEnd(),i+(t?"\n"+n:"")}detectIndentation(e){const t=e.split("\n");return t.length<2?"":r.TextUtils.Utils.lineIndent(t[1])}setValue(e,t,n,r){const s=this.name+": "+e+(this.important?" !important":"")+";";this.setText(s,t,n).then(r)}async setDisabled(e){if(!this.ownerStyle)return!1;if(e===this.disabled)return!0;if(!this.text)return!0;const t=this.text.trim(),n=e=>e+(e.endsWith(";")?"":";");let r;return r=e?"/* "+n(t)+" */":n(this.text.substring(2,t.length-2).trim()),this.setText(r,!0,!0)}setDisplayedStringForInvalidProperty(e){this.#In=e}getInvalidStringForInvalidProperty(){return this.#In}getLonghandProperties(){return this.#kn}}var ot,lt=Object.freeze({__proto__:null,CSSProperty:at});class dt{#Sn;parentRule;#wn;styleSheetId;range;cssText;#Cn;#Tn;#Rn;#xn;type;constructor(e,t,n,r){this.#Sn=e,this.parentRule=t,this.#Mn(n),this.type=r}rebase(e){if(this.styleSheetId===e.styleSheetId&&this.range)if(e.oldRange.equal(this.range))this.#Mn(e.payload);else{this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange);for(let t=0;t0||!l.validContent)continue;let s=0;for(const i of l.validContent.split(";")){const a=i.trim();if(a){let o,l;const d=a.indexOf(":");-1===d?(o=a,l=""):(o=a.substring(0,d).trim(),l=a.substring(d+1).trim());const c=new r.TextRange.TextRange(e,s,e,s+i.length);this.#wn.push(new at(this,this.#wn.length,o,l,!1,!1,!1,!1,i,c.relativeFrom(t,n)))}s+=i.length+1}}function d(e,t){t.validContent="";for(let n=0;n=0;--e)if(this.allProperties()[e].range)return e+1;return 0}#On(e){const t=this.propertyAt(e);if(t&&t.range)return t.range.collapseToStart();if(!this.range)throw new Error("CSSStyleDeclaration.range is null");return this.range.collapseToEnd()}newBlankProperty(e){e=void 0===e?this.pastLastSourcePropertyIndex():e;return new at(this,e,"","",!1,!1,!0,!1,"",this.#On(e))}setText(e,t){return this.range&&this.styleSheetId?this.#Sn.setStyleText(this.styleSheetId,this.range,e,t):Promise.resolve(!1)}insertPropertyAt(e,t,n,r){this.newBlankProperty(e).setText(t+": "+n+";",!1,!0).then(r)}appendProperty(e,t,n){this.insertPropertyAt(this.allProperties().length,e,t,n)}}!function(e){e.Regular="Regular",e.Inline="Inline",e.Attributes="Attributes"}(ot||(ot={}));var ct=Object.freeze({__proto__:null,CSSStyleDeclaration:dt,get Type(){return ot}});class ht{cssModelInternal;styleSheetId;sourceURL;origin;style;constructor(e,t){if(this.cssModelInternal=e,this.styleSheetId=t.styleSheetId,this.styleSheetId){const e=this.getStyleSheetHeader(this.styleSheetId);this.sourceURL=e.sourceURL}this.origin=t.origin,this.style=new dt(this.cssModelInternal,this,t.style,ot.Regular)}rebase(e){this.styleSheetId===e.styleSheetId&&this.style.rebase(e)}resourceURL(){if(!this.styleSheetId)return t.DevToolsPath.EmptyUrlString;return this.getStyleSheetHeader(this.styleSheetId).resourceURL()}isUserAgent(){return"user-agent"===this.origin}isInjected(){return"injected"===this.origin}isViaInspector(){return"inspector"===this.origin}isRegular(){return"regular"===this.origin}cssModel(){return this.cssModelInternal}getStyleSheetHeader(e){const t=this.cssModelInternal.styleSheetHeaderForId(e);return console.assert(null!==t),t}}class ut{text;range;specificity;constructor(e){this.text=e.text,e.range&&(this.range=r.TextRange.TextRange.fromObject(e.range)),e.specificity&&(this.specificity=e.specificity)}rebase(e){this.range&&(this.range=this.range.rebaseAfterTextEdit(e.oldRange,e.newRange))}}class gt extends ht{selectors;nestingSelectors;media;containerQueries;supports;scopes;layers;wasUsed;constructor(e,t,n){super(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId}),this.reinitializeSelectors(t.selectorList),this.nestingSelectors=t.nestingSelectors,this.media=t.media?et.parseMediaArrayPayload(e,t.media):[],this.containerQueries=t.containerQueries?Ve.parseContainerQueriesPayload(e,t.containerQueries):[],this.scopes=t.scopes?nt.parseScopesPayload(e,t.scopes):[],this.supports=t.supports?st.parseSupportsPayload(e,t.supports):[],this.layers=t.layers?Xe.parseLayerPayload(e,t.layers):[],this.wasUsed=n||!1}static createDummyRule(e,t){const n={selectorList:{text:"",selectors:[{text:t,value:void 0}]},style:{styleSheetId:"0",range:new r.TextRange.TextRange(0,0,0,0),shorthandEntries:[],cssProperties:[]},origin:"inspector"};return new gt(e,n)}reinitializeSelectors(e){this.selectors=[];for(let t=0;te.text)).join(", ")}selectorRange(){const e=this.selectors[0].range,t=this.selectors[this.selectors.length-1].range;return e&&t?new r.TextRange.TextRange(e.startLine,e.startColumn,t.endLine,t.endColumn):null}lineNumberInSource(e){const t=this.selectors[e];if(!t||!t.range||!this.styleSheetId)return 0;return this.getStyleSheetHeader(this.styleSheetId).lineNumberInSource(t.range.startLine)}columnNumberInSource(e){const t=this.selectors[e];if(!t||!t.range||!this.styleSheetId)return;return this.getStyleSheetHeader(this.styleSheetId).columnNumberInSource(t.range.startLine,t.range.startColumn)}rebase(e){if(this.styleSheetId!==e.styleSheetId)return;const t=this.selectorRange();if(t&&t.equal(e.oldRange))this.reinitializeSelectors(e.payload);else for(let t=0;tt.rebase(e))),this.containerQueries.forEach((t=>t.rebase(e))),this.scopes.forEach((t=>t.rebase(e))),this.supports.forEach((t=>t.rebase(e))),super.rebase(e)}}class pt{#Nn;#Fn;constructor(e,t){this.#Nn=new ut(t.animationName),this.#Fn=t.keyframes.map((t=>new mt(e,t)))}name(){return this.#Nn}keyframes(){return this.#Fn}}class mt extends ht{#Bn;constructor(e,t){super(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId}),this.reinitializeKey(t.keyText)}key(){return this.#Bn}reinitializeKey(e){this.#Bn=new ut(e)}rebase(e){this.styleSheetId===e.styleSheetId&&this.#Bn.range&&(e.oldRange.equal(this.#Bn.range)?this.reinitializeKey(e.payload):this.#Bn.rebase(e),super.rebase(e))}setKeyText(e){const t=this.styleSheetId;if(!t)throw"No rule stylesheet id";const n=this.#Bn.range;if(!n)throw"Keyframe key is not editable";return this.cssModelInternal.setKeyframeKey(t,n,e)}}class ft{#Dn;#Un;constructor(e,t){this.#Dn=new ut(t.name),this.#Un=t.tryRules.map((t=>new ht(e,{origin:t.origin,style:t.style,styleSheetId:t.styleSheetId})))}name(){return this.#Dn}tryRules(){return this.#Un}}var bt,yt=Object.freeze({__proto__:null,CSSRule:ht,CSSStyleRule:gt,CSSKeyframesRule:pt,CSSKeyframeRule:mt,CSSPositionFallbackRule:ft});function vt(e){const t=e.match(/var\(\s*(--(?:[\s\w\P{ASCII}-]|\\.)+),?\s*(.*)\s*\)/u);return{variableName:t&&t[1].trim(),fallback:t&&t[2]}}class It{#Sn;#Hn;#qn;#_n;#Fn;#zn;#jn;#Wn;#Vn;#Gn;#Kn;#$n;#Qn;constructor({cssModel:e,node:t,inlinePayload:n,attributesPayload:r,matchedPayload:s,pseudoPayload:i,inheritedPayload:a,inheritedPseudoPayload:o,animationsPayload:l,parentLayoutNodeId:d,positionFallbackRules:c}){this.#Sn=e,this.#Hn=t,this.#qn=new Map,this.#_n=new Map,this.#Fn=[],l&&(this.#Fn=l.map((t=>new pt(e,t)))),this.#Qn=c.map((t=>new ft(e,t))),this.#$n=d,this.#zn=new Map,this.#jn=new Set,s=h(s);for(const e of a)e.matchedCSSRules=h(e.matchedCSSRules);this.#Wn=this.buildMainCascade(n,r,s,a),[this.#Vn,this.#Gn]=this.buildPseudoCascades(i,o),this.#Kn=new Map;for(const e of Array.from(this.#Gn.values()).concat(Array.from(this.#Vn.values())).concat(this.#Wn))for(const t of e.styles())this.#Kn.set(t,e);function h(e){for(const t of e)s(t);const t=[];for(const s of e){const e=t[t.length-1];e&&"user-agent"===s.rule.origin&&"user-agent"===e.rule.origin&&s.rule.selectorList.text===e.rule.selectorList.text&&r(s)===r(e)?n(s,e):t.push(s)}return t;function n(e,t){const n=new Map,r=new Map;for(const e of t.rule.style.shorthandEntries)n.set(e.name,e.value);for(const e of t.rule.style.cssProperties)r.set(e.name,e.value);for(const t of e.rule.style.shorthandEntries)n.set(t.name,t.value);for(const t of e.rule.style.cssProperties)r.set(t.name,t.value);t.rule.style.shorthandEntries=[...n.entries()].map((([e,t])=>({name:e,value:t}))),t.rule.style.cssProperties=[...r.entries()].map((([e,t])=>({name:e,value:t})))}function r(e){return e.rule.media?e.rule.media.map((e=>e.text)).join(", "):null}function s(e){const{matchingSelectors:t,rule:n}=e;"user-agent"===n.origin&&t.length&&(n.selectorList.selectors=n.selectorList.selectors.filter(((e,n)=>t.includes(n))),n.selectorList.text=n.selectorList.selectors.map((e=>e.text)).join(", "),e.matchingSelectors=t.map(((e,t)=>t)))}}}buildMainCascade(e,t,n,r){const s=[],i=[];function a(){if(!t)return;const e=new dt(this.#Sn,null,t,ot.Attributes);this.#zn.set(e,this.#Hn),i.push(e)}if(e&&this.#Hn.nodeType()===Node.ELEMENT_NODE){const t=new dt(this.#Sn,null,e,ot.Inline);this.#zn.set(t,this.#Hn),i.push(t)}let o;for(let e=n.length-1;e>=0;--e){const t=new gt(this.#Sn,n[e].rule);!t.isInjected()&&!t.isUserAgent()||o||(o=!0,a.call(this)),this.#zn.set(t.style,this.#Hn),i.push(t.style),this.addMatchingSelectors(this.#Hn,t,n[e].matchingSelectors)}o||a.call(this),s.push(new kt(this,i,!1));let l=this.#Hn.parentNode;for(let e=0;l&&r&&e=0;--e){const n=new gt(this.#Sn,o[e].rule);this.addMatchingSelectors(l,n,o[e].matchingSelectors),this.containsInherited(n.style)&&(d(i,n.style)||d(this.#jn,n.style)||(this.#zn.set(n.style,l),t.push(n.style),this.#jn.add(n.style)))}l=l.parentNode,s.push(new kt(this,t,!0))}return new St(s);function d(e,t){if(!t.styleSheetId||!t.range)return!1;for(const n of e)if(t.styleSheetId===n.styleSheetId&&n.range&&t.range.equal(n.range))return!0;return!1}}buildSplitCustomHighlightCascades(e,t,n,r){const s=new Map;for(let r=e.length-1;r>=0;--r){const i=this.customHighlightNamesToMatchingSelectorIndices(e[r]);for(const[a,o]of i){const i=new gt(this.#Sn,e[r].rule);this.#zn.set(i.style,t),n&&this.#jn.add(i.style),this.addMatchingSelectors(t,i,o);const l=s.get(a);l?l.push(i.style):s.set(a,[i.style])}}for(const[e,t]of s){const s=new kt(this,t,n,!0),i=r.get(e);i?i.push(s):r.set(e,[s])}}customHighlightNamesToMatchingSelectorIndices(e){const t=new Map;for(let n=0;n=0;--e){const t=new gt(this.#Sn,o[e].rule);a.push(t.style);const s=v().isHighlightPseudoType(n.pseudoType)?this.#Hn:r;this.#zn.set(t.style,s),s&&this.addMatchingSelectors(s,t,o[e].matchingSelectors)}const e=v().isHighlightPseudoType(n.pseudoType),t=new kt(this,a,!1,e);s.set(n.pseudoType,[t])}}if(t){let e=this.#Hn.parentNode;for(let n=0;e&&n=0;--n){const r=new gt(this.#Sn,a[n].rule);t.push(r.style),this.#zn.set(r.style,e),this.#jn.add(r.style),this.addMatchingSelectors(e,r,a[n].matchingSelectors)}const r=v().isHighlightPseudoType(n.pseudoType),i=new kt(this,t,!0,r),o=s.get(n.pseudoType);o?o.push(i):s.set(n.pseudoType,[i])}}e=e.parentNode}}for(const[e,t]of s.entries())n.set(e,new St(t));for(const[e,t]of i.entries())r.set(e,new St(t));return[n,r]}addMatchingSelectors(e,t,n){for(const r of n){const n=t.selectors[r];n&&this.setSelectorMatches(e,n.text,!0)}}node(){return this.#Hn}cssModel(){return this.#Sn}hasMatchingSelectors(e){return this.getMatchingSelectors(e).length>0&&this.queryMatches(e.style)}getParentLayoutNodeId(){return this.#$n}getMatchingSelectors(e){const t=this.nodeForStyle(e.style);if(!t||"number"!=typeof t.id)return[];const n=this.#_n.get(t.id);if(!n)return[];const r=[];for(let t=0;t=0;e--){const t=this.styles[e],n=t.parentRule;if((!n||n instanceof gt)&&(!n||this.#Xn.hasMatchingSelectors(n)))for(const e of t.allProperties()){const n=v();if(this.#Jn&&!this.#Yn&&!n.isPropertyInherited(e.name))continue;if(t.range&&!e.range)continue;if(!e.activeInStyle()){this.propertiesState.set(e,bt.Overloaded);continue}const r=n.canonicalPropertyName(e.name);this.updatePropertyState(e,r);for(const t of e.getLonghandProperties())n.isCSSPropertyName(t.name)&&this.updatePropertyState(t,t.name)}}}updatePropertyState(e,t){const n=this.activeProperties.get(t);!n?.important||e.important?(n&&this.propertiesState.set(n,bt.Overloaded),this.propertiesState.set(e,bt.Active),this.activeProperties.set(t,e)):this.propertiesState.set(e,bt.Overloaded)}}class St{#Zn;#er;#tr;#nr;#rr;#sr;constructor(e){this.#Zn=e,this.#er=new Map,this.#tr=new Map,this.#nr=new Map,this.#rr=!1,this.#sr=new Map;for(const t of e)for(const e of t.styles)this.#sr.set(e,t)}findAvailableCSSVariables(e){const t=this.#sr.get(e);if(!t)return[];this.ensureInitialized();const n=this.#tr.get(t);return n?Array.from(n.keys()):[]}computeCSSVariable(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);return r&&s?this.innerComputeCSSVariable(r,s,t):null}computeValue(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);return r&&s?this.innerComputeValue(r,s,t):null}computeSingleVariableValue(e,t){const n=this.#sr.get(e);if(!n)return null;this.ensureInitialized();const r=this.#tr.get(n),s=this.#nr.get(n);if(!r||!s)return null;const i=this.innerComputeValue(r,s,t),{variableName:a}=vt(t);return{computedValue:i,fromFallback:null!==a&&!r.has(a)}}innerComputeCSSVariable(e,t,n){if(!e.has(n))return null;if(t.has(n))return t.get(n)||null;t.set(n,null);const r=e.get(n);if(null==r)return null;const s=this.innerComputeValue(e,t,r);return t.set(n,s),s}innerComputeValue(e,t,n){const s=r.TextUtils.Utils.splitStringByRegexes(n,[f]),i=[];for(const n of s){if(-1===n.regexIndex){i.push(n.value);continue}const{variableName:r,fallback:s}=vt(n.value);if(!r)return null;const a=this.innerComputeCSSVariable(e,t,r);if(null===a&&!s)return null;null===a?i.push(s):i.push(a)}return i.map((e=>e?e.trim():"")).join(" ")}styles(){return Array.from(this.#sr.keys())}propertyState(e){return this.ensureInitialized(),this.#er.get(e)||null}reset(){this.#rr=!1,this.#er.clear(),this.#tr.clear(),this.#nr.clear()}ensureInitialized(){if(this.#rr)return;this.#rr=!0;const e=new Map;for(const t of this.#Zn){t.computeActiveProperties();for(const[n,r]of t.propertiesState){if(r===bt.Overloaded){this.#er.set(n,bt.Overloaded);continue}const t=v().canonicalPropertyName(n.name);e.has(t)?this.#er.set(n,bt.Overloaded):(e.set(t,n),this.#er.set(n,bt.Active))}}for(const[t,n]of e){const r=n.ownerStyle,s=n.getLonghandProperties();if(!s.length)continue;let i=!1;for(const t of s){const n=v().canonicalPropertyName(t.name),s=e.get(n);if(s&&s.ownerStyle===r){i=!0;break}}i||(e.delete(t),this.#er.set(n,bt.Overloaded))}const t=new Map;for(let e=this.#Zn.length-1;e>=0;--e){const n=this.#Zn[e],r=[];for(const e of n.activeProperties.entries()){const n=e[0],s=e[1];n.startsWith("--")&&(t.set(n,s.value),r.push(n))}const s=new Map(t),i=new Map;this.#tr.set(n,s),this.#nr.set(n,i);for(const e of r)t.delete(e),t.set(e,this.innerComputeCSSVariable(s,i,e))}}}!function(e){e.Active="Active",e.Overloaded="Overloaded"}(bt||(bt={}));var wt=Object.freeze({__proto__:null,parseCSSVariableNameAndFallback:vt,CSSMatchedStyles:It,get PropertyState(){return bt}});const Ct={couldNotFindTheOriginalStyle:"Could not find the original style sheet.",thereWasAnErrorRetrievingThe:"There was an error retrieving the source styles."},Tt=s.i18n.registerUIStrings("core/sdk/CSSStyleSheetHeader.ts",Ct),Rt=s.i18n.getLocalizedString.bind(void 0,Tt);class xt{#Sn;id;frameId;sourceURL;hasSourceURL;origin;title;disabled;isInline;isMutable;isConstructed;startLine;startColumn;endLine;endColumn;contentLength;ownerNode;sourceMapURL;loadingFailed;#ir;constructor(e,t){this.#Sn=e,this.id=t.styleSheetId,this.frameId=t.frameId,this.sourceURL=t.sourceURL,this.hasSourceURL=Boolean(t.hasSourceURL),this.origin=t.origin,this.title=t.title,this.disabled=t.disabled,this.isInline=t.isInline,this.isMutable=t.isMutable,this.isConstructed=t.isConstructed,this.startLine=t.startLine,this.startColumn=t.startColumn,this.endLine=t.endLine,this.endColumn=t.endColumn,this.contentLength=t.length,t.ownerNode&&(this.ownerNode=new Rn(e.target(),t.ownerNode)),this.sourceMapURL=t.sourceMapURL,this.loadingFailed=t.loadingFailed??!1,this.#ir=null}originalContentProvider(){if(!this.#ir){const e=async()=>{const e=await this.#Sn.originalStyleSheetText(this);return null===e?{content:null,error:Rt(Ct.couldNotFindTheOriginalStyle),isEncoded:!1}:{content:e,isEncoded:!1}};this.#ir=new r.StaticContentProvider.StaticContentProvider(this.contentURL(),this.contentType(),e)}return this.#ir}setSourceMapURL(e){this.sourceMapURL=e}cssModel(){return this.#Sn}isAnonymousInlineStyleSheet(){return!this.resourceURL()&&!this.#Sn.sourceMapManager().sourceMapForClient(this)}isConstructedByNew(){return this.isConstructed&&0===this.sourceURL.length}resourceURL(){const e=this.isViaInspector()?this.viaInspectorResourceURL():this.sourceURL;return!e&&o.Runtime.experiments.isEnabled(o.Runtime.ExperimentName.STYLES_PANE_CSS_CHANGES)?this.dynamicStyleURL():e}getFrameURLPath(){const t=this.#Sn.target().model(jn);if(console.assert(Boolean(t)),!t)return"";const n=t.frameForId(this.frameId);if(!n)return"";console.assert(Boolean(n));const r=new e.ParsedURL.ParsedURL(n.url);let s=r.host+r.folderPathComponents;return s.endsWith("/")||(s+="/"),s}viaInspectorResourceURL(){return`inspector://${this.getFrameURLPath()}inspector-stylesheet`}dynamicStyleURL(){return`stylesheet://${this.getFrameURLPath()}style#${this.id}`}lineNumberInSource(e){return this.startLine+e}columnNumberInSource(e,t){return(e?0:this.startColumn)+t}containsLocation(e,t){const n=e===this.startLine&&t>=this.startColumn||e>this.startLine,r=ee.isOutermostFrame()));this.#dr=e.length>0?e[0]:null}getFrame(e){const t=this.#or.get(e);return t?t.frame:null}getAllFrames(){return Array.from(this.#or.values(),(e=>e.frame))}getOutermostFrame(){return this.#dr}async getOrWaitForFrame(e,t){const n=this.getFrame(e);return!n||t&&t===n.resourceTreeModel().target()?new Promise((n=>{const r=this.#hr.get(e);r?r.push({notInTarget:t,resolve:n}):this.#hr.set(e,[{notInTarget:t,resolve:n}])})):n}resolveAwaitedFrame(e){const t=this.#hr.get(e.id);if(!t)return;const n=t.filter((({notInTarget:t,resolve:n})=>!(!t||t!==e.resourceTreeModel().target())||(n(e),!1)));n.length>0?this.#hr.set(e.id,n):this.#hr.delete(e.id)}}var Et;!function(e){e.FrameAddedToTarget="FrameAddedToTarget",e.FrameNavigated="FrameNavigated",e.FrameRemoved="FrameRemoved",e.ResourceAdded="ResourceAdded",e.OutermostFrameNavigated="OutermostFrameNavigated"}(Et||(Et={}));var At=Object.freeze({__proto__:null,FrameManager:Lt,get Events(){return Et}});class Ot extends c{constructor(e){super(e)}async read(t,n,r){const s=await this.target().ioAgent().invoke_read({handle:t,offset:r,size:n});if(s.getError())throw new Error(s.getError());return s.eof?null:s.base64Encoded?e.Base64.decode(s.data):s.data}async close(e){(await this.target().ioAgent().invoke_close({handle:e})).getError()&&console.error("Could not close stream.")}async resolveBlob(e){const t=e instanceof Le?e.objectId:e;if(!t)throw new Error("Remote object has undefined objectId");const n=await this.target().ioAgent().invoke_resolveBlob({objectId:t});if(n.getError())throw new Error(n.getError());return`blob:${n.uuid}`}async readToString(e){const t=[],n=new TextDecoder;for(;;){const r=await this.read(e,1048576);if(null===r){t.push(n.decode());break}r instanceof ArrayBuffer?t.push(n.decode(r,{stream:!0})):t.push(r)}return t.join("")}}c.register(Ot,{capabilities:z.IO,autostart:!0});var Nt=Object.freeze({__proto__:null,IOModel:Ot});const Ft={loadCanceledDueToReloadOf:"Load canceled due to reload of inspected page"},Bt=s.i18n.registerUIStrings("core/sdk/PageResourceLoader.ts",Ft),Dt=s.i18n.getLocalizedString.bind(void 0,Bt);let Ut=null;class Ht extends e.ObjectWrapper.ObjectWrapper{#ur;#gr;#pr;#mr;#fr;constructor(e,t){super(),this.#ur=0,this.#gr=t,this.#pr=new Map,this.#mr=[],K.instance().addModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),this.#fr=e}static instance({forceNew:e,loadOverride:t,maxConcurrentLoads:n}={forceNew:!1,loadOverride:null,maxConcurrentLoads:500}){return Ut&&!e||(Ut=new Ht(t,n)),Ut}static removeInstance(){Ut=null}onPrimaryPageChanged(e){if(e.data.frame.isOutermostFrame()){for(const{reject:e}of this.#mr)e(new Error(Dt(Ft.loadCanceledDueToReloadOf)));this.#mr=[],this.#pr.clear(),this.dispatchEventToListeners(_t.Update)}}getResourcesLoaded(){return this.#pr}getNumberOfResources(){return{loading:this.#ur,queued:this.#mr.length,resources:this.#pr.size}}async acquireLoadSlot(){if(this.#ur++,this.#ur>this.#gr){const e={resolve:()=>{},reject:()=>{}},t=new Promise(((t,n)=>{e.resolve=t,e.reject=n}));this.#mr.push(e),await t}}releaseLoadSlot(){this.#ur--;const e=this.#mr.shift();e&&e.resolve()}static makeKey(e,t){if(t.frameId)return`${e}-${t.frameId}`;if(t.target)return`${e}-${t.target.id()}`;throw new Error("Invalid initiator")}async loadResource(e,t){const n=Ht.makeKey(e,t),r={success:null,size:null,errorMessage:void 0,url:e,initiator:t};this.#pr.set(n,r),this.dispatchEventToListeners(_t.Update);try{await this.acquireLoadSlot();const n=this.dispatchLoad(e,t),s=await n;if(r.errorMessage=s.errorDescription.message,r.success=s.success,s.success)return r.size=s.content.length,{content:s.content};throw new Error(s.errorDescription.message)}catch(e){throw void 0===r.errorMessage&&(r.errorMessage=e.message),null===r.success&&(r.success=!1),e}finally{this.releaseLoadSlot(),this.dispatchEventToListeners(_t.Update)}}async dispatchLoad(t,n){let r=null;if(this.#fr)return this.#fr(t);const s=new e.ParsedURL.ParsedURL(t),a=qt().get()&&s&&"file"!==s.scheme&&"data"!==s.scheme&&"devtools"!==s.scheme;if(i.userMetrics.developerResourceScheme(this.getDeveloperResourceScheme(s)),a){try{if(n.target){i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageViaTarget);return await this.loadFromTarget(n.target,n.frameId,t)}const e=Lt.instance().getFrame(n.frameId);if(e){i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageViaFrame);return await this.loadFromTarget(e.resourceTreeModel().target(),n.frameId,t)}}catch(e){e instanceof Error&&(i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageFailure),r=e.message)}i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.LoadThroughPageFallback),console.warn("Fallback triggered",t,n)}else{const e=qt().get()?i.UserMetrics.DeveloperResourceLoaded.FallbackPerProtocol:i.UserMetrics.DeveloperResourceLoaded.FallbackPerOverride;i.userMetrics.developerResourceLoaded(e)}const o=await ue.instance().loadResource(t);return a&&!o.success&&i.userMetrics.developerResourceLoaded(i.UserMetrics.DeveloperResourceLoaded.FallbackFailure),r&&(o.errorDescription.message=`Fetch through target failed: ${r}; Fallback: ${o.errorDescription.message}`),o}getDeveloperResourceScheme(e){if(!e||""===e.scheme)return i.UserMetrics.DeveloperResourceScheme.SchemeUnknown;const t="localhost"===e.host||e.host.endsWith(".localhost");switch(e.scheme){case"file":return i.UserMetrics.DeveloperResourceScheme.SchemeFile;case"data":return i.UserMetrics.DeveloperResourceScheme.SchemeData;case"blob":return i.UserMetrics.DeveloperResourceScheme.SchemeBlob;case"http":return t?i.UserMetrics.DeveloperResourceScheme.SchemeHttpLocalhost:i.UserMetrics.DeveloperResourceScheme.SchemeHttp;case"https":return t?i.UserMetrics.DeveloperResourceScheme.SchemeHttpsLocalhost:i.UserMetrics.DeveloperResourceScheme.SchemeHttps}return i.UserMetrics.DeveloperResourceScheme.SchemeOther}async loadFromTarget(t,n,r){const s=t.model(ne),a=t.model(Ot),o=e.Settings.Settings.instance().moduleSetting("cacheDisabled").get(),l=await s.loadNetworkResource(n,r,{disableCache:o,includeCredentials:!0});try{const e=l.stream?await a.readToString(l.stream):"";return{success:l.success,content:e,errorDescription:{statusCode:l.httpStatusCode||0,netError:l.netError,netErrorName:l.netErrorName,message:i.ResourceLoader.netErrorToMessage(l.netError,l.httpStatusCode,l.netErrorName)||"",urlValid:void 0}}}finally{l.stream&&a.close(l.stream)}}}function qt(){return e.Settings.Settings.instance().createSetting("loadThroughTarget",!0)}var _t;(_t||(_t={})).Update="Update";var zt=Object.freeze({__proto__:null,PageResourceLoader:Ht,getLoadThroughTargetSetting:qt,get Events(){return _t}});function jt(e){return e.startsWith(")]}")&&(e=e.substring(e.indexOf("\n"))),65279===e.charCodeAt(0)&&(e=e.slice(1)),JSON.parse(e)}class Wt{lineNumber;columnNumber;sourceURL;sourceLineNumber;sourceColumnNumber;name;constructor(e,t,n,r,s,i){this.lineNumber=e,this.columnNumber=t,this.sourceURL=n,this.sourceLineNumber=r,this.sourceColumnNumber=s,this.name=i}static compare(e,t){return e.lineNumber!==t.lineNumber?e.lineNumber-t.lineNumber:e.columnNumber-t.columnNumber}}const Vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Gt=new Map;for(let e=0;e"url"in e))&&e.Console.Console.instance().warn(`SourceMap "${n}" contains unsupported "URL" field in one of its sections.`),this.eachSection(this.parseSources.bind(this))}compiledURL(){return this.#yr}url(){return this.#vr}sourceURLs(){return[...this.#Sr.keys()]}embeddedContentByURL(e){const t=this.#Sr.get(e);return t?t.content:null}findEntry(e,n){const r=this.mappings(),s=t.ArrayUtilities.upperBound(r,void 0,((t,r)=>e-r.lineNumber||n-r.columnNumber));return s?r[s-1]:null}findEntryRanges(e,n){const s=this.mappings(),i=t.ArrayUtilities.upperBound(s,void 0,((t,r)=>e-r.lineNumber||n-r.columnNumber));if(!i)return null;const a=i-1,o=s[a].sourceURL;if(!o)return null;const l=iu-s[t].sourceLineNumber||g-s[t].sourceColumnNumber));if(!p)return null;const m=p=i.length||s[i[a]].sourceLineNumber!==n)return null;const l=i.slice(a,o);if(!l.length)return null;const d=t.ArrayUtilities.lowerBound(l,r,((e,t)=>e-s[t].sourceColumnNumber));return d>=l.length?s[l[l.length-1]]:s[l[d]];function c(e,t){return e-s[t].sourceLineNumber}}findReverseIndices(e,n,r){const s=this.mappings(),i=this.reversedMappings(e),a=t.ArrayUtilities.upperBound(i,void 0,((e,t)=>n-s[t].sourceLineNumber||r-s[t].sourceColumnNumber));let o=a;for(;o>0&&s[i[o-1]].sourceLineNumber===s[i[a-1]].sourceLineNumber&&s[i[o-1]].sourceColumnNumber===s[i[a-1]].sourceColumnNumber;)--o;return i.slice(o,a)}findReverseEntries(e,t,n){const r=this.mappings();return this.findReverseIndices(e,t,n).map((e=>r[e]))}findReverseRanges(e,t,n){const s=this.mappings(),i=this.findReverseIndices(e,t,n),a=[];for(let e=0;e>=1,s?-t:t}reverseMapTextRanges(e,n){const s=this.reversedMappings(e),i=this.mappings();if(0===s.length)return[];let a=t.ArrayUtilities.lowerBound(s,n,(({startLine:e,startColumn:t},n)=>{const{sourceLineNumber:r,sourceColumnNumber:s}=i[n];return e-r||t-s}));for(;a===s.length||a>0&&(i[s[a]].sourceLineNumber>n.startLine||i[s[a]].sourceColumnNumber>n.startColumn);)a--;let o=a+1;for(;o0){const t=e[0];return 0===t?.lineNumber||0===t.columnNumber}return!1}hasIgnoreListHint(e){return this.#Sr.get(e)?.ignoreListHint??!1}findRanges(e,t){const n=this.mappings(),s=[];if(!n.length)return[];let i=null;0===n[0].lineNumber&&0===n[0].columnNumber||!t?.isStartMatching||(i=r.TextRange.TextRange.createUnboundedFromLocation(0,0),s.push(i));for(const{sourceURL:t,lineNumber:a,columnNumber:o}of n){const n=t&&e(t);i||!n?i&&!n&&(i.endLine=a,i.endColumn=o,i=null):(i=r.TextRange.TextRange.createUnboundedFromLocation(a,o),s.push(i))}return s}compatibleForURL(e,t){return this.embeddedContentByURL(e)===t.embeddedContentByURL(e)&&this.hasIgnoreListHint(e)===t.hasIgnoreListHint(e)}}!function(e){e._VLQ_BASE_SHIFT=5,e._VLQ_BASE_MASK=31,e._VLQ_CONTINUATION_MASK=32;e.StringCharIterator=class{string;position;constructor(e){this.string=e,this.position=0}next(){return this.string.charAt(this.position++)}peek(){return this.string.charAt(this.position)}hasNext(){return this.position{const n=new $t(i,a,e);return this.#Rr.get(t)===s&&(s.sourceMap=n,this.#xr.set(n,t),this.dispatchEventToListeners(Qt.SourceMapAttached,{client:t,sourceMap:n})),n}),(n=>{e.Console.Console.instance().warn(`DevTools failed to load source map: ${n.message}`),this.#Rr.get(t)===s&&this.dispatchEventToListeners(Qt.SourceMapFailedToAttach,{client:t})}))}}this.#Rr.set(t,s)}detachSourceMap(e){const t=this.#Rr.get(e);if(!t)return;if(this.#Rr.delete(e),!this.#Tr)return;const{sourceMap:n}=t;n?(this.#xr.delete(n),this.dispatchEventToListeners(Qt.SourceMapDetached,{client:e,sourceMap:n})):this.dispatchEventToListeners(Qt.SourceMapFailedToAttach,{client:e})}dispose(){K.instance().removeEventListener($.InspectedURLChanged,this.inspectedURLChanged,this)}}!function(e){e.SourceMapWillAttach="SourceMapWillAttach",e.SourceMapFailedToAttach="SourceMapFailedToAttach",e.SourceMapAttached="SourceMapAttached",e.SourceMapDetached="SourceMapDetached"}(Qt||(Qt={}));var Yt,Zt=Object.freeze({__proto__:null,SourceMapManager:Jt,get Events(){return Qt}});class en extends c{agent;#Mr;#Pr;#Lr;#Er;#Ar;#Or;#Nr;#Fr;#Br;#Dr;#Ur;#Hr;#qr;#Tr;#_r;#zr;constructor(t){super(t),this.#Tr=!1,this.#Dr=null,this.#Ur=null,this.#Mr=t.model(Pn),this.#Ar=new Jt(t),this.agent=t.cssAgent(),this.#Or=new an(this),this.#Er=t.model(jn),this.#Er&&this.#Er.addEventListener(_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),t.registerCSSDispatcher(new sn(this)),t.suspended()||this.enable(),this.#Br=new Map,this.#Fr=new Map,this.#Lr=new Map,this.#_r=!1,this.#Pr=new Map,this.#Hr=null,this.#qr=!1,this.#zr=!1,this.#Nr=new e.Throttler.Throttler(dn),this.#Ar.setEnabled(e.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").get()),e.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").addChangeListener((e=>this.#Ar.setEnabled(e.data)))}headersForSourceURL(e){const t=[];for(const n of this.getStyleSheetIdsForURL(e)){const e=this.styleSheetHeaderForId(n);e&&t.push(e)}return t}createRawLocationsByURL(e,n,r=0){const s=this.headersForSourceURL(e);s.sort((function(e,t){return e.startLine-t.startLine||e.startColumn-t.startColumn||e.id.localeCompare(t.id)}));const i=t.ArrayUtilities.upperBound(s,void 0,((e,t)=>n-t.startLine||r-t.startColumn));if(!i)return[];const a=[],o=s[i-1];for(let e=i-1;e>=0&&s[e].startLine===o.startLine&&s[e].startColumn===o.startColumn;--e)s[e].containsLocation(n,r)&&a.push(new rn(s[e],n,r));return a}sourceMapManager(){return this.#Ar}static readableLayerName(e){return e||""}static trimSourceURL(e){let t=e.lastIndexOf("/*# sourceURL=");if(-1===t&&(t=e.lastIndexOf("/*@ sourceURL="),-1===t))return e;const n=e.lastIndexOf("\n",t);if(-1===n)return e;const r=e.substr(n+1).split("\n",1)[0];return-1===r.search(/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/)?e:e.substr(0,n)+e.substr(n+r.length+1)}domModel(){return this.#Mr}async setStyleText(e,t,n,r){try{await this.ensureOriginalStyleSheetText(e);const{styles:s}=await this.agent.invoke_setStyleTexts({edits:[{styleSheetId:e,range:t.serializeToObject(),text:n}]});if(!s||1!==s.length)return!1;this.#Mr.markUndoableState(!r);const i=new nn(e,t,n,s[0]);return this.fireStyleSheetChanged(e,i),!0}catch(e){return!1}}async setSelectorText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{selectorList:r}=await this.agent.invoke_setRuleSelector({styleSheetId:e,range:t,selector:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setKeyframeKey(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{keyText:r}=await this.agent.invoke_setKeyframeKey({styleSheetId:e,range:t,keyText:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}startCoverage(){return this.#_r=!0,this.agent.invoke_startRuleUsageTracking()}async takeCoverageDelta(){const e=await this.agent.invoke_takeCoverageDelta();return{timestamp:e&&e.timestamp||0,coverage:e&&e.coverage||[]}}setLocalFontsEnabled(e){return this.agent.invoke_setLocalFontsEnabled({enabled:e})}async stopCoverage(){this.#_r=!1,await this.agent.invoke_stopRuleUsageTracking()}async getMediaQueries(){const{medias:e}=await this.agent.invoke_getMediaQueries();return e?et.parseMediaArrayPayload(this,e):[]}async getRootLayer(e){const{rootLayer:t}=await this.agent.invoke_getLayersForNode({nodeId:e});return t}isEnabled(){return this.#Tr}async enable(){await this.agent.invoke_enable(),this.#Tr=!0,this.#_r&&await this.startCoverage(),this.dispatchEventToListeners(Yt.ModelWasEnabled)}async getMatchedStyles(e){const t=await this.agent.invoke_getMatchedStylesForNode({nodeId:e});if(t.getError())return null;const n=this.#Mr.nodeForId(e);return n?new It({cssModel:this,node:n,inlinePayload:t.inlineStyle||null,attributesPayload:t.attributesStyle||null,matchedPayload:t.matchedCSSRules||[],pseudoPayload:t.pseudoElements||[],inheritedPayload:t.inherited||[],inheritedPseudoPayload:t.inheritedPseudoElements||[],animationsPayload:t.cssKeyframesRules||[],parentLayoutNodeId:t.parentLayoutNodeId,positionFallbackRules:t.cssPositionFallbackRules||[]}):null}async getClassNames(e){const{classNames:t}=await this.agent.invoke_collectClassNames({styleSheetId:e});return t||[]}async getComputedStyle(e){return this.isEnabled()||await this.enable(),this.#Or.computedStylePromise(e)}async getBackgroundColors(e){const t=await this.agent.invoke_getBackgroundColors({nodeId:e});return t.getError()?null:{backgroundColors:t.backgroundColors||null,computedFontSize:t.computedFontSize||"",computedFontWeight:t.computedFontWeight||""}}async getPlatformFonts(e){const{fonts:t}=await this.agent.invoke_getPlatformFontsForNode({nodeId:e});return t}allStyleSheets(){const e=[...this.#Br.values()];return e.sort((function(e,t){return e.sourceURLt.sourceURL?1:e.startLine-t.startLine||e.startColumn-t.startColumn})),e}async getInlineStyles(e){const t=await this.agent.invoke_getInlineStylesForNode({nodeId:e});if(t.getError()||!t.inlineStyle)return null;const n=new dt(this,null,t.inlineStyle,ot.Inline),r=t.attributesStyle?new dt(this,null,t.attributesStyle,ot.Attributes):null;return new on(n,r)}forcePseudoState(e,n,r){const s=e.marker(tn)||[],i=s.includes(n);if(r){if(i)return!1;s.push(n),e.setMarker(tn,s)}else{if(!i)return!1;t.ArrayUtilities.removeElement(s,n),s.length?e.setMarker(tn,s):e.setMarker(tn,null)}return void 0!==e.id&&(this.agent.invoke_forcePseudoState({nodeId:e.id,forcedPseudoClasses:s}),this.dispatchEventToListeners(Yt.PseudoStateForced,{node:e,pseudoClass:n,enable:r}),!0)}pseudoState(e){return e.marker(tn)||[]}async setMediaText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{media:r}=await this.agent.invoke_setMediaText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setContainerQueryText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{containerQuery:r}=await this.agent.invoke_setContainerQueryText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setSupportsText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{supports:r}=await this.agent.invoke_setSupportsText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return!1}}async setScopeText(e,t,n){i.userMetrics.actionTaken(i.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{scope:r}=await this.agent.invoke_setScopeText({styleSheetId:e,range:t,text:n});if(!r)return!1;this.#Mr.markUndoableState();const s=new nn(e,t,n,r);return this.fireStyleSheetChanged(e,s),!0}catch(e){return console.error(e),!1}}async addRule(e,t,n){try{await this.ensureOriginalStyleSheetText(e);const{rule:r}=await this.agent.invoke_addRule({styleSheetId:e,ruleText:t,location:n});if(!r)return null;this.#Mr.markUndoableState();const s=new nn(e,n,t,r);return this.fireStyleSheetChanged(e,s),new gt(this,r)}catch(e){return null}}async requestViaInspectorStylesheet(e){const t=e.frameId()||(this.#Er&&this.#Er.mainFrame?this.#Er.mainFrame.id:null),n=[...this.#Br.values()].find((e=>e.frameId===t&&e.isViaInspector()));if(n)return n;if(!t)return null;try{const{styleSheetId:e}=await this.agent.invoke_createStyleSheet({frameId:t});return e&&this.#Br.get(e)||null}catch(e){return null}}mediaQueryResultChanged(){this.dispatchEventToListeners(Yt.MediaQueryResultChanged)}fontsUpdated(e){e&&this.#Pr.set(e.src,new _e(e)),this.dispatchEventToListeners(Yt.FontsUpdated)}fontFaces(){return[...this.#Pr.values()]}fontFaceForSource(e){return this.#Pr.get(e)}styleSheetHeaderForId(e){return this.#Br.get(e)||null}styleSheetHeaders(){return[...this.#Br.values()]}fireStyleSheetChanged(e,t){this.dispatchEventToListeners(Yt.StyleSheetChanged,{styleSheetId:e,edit:t})}ensureOriginalStyleSheetText(e){const t=this.styleSheetHeaderForId(e);if(!t)return Promise.resolve(null);let n=this.#Lr.get(t);return n||(n=this.getStyleSheetText(t.id),this.#Lr.set(t,n),this.originalContentRequestedForTest(t)),n}originalContentRequestedForTest(e){}originalStyleSheetText(e){return this.ensureOriginalStyleSheetText(e.id)}getAllStyleSheetHeaders(){return this.#Br.values()}styleSheetAdded(e){console.assert(!this.#Br.get(e.styleSheetId)),e.loadingFailed&&(e.hasSourceURL=!1,e.isConstructed=!0,e.isInline=!1,e.isMutable=!1,e.sourceURL="",e.sourceMapURL=void 0);const t=new xt(this,e);this.#Br.set(e.styleSheetId,t);const n=t.resourceURL();let r=this.#Fr.get(n);if(r||(r=new Map,this.#Fr.set(n,r)),r){let e=r.get(t.frameId);e||(e=new Set,r.set(t.frameId,e)),e.add(t.id)}this.#Ar.attachSourceMap(t,t.sourceURL,t.sourceMapURL),this.dispatchEventToListeners(Yt.StyleSheetAdded,t)}styleSheetRemoved(e){const t=this.#Br.get(e);if(console.assert(Boolean(t)),!t)return;this.#Br.delete(e);const n=t.resourceURL(),r=this.#Fr.get(n);if(console.assert(Boolean(r),"No frameId to styleSheetId map is available for given style sheet URL."),r){const s=r.get(t.frameId);s&&(s.delete(e),s.size||(r.delete(t.frameId),r.size||this.#Fr.delete(n)))}this.#Lr.delete(t),this.#Ar.detachSourceMap(t),this.dispatchEventToListeners(Yt.StyleSheetRemoved,t)}getStyleSheetIdsForURL(e){const t=this.#Fr.get(e);if(!t)return[];const n=[];for(const e of t.values())n.push(...e);return n}async setStyleSheetText(e,t,n){const r=this.#Br.get(e);if(!r)return"Unknown stylesheet in CSS.setStyleSheetText";t=en.trimSourceURL(t),r.hasSourceURL&&(t+="\n/*# sourceURL="+r.sourceURL+" */"),await this.ensureOriginalStyleSheetText(e);const s=(await this.agent.invoke_setStyleSheetText({styleSheetId:r.id,text:t})).sourceMapURL;return this.#Ar.detachSourceMap(r),r.setSourceMapURL(s),this.#Ar.attachSourceMap(r,r.sourceURL,r.sourceMapURL),null===s?"Error in CSS.setStyleSheetText":(this.#Mr.markUndoableState(!n),this.fireStyleSheetChanged(e),null)}async getStyleSheetText(e){try{const{text:t}=await this.agent.invoke_getStyleSheetText({styleSheetId:e});return t&&en.trimSourceURL(t)}catch(e){return null}}async onPrimaryPageChanged(e){e.data.frame.backForwardCacheDetails.restoredFromCache?(await this.suspendModel(),await this.resumeModel()):(this.resetStyleSheets(),this.resetFontFaces())}resetStyleSheets(){const e=[...this.#Br.values()];this.#Fr.clear(),this.#Br.clear();for(const t of e)this.#Ar.detachSourceMap(t),this.dispatchEventToListeners(Yt.StyleSheetRemoved,t)}resetFontFaces(){this.#Pr.clear()}async suspendModel(){this.#Tr=!1,await this.agent.invoke_disable(),this.resetStyleSheets(),this.resetFontFaces()}async resumeModel(){return this.enable()}setEffectivePropertyValueForNode(e,t,n){this.agent.invoke_setEffectivePropertyValueForNode({nodeId:e,propertyName:t,value:n})}cachedMatchedCascadeForNode(e){if(this.#Dr!==e&&this.discardCachedMatchedCascade(),this.#Dr=e,!this.#Ur){if(!e.id)return Promise.resolve(null);this.#Ur=this.getMatchedStyles(e.id)}return this.#Ur}discardCachedMatchedCascade(){this.#Dr=null,this.#Ur=null}createCSSPropertyTracker(e){return new ln(this,e)}enableCSSPropertyTracker(e){const t=e.getTrackedProperties();0!==t.length&&(this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:t}),this.#qr=!0,this.#Hr=e,this.pollComputedStyleUpdates())}disableCSSPropertyTracker(){this.#qr=!1,this.#Hr=null,this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:[]})}async pollComputedStyleUpdates(){if(!this.#zr){if(this.#qr){this.#zr=!0;const e=await this.agent.invoke_takeComputedStyleUpdates();if(this.#zr=!1,e.getError()||!e.nodeIds||!this.#qr)return;this.#Hr&&this.#Hr.dispatchEventToListeners(cn.TrackedCSSPropertiesUpdated,e.nodeIds.map((e=>this.#Mr.nodeForId(e))))}this.#qr&&this.#Nr.schedule(this.pollComputedStyleUpdates.bind(this))}}dispose(){this.disableCSSPropertyTracker(),super.dispose(),this.#Ar.dispose()}getAgent(){return this.agent}}!function(e){e.FontsUpdated="FontsUpdated",e.MediaQueryResultChanged="MediaQueryResultChanged",e.ModelWasEnabled="ModelWasEnabled",e.PseudoStateForced="PseudoStateForced",e.StyleSheetAdded="StyleSheetAdded",e.StyleSheetChanged="StyleSheetChanged",e.StyleSheetRemoved="StyleSheetRemoved"}(Yt||(Yt={}));const tn="pseudo-state-marker";class nn{styleSheetId;oldRange;newRange;newText;payload;constructor(e,t,n,s){this.styleSheetId=e,this.oldRange=t,this.newRange=r.TextRange.TextRange.fromEdit(t,n),this.newText=n,this.payload=s}}class rn{#Sn;styleSheetId;url;lineNumber;columnNumber;constructor(e,t,n){this.#Sn=e.cssModel(),this.styleSheetId=e.id,this.url=e.resourceURL(),this.lineNumber=t,this.columnNumber=n||0}cssModel(){return this.#Sn}header(){return this.#Sn.styleSheetHeaderForId(this.styleSheetId)}}class sn{#jr;constructor(e){this.#jr=e}mediaQueryResultChanged(){this.#jr.mediaQueryResultChanged()}fontsUpdated({font:e}){this.#jr.fontsUpdated(e)}styleSheetChanged({styleSheetId:e}){this.#jr.fireStyleSheetChanged(e)}styleSheetAdded({header:e}){this.#jr.styleSheetAdded(e)}styleSheetRemoved({styleSheetId:e}){this.#jr.styleSheetRemoved(e)}}class an{#jr;#Wr;constructor(e){this.#jr=e,this.#Wr=new Map}computedStylePromise(e){let t=this.#Wr.get(e);return t||(t=this.#jr.getAgent().invoke_getComputedStyleForNode({nodeId:e}).then((({computedStyle:t})=>{if(this.#Wr.delete(e),!t||!t.length)return null;const n=new Map;for(const e of t)n.set(e.name,e.value);return n})),this.#Wr.set(e,t),t)}}class on{inlineStyle;attributesStyle;constructor(e,t){this.inlineStyle=e,this.attributesStyle=t}}class ln extends e.ObjectWrapper.ObjectWrapper{#jr;#Vr;constructor(e,t){super(),this.#jr=e,this.#Vr=t}start(){this.#jr.enableCSSPropertyTracker(this)}stop(){this.#jr.disableCSSPropertyTracker()}getTrackedProperties(){return this.#Vr}}const dn=1e3;var cn;!function(e){e.TrackedCSSPropertiesUpdated="TrackedCSSPropertiesUpdated"}(cn||(cn={})),c.register(en,{capabilities:z.DOM,autostart:!0});var hn=Object.freeze({__proto__:null,CSSModel:en,get Events(){return Yt},Edit:nn,CSSLocation:rn,InlineStyleResult:on,CSSPropertyTracker:ln,get CSSPropertyTrackerEvents(){return cn}});class un{#Gr;#Kr;constructor(){const t="rgba";this.#Gr=[new e.Color.Legacy([.9607843137254902,.592156862745098,.5803921568627451,1],t),new e.Color.Legacy([.9411764705882353,.7490196078431373,.2980392156862745,1],t),new e.Color.Legacy([.8313725490196079,.9294117647058824,.19215686274509805,1],t),new e.Color.Legacy([.6196078431372549,.9215686274509803,.2784313725490196,1],t),new e.Color.Legacy([.3568627450980392,.8196078431372549,.8431372549019608,1],t),new e.Color.Legacy([.7372549019607844,.807843137254902,.984313725490196,1],t),new e.Color.Legacy([.7764705882352941,.7450980392156863,.9333333333333333,1],t),new e.Color.Legacy([.8156862745098039,.5803921568627451,.9176470588235294,1],t),new e.Color.Legacy([.9215686274509803,.5803921568627451,.8117647058823529,1],t)],this.#Kr=0}next(){const e=this.#Gr[this.#Kr];return this.#Kr++,this.#Kr>=this.#Gr.length&&(this.#Kr=0),e}}var gn=Object.freeze({__proto__:null,OverlayColorGenerator:un});class pn{#$r;#Qr;#Xr;#Jr;#Yr;#Zr;#Gr;#es;#ts;#ns;#rs;#ss;#is;#as;constructor(t,n=!0){this.#$r=t,this.#Qr=new Map,this.#Xr=new Map,this.#Jr=new Map,this.#Yr=new Map,this.#Zr=new Map,this.#Gr=new Map,this.#es=new un,this.#ts=new un,this.#ns=n,this.#rs=e.Settings.Settings.instance().moduleSetting("showGridLineLabels"),this.#rs.addChangeListener(this.onSettingChange,this),this.#ss=e.Settings.Settings.instance().moduleSetting("extendGridLines"),this.#ss.addChangeListener(this.onSettingChange,this),this.#is=e.Settings.Settings.instance().moduleSetting("showGridAreas"),this.#is.addChangeListener(this.onSettingChange,this),this.#as=e.Settings.Settings.instance().moduleSetting("showGridTrackSizes"),this.#as.addChangeListener(this.onSettingChange,this)}onSettingChange(){this.resetOverlay()}buildGridHighlightConfig(e){const t=this.colorOfGrid(e).asLegacyColor(),n=t.setAlpha(.1).asLegacyColor(),r=t.setAlpha(.3).asLegacyColor(),s=t.setAlpha(.8).asLegacyColor(),i=this.#ss.get(),a="lineNumbers"===this.#rs.get(),o=a,l="lineNames"===this.#rs.get();return{rowGapColor:r.toProtocolRGBA(),rowHatchColor:s.toProtocolRGBA(),columnGapColor:r.toProtocolRGBA(),columnHatchColor:s.toProtocolRGBA(),gridBorderColor:t.toProtocolRGBA(),gridBorderDash:!1,rowLineColor:t.toProtocolRGBA(),columnLineColor:t.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0,showGridExtensionLines:i,showPositiveLineNumbers:a,showNegativeLineNumbers:o,showLineNames:l,showAreaNames:this.#is.get(),showTrackSizes:this.#as.get(),areaBorderColor:t.toProtocolRGBA(),gridBackgroundColor:n.toProtocolRGBA()}}buildFlexContainerHighlightConfig(e){const t=this.colorOfFlex(e).asLegacyColor();return{containerBorder:{color:t.toProtocolRGBA(),pattern:"dashed"},itemSeparator:{color:t.toProtocolRGBA(),pattern:"dotted"},lineSeparator:{color:t.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:t.toProtocolRGBA()},crossDistributedSpace:{hatchColor:t.toProtocolRGBA()}}}buildScrollSnapContainerHighlightConfig(t){return{snapAreaBorder:{color:e.Color.PageHighlight.GridBorder.toProtocolRGBA(),pattern:"dashed"},snapportBorder:{color:e.Color.PageHighlight.GridBorder.toProtocolRGBA()},scrollMarginColor:e.Color.PageHighlight.Margin.toProtocolRGBA(),scrollPaddingColor:e.Color.PageHighlight.Padding.toProtocolRGBA()}}highlightGridInOverlay(e){this.#Qr.set(e,this.buildGridHighlightConfig(e)),this.updateHighlightsInOverlay()}isGridHighlighted(e){return this.#Qr.has(e)}colorOfGrid(e){let t=this.#Gr.get(e);return t||(t=this.#es.next(),this.#Gr.set(e,t)),t}setColorOfGrid(e,t){this.#Gr.set(e,t)}hideGridInOverlay(e){this.#Qr.has(e)&&(this.#Qr.delete(e),this.updateHighlightsInOverlay())}highlightScrollSnapInOverlay(e){this.#Xr.set(e,this.buildScrollSnapContainerHighlightConfig(e)),this.updateHighlightsInOverlay()}isScrollSnapHighlighted(e){return this.#Xr.has(e)}hideScrollSnapInOverlay(e){this.#Xr.has(e)&&(this.#Xr.delete(e),this.updateHighlightsInOverlay())}highlightFlexInOverlay(e){this.#Jr.set(e,this.buildFlexContainerHighlightConfig(e)),this.updateHighlightsInOverlay()}isFlexHighlighted(e){return this.#Jr.has(e)}colorOfFlex(e){let t=this.#Gr.get(e);return t||(t=this.#ts.next(),this.#Gr.set(e,t)),t}setColorOfFlex(e,t){this.#Gr.set(e,t)}hideFlexInOverlay(e){this.#Jr.has(e)&&(this.#Jr.delete(e),this.updateHighlightsInOverlay())}highlightContainerQueryInOverlay(e){this.#Yr.set(e,this.buildContainerQueryContainerHighlightConfig()),this.updateHighlightsInOverlay()}hideContainerQueryInOverlay(e){this.#Yr.has(e)&&(this.#Yr.delete(e),this.updateHighlightsInOverlay())}isContainerQueryHighlighted(e){return this.#Yr.has(e)}buildContainerQueryContainerHighlightConfig(){return{containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},descendantBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}}}highlightIsolatedElementInOverlay(e){this.#Zr.set(e,this.buildIsolationModeHighlightConfig()),this.updateHighlightsInOverlay()}hideIsolatedElementInOverlay(e){this.#Zr.has(e)&&(this.#Zr.delete(e),this.updateHighlightsInOverlay())}isIsolatedElementHighlighted(e){return this.#Zr.has(e)}buildIsolationModeHighlightConfig(){return{resizerColor:e.Color.IsolationModeHighlight.Resizer.toProtocolRGBA(),resizerHandleColor:e.Color.IsolationModeHighlight.ResizerHandle.toProtocolRGBA(),maskColor:e.Color.IsolationModeHighlight.Mask.toProtocolRGBA()}}hideAllInOverlay(){this.#Jr.clear(),this.#Qr.clear(),this.#Xr.clear(),this.#Yr.clear(),this.#Zr.clear(),this.updateHighlightsInOverlay()}refreshHighlights(){const e=this.updateHighlightsForDeletedNodes(this.#Qr),t=this.updateHighlightsForDeletedNodes(this.#Jr),n=this.updateHighlightsForDeletedNodes(this.#Xr),r=this.updateHighlightsForDeletedNodes(this.#Yr),s=this.updateHighlightsForDeletedNodes(this.#Zr);(t||e||n||r||s)&&this.updateHighlightsInOverlay()}updateHighlightsForDeletedNodes(e){let t=!1;for(const n of e.keys())null===this.#$r.getDOMModel().nodeForId(n)&&(e.delete(n),t=!0);return t}resetOverlay(){for(const e of this.#Qr.keys())this.#Qr.set(e,this.buildGridHighlightConfig(e));for(const e of this.#Jr.keys())this.#Jr.set(e,this.buildFlexContainerHighlightConfig(e));for(const e of this.#Xr.keys())this.#Xr.set(e,this.buildScrollSnapContainerHighlightConfig(e));for(const e of this.#Yr.keys())this.#Yr.set(e,this.buildContainerQueryContainerHighlightConfig());for(const e of this.#Zr.keys())this.#Zr.set(e,this.buildIsolationModeHighlightConfig());this.updateHighlightsInOverlay()}updateHighlightsInOverlay(){const e=this.#Qr.size>0||this.#Jr.size>0||this.#Yr.size>0||this.#Zr.size>0;this.#$r.setShowViewportSizeOnResize(!e),this.updateGridHighlightsInOverlay(),this.updateFlexHighlightsInOverlay(),this.updateScrollSnapHighlightsInOverlay(),this.updateContainerQueryHighlightsInOverlay(),this.updateIsolatedElementHighlightsInOverlay()}updateGridHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Qr.entries())t.push({nodeId:e,gridHighlightConfig:n});e.target().overlayAgent().invoke_setShowGridOverlays({gridNodeHighlightConfigs:t})}updateFlexHighlightsInOverlay(){if(!this.#ns)return;const e=this.#$r,t=[];for(const[e,n]of this.#Jr.entries())t.push({nodeId:e,flexContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowFlexOverlays({flexNodeHighlightConfigs:t})}updateScrollSnapHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Xr.entries())t.push({nodeId:e,scrollSnapContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowScrollSnapOverlays({scrollSnapHighlightConfigs:t})}updateContainerQueryHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Yr.entries())t.push({nodeId:e,containerQueryContainerHighlightConfig:n});e.target().overlayAgent().invoke_setShowContainerQueryOverlays({containerQueryHighlightConfigs:t})}updateIsolatedElementHighlightsInOverlay(){const e=this.#$r,t=[];for(const[e,n]of this.#Zr.entries())t.push({nodeId:e,isolationModeHighlightConfig:n});e.target().overlayAgent().invoke_setShowIsolatedElements({isolatedElementHighlightConfigs:t})}}var mn=Object.freeze({__proto__:null,OverlayPersistentHighlighter:pn});const fn={pausedInDebugger:"Paused in debugger"},bn=s.i18n.registerUIStrings("core/sdk/OverlayModel.ts",fn),yn=s.i18n.getLocalizedString.bind(void 0,bn);class vn extends c{#Mr;overlayAgent;#os;#ls;#ds;#cs;#hs;#us;#gs;#ps;#ms;#fs;#bs;#ys;#vs;#Is;#ks;#Ss;#ws;constructor(t){super(t),this.#Mr=t.model(Pn),t.registerOverlayDispatcher(this),this.overlayAgent=t.overlayAgent(),this.#os=t.model(or),this.#os&&(e.Settings.Settings.instance().moduleSetting("disablePausedStateOverlay").addChangeListener(this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.DebuggerPaused,this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.DebuggerResumed,this.updatePausedInDebuggerMessage,this),this.#os.addEventListener(cr.GlobalObjectCleared,this.updatePausedInDebuggerMessage,this)),this.#ls=!1,this.#ds=null,this.#cs=new kn(this),this.#hs=this.#cs,this.#us=e.Settings.Settings.instance().moduleSetting("showPaintRects"),this.#gs=e.Settings.Settings.instance().moduleSetting("showLayoutShiftRegions"),this.#ps=e.Settings.Settings.instance().moduleSetting("showAdHighlights"),this.#ms=e.Settings.Settings.instance().moduleSetting("showDebugBorders"),this.#fs=e.Settings.Settings.instance().moduleSetting("showFPSCounter"),this.#bs=e.Settings.Settings.instance().moduleSetting("showScrollBottleneckRects"),this.#ys=e.Settings.Settings.instance().moduleSetting("showWebVitals"),this.#vs=[],this.#Is=!0,t.suspended()||(this.overlayAgent.invoke_enable(),this.wireAgentToSettings()),this.#ks=new pn(this),this.#Mr.addEventListener(wn.NodeRemoved,(()=>{this.#ks&&this.#ks.refreshHighlights()})),this.#Mr.addEventListener(wn.DocumentUpdated,(()=>{this.#ks&&this.#ks.hideAllInOverlay()})),this.#Ss=new Sn(this),this.#ws=!1}static highlightObjectAsDOMNode(e){const t=e.runtimeModel().target().model(Pn);t&&t.overlayModel().highlightInOverlay({object:e,selectorList:void 0})}static hideDOMNodeHighlight(){for(const e of K.instance().models(vn))e.delayedHideHighlight(0)}static async muteHighlight(){return Promise.all(K.instance().models(vn).map((e=>e.suspendModel())))}static async unmuteHighlight(){return Promise.all(K.instance().models(vn).map((e=>e.resumeModel())))}static highlightRect(e){for(const t of K.instance().models(vn))t.highlightRect(e)}static clearHighlight(){for(const e of K.instance().models(vn))e.clearHighlight()}getDOMModel(){return this.#Mr}highlightRect({x:e,y:t,width:n,height:r,color:s,outlineColor:i}){const a=s||{r:255,g:0,b:255,a:.3},o=i||{r:255,g:0,b:255,a:.5};return this.overlayAgent.invoke_highlightRect({x:e,y:t,width:n,height:r,color:a,outlineColor:o})}clearHighlight(){return this.overlayAgent.invoke_hideHighlight()}async wireAgentToSettings(){this.#vs=[this.#us.addChangeListener((()=>this.overlayAgent.invoke_setShowPaintRects({result:this.#us.get()}))),this.#gs.addChangeListener((()=>this.overlayAgent.invoke_setShowLayoutShiftRegions({result:this.#gs.get()}))),this.#ps.addChangeListener((()=>this.overlayAgent.invoke_setShowAdHighlights({show:this.#ps.get()}))),this.#ms.addChangeListener((()=>this.overlayAgent.invoke_setShowDebugBorders({show:this.#ms.get()}))),this.#fs.addChangeListener((()=>this.overlayAgent.invoke_setShowFPSCounter({show:this.#fs.get()}))),this.#bs.addChangeListener((()=>this.overlayAgent.invoke_setShowScrollBottleneckRects({show:this.#bs.get()}))),this.#ys.addChangeListener((()=>this.overlayAgent.invoke_setShowWebVitals({show:this.#ys.get()})))],this.#us.get()&&this.overlayAgent.invoke_setShowPaintRects({result:!0}),this.#gs.get()&&this.overlayAgent.invoke_setShowLayoutShiftRegions({result:!0}),this.#ps.get()&&this.overlayAgent.invoke_setShowAdHighlights({show:!0}),this.#ms.get()&&this.overlayAgent.invoke_setShowDebugBorders({show:!0}),this.#fs.get()&&this.overlayAgent.invoke_setShowFPSCounter({show:!0}),this.#bs.get()&&this.overlayAgent.invoke_setShowScrollBottleneckRects({show:!0}),this.#ys.get()&&this.overlayAgent.invoke_setShowWebVitals({show:!0}),this.#os&&this.#os.isPaused()&&this.updatePausedInDebuggerMessage(),await this.overlayAgent.invoke_setShowViewportSizeOnResize({show:this.#Is})}async suspendModel(){e.EventTarget.removeEventListeners(this.#vs),await this.overlayAgent.invoke_disable()}async resumeModel(){await Promise.all([this.overlayAgent.invoke_enable(),this.wireAgentToSettings()])}setShowViewportSizeOnResize(e){this.#Is!==e&&(this.#Is=e,this.target().suspended()||this.overlayAgent.invoke_setShowViewportSizeOnResize({show:e}))}updatePausedInDebuggerMessage(){if(this.target().suspended())return;const t=this.#os&&this.#os.isPaused()&&!e.Settings.Settings.instance().moduleSetting("disablePausedStateOverlay").get()?yn(fn.pausedInDebugger):void 0;this.overlayAgent.invoke_setPausedInDebuggerMessage({message:t})}setHighlighter(e){this.#hs=e||this.#cs}async setInspectMode(e,t=!0){await this.#Mr.requestDocument(),this.#ls="none"!==e,this.dispatchEventToListeners(In.InspectModeWillBeToggled,this),this.#hs.setInspectMode(e,this.buildHighlightConfig("all",t))}inspectModeEnabled(){return this.#ls}highlightInOverlay(e,t,n){if(this.#ws)return;this.#ds&&(clearTimeout(this.#ds),this.#ds=null);const r=this.buildHighlightConfig(t);void 0!==n&&(r.showInfo=n),this.#hs.highlightInOverlay(e,r)}highlightInOverlayForTwoSeconds(e){this.highlightInOverlay(e),this.delayedHideHighlight(2e3)}highlightGridInPersistentOverlay(e){this.#ks&&(this.#ks.highlightGridInOverlay(e),this.dispatchEventToListeners(In.PersistentGridOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedGridInPersistentOverlay(e){return!!this.#ks&&this.#ks.isGridHighlighted(e)}hideGridInPersistentOverlay(e){this.#ks&&(this.#ks.hideGridInOverlay(e),this.dispatchEventToListeners(In.PersistentGridOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightScrollSnapInPersistentOverlay(e){this.#ks&&(this.#ks.highlightScrollSnapInOverlay(e),this.dispatchEventToListeners(In.PersistentScrollSnapOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedScrollSnapInPersistentOverlay(e){return!!this.#ks&&this.#ks.isScrollSnapHighlighted(e)}hideScrollSnapInPersistentOverlay(e){this.#ks&&(this.#ks.hideScrollSnapInOverlay(e),this.dispatchEventToListeners(In.PersistentScrollSnapOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightFlexContainerInPersistentOverlay(e){this.#ks&&(this.#ks.highlightFlexInOverlay(e),this.dispatchEventToListeners(In.PersistentFlexContainerOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedFlexContainerInPersistentOverlay(e){return!!this.#ks&&this.#ks.isFlexHighlighted(e)}hideFlexContainerInPersistentOverlay(e){this.#ks&&(this.#ks.hideFlexInOverlay(e),this.dispatchEventToListeners(In.PersistentFlexContainerOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightContainerQueryInPersistentOverlay(e){this.#ks&&(this.#ks.highlightContainerQueryInOverlay(e),this.dispatchEventToListeners(In.PersistentContainerQueryOverlayStateChanged,{nodeId:e,enabled:!0}))}isHighlightedContainerQueryInPersistentOverlay(e){return!!this.#ks&&this.#ks.isContainerQueryHighlighted(e)}hideContainerQueryInPersistentOverlay(e){this.#ks&&(this.#ks.hideContainerQueryInOverlay(e),this.dispatchEventToListeners(In.PersistentContainerQueryOverlayStateChanged,{nodeId:e,enabled:!1}))}highlightSourceOrderInOverlay(t){const n={parentOutlineColor:e.Color.SourceOrderHighlight.ParentOutline.toProtocolRGBA(),childOutlineColor:e.Color.SourceOrderHighlight.ChildOutline.toProtocolRGBA()};this.#Ss.highlightSourceOrderInOverlay(t,n)}colorOfGridInPersistentOverlay(e){return this.#ks?this.#ks.colorOfGrid(e).asString("hex"):null}setColorOfGridInPersistentOverlay(t,n){if(!this.#ks)return;const r=e.Color.parse(n);r&&(this.#ks.setColorOfGrid(t,r),this.#ks.resetOverlay())}colorOfFlexInPersistentOverlay(e){return this.#ks?this.#ks.colorOfFlex(e).asString("hex"):null}setColorOfFlexInPersistentOverlay(t,n){if(!this.#ks)return;const r=e.Color.parse(n);r&&(this.#ks.setColorOfFlex(t,r),this.#ks.resetOverlay())}hideSourceOrderInOverlay(){this.#Ss.hideSourceOrderHighlight()}setSourceOrderActive(e){this.#ws=e}sourceOrderModeActive(){return this.#ws}highlightIsolatedElementInPersistentOverlay(e){this.#ks&&this.#ks.highlightIsolatedElementInOverlay(e)}hideIsolatedElementInPersistentOverlay(e){this.#ks&&this.#ks.hideIsolatedElementInOverlay(e)}isHighlightedIsolatedElementInPersistentOverlay(e){return!!this.#ks&&this.#ks.isIsolatedElementHighlighted(e)}delayedHideHighlight(e){null===this.#ds&&(this.#ds=window.setTimeout((()=>this.highlightInOverlay({clear:!0})),e))}highlightFrame(e){this.#ds&&(clearTimeout(this.#ds),this.#ds=null),this.#hs.highlightFrame(e)}showHingeForDualScreen(e){if(e){const{x:t,y:n,width:r,height:s,contentColor:i,outlineColor:a}=e;this.overlayAgent.invoke_setShowHinge({hingeConfig:{rect:{x:t,y:n,width:r,height:s},contentColor:i,outlineColor:a}})}else this.overlayAgent.invoke_setShowHinge({})}buildHighlightConfig(t="all",n=!1){const r=e.Settings.Settings.instance().moduleSetting("showMetricsRulers").get(),s=e.Settings.Settings.instance().moduleSetting("colorFormat").get(),i={showInfo:"all"===t||"container-outline"===t,showRulers:r,showStyles:n,showAccessibilityInfo:n,showExtensionLines:r,gridHighlightConfig:{},flexContainerHighlightConfig:{},flexItemHighlightConfig:{},contrastAlgorithm:o.Runtime.experiments.isEnabled("APCA")?"apca":"aa"};"all"!==t&&"content"!==t||(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA()),"all"!==t&&"padding"!==t||(i.paddingColor=e.Color.PageHighlight.Padding.toProtocolRGBA()),"all"!==t&&"border"!==t||(i.borderColor=e.Color.PageHighlight.Border.toProtocolRGBA()),"all"!==t&&"margin"!==t||(i.marginColor=e.Color.PageHighlight.Margin.toProtocolRGBA()),"all"===t&&(i.eventTargetColor=e.Color.PageHighlight.EventTarget.toProtocolRGBA(),i.shapeColor=e.Color.PageHighlight.Shape.toProtocolRGBA(),i.shapeMarginColor=e.Color.PageHighlight.ShapeMargin.toProtocolRGBA(),i.gridHighlightConfig={rowGapColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA(),rowHatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),columnGapColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA(),columnHatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0},i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},itemSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},lineSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},crossDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},rowGapSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()},columnGapSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}},i.flexItemHighlightConfig={baseSizeBox:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA()},baseSizeBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},flexibilityArrow:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),t.endsWith("gap")&&(i.gridHighlightConfig={gridBorderColor:e.Color.PageHighlight.GridBorder.toProtocolRGBA(),gridBorderDash:!0},"gap"!==t&&"row-gap"!==t||(i.gridHighlightConfig.rowGapColor=e.Color.PageHighlight.GapBackground.toProtocolRGBA(),i.gridHighlightConfig.rowHatchColor=e.Color.PageHighlight.GapHatch.toProtocolRGBA()),"gap"!==t&&"column-gap"!==t||(i.gridHighlightConfig.columnGapColor=e.Color.PageHighlight.GapBackground.toProtocolRGBA(),i.gridHighlightConfig.columnHatchColor=e.Color.PageHighlight.GapHatch.toProtocolRGBA())),t.endsWith("gap")&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}},"gap"!==t&&"row-gap"!==t||(i.flexContainerHighlightConfig.rowGapSpace={hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}),"gap"!==t&&"column-gap"!==t||(i.flexContainerHighlightConfig.columnGapSpace={hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()})),"grid-areas"===t&&(i.gridHighlightConfig={rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0,columnLineDash:!0,showAreaNames:!0,areaBorderColor:e.Color.PageHighlight.GridAreaBorder.toProtocolRGBA()}),"grid-template-columns"===t&&(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA(),i.gridHighlightConfig={columnLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),columnLineDash:!0}),"grid-template-rows"===t&&(i.contentColor=e.Color.PageHighlight.Content.toProtocolRGBA(),i.gridHighlightConfig={rowLineColor:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),rowLineDash:!0}),"justify-content"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},mainDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}}),"align-content"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},crossDistributedSpace:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA(),fillColor:e.Color.PageHighlight.GapBackground.toProtocolRGBA()}}),"align-items"===t&&(i.flexContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},lineSeparator:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"},crossAlignment:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),"flexibility"===t&&(i.flexItemHighlightConfig={baseSizeBox:{hatchColor:e.Color.PageHighlight.GapHatch.toProtocolRGBA()},baseSizeBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dotted"},flexibilityArrow:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA()}}),"container-outline"===t&&(i.containerQueryContainerHighlightConfig={containerBorder:{color:e.Color.PageHighlight.LayoutLine.toProtocolRGBA(),pattern:"dashed"}});return new Set(["rgb","hsl","hex"]).has(s)&&(i.colorFormat=s),i}nodeHighlightRequested({nodeId:e}){const t=this.#Mr.nodeForId(e);t&&this.dispatchEventToListeners(In.HighlightNodeRequested,t)}static setInspectNodeHandler(e){vn.inspectNodeHandler=e}inspectNodeRequested({backendNodeId:t}){const n=new Rn(this.target(),t);vn.inspectNodeHandler?n.resolvePromise().then((e=>{e&&vn.inspectNodeHandler&&vn.inspectNodeHandler(e)})):e.Revealer.reveal(n),this.dispatchEventToListeners(In.ExitedInspectMode)}screenshotRequested({viewport:e}){this.dispatchEventToListeners(In.ScreenshotRequested,e),this.dispatchEventToListeners(In.ExitedInspectMode)}inspectModeCanceled(){this.dispatchEventToListeners(In.ExitedInspectMode)}static inspectNodeHandler=null;getOverlayAgent(){return this.overlayAgent}}var In;!function(e){e.InspectModeWillBeToggled="InspectModeWillBeToggled",e.ExitedInspectMode="InspectModeExited",e.HighlightNodeRequested="HighlightNodeRequested",e.ScreenshotRequested="ScreenshotRequested",e.PersistentGridOverlayStateChanged="PersistentGridOverlayStateChanged",e.PersistentFlexContainerOverlayStateChanged="PersistentFlexContainerOverlayStateChanged",e.PersistentScrollSnapOverlayStateChanged="PersistentScrollSnapOverlayStateChanged",e.PersistentContainerQueryOverlayStateChanged="PersistentContainerQueryOverlayStateChanged"}(In||(In={}));class kn{#$r;constructor(e){this.#$r=e}highlightInOverlay(e,t){const{node:n,deferredNode:r,object:s,selectorList:i}={node:void 0,deferredNode:void 0,object:void 0,selectorList:void 0,...e},a=n?n.id:void 0,o=r?r.backendNodeId():void 0,l=s?s.objectId:void 0;a||o||l?this.#$r.target().overlayAgent().invoke_highlightNode({highlightConfig:t,nodeId:a,backendNodeId:o,objectId:l,selector:i}):this.#$r.target().overlayAgent().invoke_hideHighlight()}async setInspectMode(e,t){await this.#$r.target().overlayAgent().invoke_setInspectMode({mode:e,highlightConfig:t})}highlightFrame(t){this.#$r.target().overlayAgent().invoke_highlightFrame({frameId:t,contentColor:e.Color.PageHighlight.Content.toProtocolRGBA(),contentOutlineColor:e.Color.PageHighlight.ContentOutline.toProtocolRGBA()})}}class Sn{#$r;constructor(e){this.#$r=e}highlightSourceOrderInOverlay(e,t){this.#$r.setSourceOrderActive(!0),this.#$r.setShowViewportSizeOnResize(!1),this.#$r.getOverlayAgent().invoke_highlightSourceOrder({sourceOrderConfig:t,nodeId:e.id})}hideSourceOrderHighlight(){this.#$r.setSourceOrderActive(!1),this.#$r.setShowViewportSizeOnResize(!0),this.#$r.clearHighlight()}}c.register(vn,{capabilities:z.DOM,autostart:!0});var wn,Cn=Object.freeze({__proto__:null,OverlayModel:vn,get Events(){return In},SourceOrderHighlighter:Sn});class Tn{#Cs;#Ts;ownerDocument;#Rs;id;index;#xs;#Ms;#Ps;#Ls;nodeValueInternal;#Es;#As;#Os;#Ns;#Fs;#Bs;#Ds;#Us;#Hs;assignedSlot;shadowRootsInternal;#qs;#_s;#zs;childNodeCountInternal;childrenInternal;nextSibling;previousSibling;firstChild;lastChild;parentNode;templateContentInternal;contentDocumentInternal;childDocumentPromiseForTesting;#js;publicId;systemId;internalSubset;name;value;constructor(e){this.#Cs=e,this.#Ts=this.#Cs.getAgent(),this.index=void 0,this.#Ds=null,this.#Us=new Map,this.#Hs=[],this.assignedSlot=null,this.shadowRootsInternal=[],this.#qs=new Map,this.#_s=new Map,this.#zs=0,this.childrenInternal=null,this.nextSibling=null,this.previousSibling=null,this.firstChild=null,this.lastChild=null,this.parentNode=null}static create(e,t,n,r){const s=new Tn(e);return s.init(t,n,r),s}init(e,t,n){if(this.#Ts=this.#Cs.getAgent(),this.ownerDocument=e,this.#Rs=t,this.id=n.nodeId,this.#xs=n.backendNodeId,this.#Cs.registerNode(this),this.#Ms=n.nodeType,this.#Ps=n.nodeName,this.#Ls=n.localName,this.nodeValueInternal=n.nodeValue,this.#Es=n.pseudoType,this.#As=n.pseudoIdentifier,this.#Os=n.shadowRootType,this.#Ns=n.frameId||null,this.#Fs=n.xmlVersion,this.#Bs=Boolean(n.isSVG),n.attributes&&this.setAttributesPayload(n.attributes),this.childNodeCountInternal=n.childNodeCount||0,n.shadowRoots)for(let e=0;ee.creation||null)),this.#Ds}get subtreeMarkerCount(){return this.#zs}domModel(){return this.#Cs}backendNodeId(){return this.#xs}children(){return this.childrenInternal?this.childrenInternal.slice():null}setChildren(e){this.childrenInternal=e}hasAttributes(){return this.#qs.size>0}childNodeCount(){return this.childNodeCountInternal}setChildNodeCount(e){this.childNodeCountInternal=e}hasShadowRoots(){return Boolean(this.shadowRootsInternal.length)}shadowRoots(){return this.shadowRootsInternal.slice()}templateContent(){return this.templateContentInternal||null}contentDocument(){return this.contentDocumentInternal||null}setContentDocument(e){this.contentDocumentInternal=e}isIframe(){return"IFRAME"===this.#Ps}isPortal(){return"PORTAL"===this.#Ps}importedDocument(){return this.#js||null}nodeType(){return this.#Ms}nodeName(){return this.#Ps}pseudoType(){return this.#Es}pseudoIdentifier(){return this.#As}hasPseudoElements(){return this.#Us.size>0}pseudoElements(){return this.#Us}beforePseudoElement(){return this.#Us.get("before")?.at(-1)}afterPseudoElement(){return this.#Us.get("after")?.at(-1)}markerPseudoElement(){return this.#Us.get("marker")?.at(-1)}backdropPseudoElement(){return this.#Us.get("backdrop")?.at(-1)}viewTransitionPseudoElements(){return[...this.#Us.get("view-transition")||[],...this.#Us.get("view-transition-group")||[],...this.#Us.get("view-transition-image-pair")||[],...this.#Us.get("view-transition-old")||[],...this.#Us.get("view-transition-new")||[]]}hasAssignedSlot(){return null!==this.assignedSlot}isInsertionPoint(){return!this.isXMLNode()&&("SHADOW"===this.#Ps||"CONTENT"===this.#Ps||"SLOT"===this.#Ps)}distributedNodes(){return this.#Hs}isInShadowTree(){return this.#Rs}ancestorShadowHost(){const e=this.ancestorShadowRoot();return e?e.parentNode:null}ancestorShadowRoot(){if(!this.#Rs)return null;let e=this;for(;e&&!e.isShadowRoot();)e=e.parentNode;return e}ancestorUserAgentShadowRoot(){const e=this.ancestorShadowRoot();return e&&e.shadowRootType()===Tn.ShadowRootTypes.UserAgent?e:null}isShadowRoot(){return Boolean(this.#Os)}shadowRootType(){return this.#Os||null}nodeNameInCorrectCase(){const e=this.shadowRootType();return e?"#shadow-root ("+e+")":this.localName()?this.localName().length!==this.nodeName().length?this.nodeName():this.localName():this.nodeName()}setNodeName(e,t){this.#Ts.invoke_setNodeName({nodeId:this.id,name:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}localName(){return this.#Ls}nodeValue(){return this.nodeValueInternal}setNodeValueInternal(e){this.nodeValueInternal=e}setNodeValue(e,t){this.#Ts.invoke_setNodeValue({nodeId:this.id,value:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null)}))}getAttribute(e){const t=this.#qs.get(e);return t?t.value:void 0}setAttribute(e,t,n){this.#Ts.invoke_setAttributesAsText({nodeId:this.id,text:t,name:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null)}))}setAttributeValue(e,t,n){this.#Ts.invoke_setAttributeValue({nodeId:this.id,name:e,value:t}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null)}))}setAttributeValuePromise(e,t){return new Promise((n=>this.setAttributeValue(e,t,n)))}attributes(){return[...this.#qs.values()]}async removeAttribute(e){(await this.#Ts.invoke_removeAttribute({nodeId:this.id,name:e})).getError()||(this.#qs.delete(e),this.#Cs.markUndoableState())}getChildNodes(e){this.childrenInternal?e(this.children()):this.#Ts.invoke_requestChildNodes({nodeId:this.id}).then((t=>{e(t.getError()?null:this.children())}))}async getSubtree(e,t){return(await this.#Ts.invoke_requestChildNodes({nodeId:this.id,depth:e,pierce:t})).getError()?null:this.childrenInternal}async getOuterHTML(){const{outerHTML:e}=await this.#Ts.invoke_getOuterHTML({nodeId:this.id});return e}setOuterHTML(e,t){this.#Ts.invoke_setOuterHTML({nodeId:this.id,outerHTML:e}).then((e=>{e.getError()||this.#Cs.markUndoableState(),t&&t(e.getError()||null)}))}removeNode(e){return this.#Ts.invoke_removeNode({nodeId:this.id}).then((t=>{t.getError()||this.#Cs.markUndoableState(),e&&e(t.getError()||null)}))}async copyNode(){const{outerHTML:e}=await this.#Ts.invoke_getOuterHTML({nodeId:this.id});return null!==e&&i.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(e),e}path(){function e(e){return(void 0!==e.index||e.isShadowRoot()&&e.parentNode)&&e.#Ps.length}const t=[];let n=this;for(;n&&e(n);){const e="number"==typeof n.index?n.index:n.shadowRootType()===Tn.ShadowRootTypes.UserAgent?"u":"a";t.push([e,n.#Ps]),n=n.parentNode}return t.reverse(),t.join(",")}isAncestor(e){if(!e)return!1;let t=e.parentNode;for(;t;){if(this===t)return!0;t=t.parentNode}return!1}isDescendant(e){return null!==e&&e.isAncestor(this)}frameOwnerFrameId(){return this.#Ns}frameId(){let e=this.parentNode||this;for(;!e.#Ns&&e.parentNode;)e=e.parentNode;return e.#Ns}setAttributesPayload(e){let t=!this.#qs||e.length!==2*this.#qs.size;const n=this.#qs||new Map;this.#qs=new Map;for(let r=0;rt!==e));n&&n.length>0?this.#Us.set(t,n):this.#Us.delete(t)}else{const t=this.shadowRootsInternal.indexOf(e);if(-1!==t)this.shadowRootsInternal.splice(t,1);else{if(!this.childrenInternal)throw new Error("DOMNode._children is expected to not be null.");if(-1===this.childrenInternal.indexOf(e))throw new Error("DOMNode._children is expected to contain the node to be removed.");this.childrenInternal.splice(this.childrenInternal.indexOf(e),1)}}e.parentNode=null,this.#zs-=e.#zs,e.#zs&&this.#Cs.dispatchEventToListeners(wn.MarkersChanged,this),this.renumber()}setChildrenPayload(e){this.childrenInternal=[];for(let t=0;t=0?this.childrenInternal[e-1]:null,t.parentNode=this}}addAttribute(e,t){const n={name:e,value:t,_node:this};this.#qs.set(e,n)}setAttributeInternal(e,t){const n=this.#qs.get(e);n?n.value=t:this.addAttribute(e,t)}removeAttributeInternal(e){this.#qs.delete(e)}copyTo(e,t,n){this.#Ts.invoke_copyTo({nodeId:this.id,targetNodeId:e.id,insertBeforeNodeId:t?t.id:void 0}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}moveTo(e,t,n){this.#Ts.invoke_moveTo({nodeId:this.id,targetNodeId:e.id,insertBeforeNodeId:t?t.id:void 0}).then((e=>{e.getError()||this.#Cs.markUndoableState(),n&&n(e.getError()||null,this.#Cs.nodeForId(e.nodeId))}))}isXMLNode(){return Boolean(this.#Fs)}setMarker(e,t){if(null!==t){if(this.parentNode&&!this.#_s.has(e))for(let e=this;e;e=e.parentNode)++e.#zs;this.#_s.set(e,t);for(let e=this;e;e=e.parentNode)this.#Cs.dispatchEventToListeners(wn.MarkersChanged,e)}else{if(!this.#_s.has(e))return;this.#_s.delete(e);for(let e=this;e;e=e.parentNode)--e.#zs;for(let e=this;e;e=e.parentNode)this.#Cs.dispatchEventToListeners(wn.MarkersChanged,e)}}marker(e){return this.#_s.get(e)||null}getMarkerKeysForTest(){return[...this.#_s.keys()]}traverseMarkers(e){!function t(n){if(n.#zs){for(const t of n.#_s.keys())e(n,t);if(n.childrenInternal)for(const e of n.childrenInternal)t(e)}}(this)}resolveURL(t){if(!t)return t;for(let n=this;n;n=n.parentNode)if(n instanceof Mn&&n.baseURL)return e.ParsedURL.ParsedURL.completeURL(n.baseURL,t);return null}highlight(e){this.#Cs.overlayModel().highlightInOverlay({node:this,selectorList:void 0},e)}highlightForTwoSeconds(){this.#Cs.overlayModel().highlightInOverlayForTwoSeconds({node:this,selectorList:void 0})}async resolveToObject(e){const{object:t}=await this.#Ts.invoke_resolveNode({nodeId:this.id,backendNodeId:void 0,objectGroup:e});return t&&this.#Cs.runtimeModelInternal.createRemoteObject(t)||null}async boxModel(){const{model:e}=await this.#Ts.invoke_getBoxModel({nodeId:this.id});return e}async setAsInspectedNode(){let e=this;for(e&&e.pseudoType()&&(e=e.parentNode);e;){let t=e.ancestorUserAgentShadowRoot();if(!t)break;if(t=e.ancestorShadowHost(),!t)break;e=t}if(!e)throw new Error("In DOMNode.setAsInspectedNode: node is expected to not be null.");await this.#Ts.invoke_setInspectedNode({nodeId:e.id})}enclosingElementOrSelf(){let e=this;return e&&e.nodeType()===Node.TEXT_NODE&&e.parentNode&&(e=e.parentNode),e&&e.nodeType()!==Node.ELEMENT_NODE&&(e=null),e}async scrollIntoView(){const e=this.enclosingElementOrSelf();if(!e)return;const t=await e.resolveToObject();t&&(t.callFunction((function(){this.scrollIntoViewIfNeeded(!0)})),t.release(),e.highlightForTwoSeconds())}async focus(){const e=this.enclosingElementOrSelf();if(!e)throw new Error("DOMNode.focus expects node to not be null.");const t=await e.resolveToObject();t&&(await t.callFunction((function(){this.focus()})),t.release(),e.highlightForTwoSeconds(),await this.#Cs.target().pageAgent().invoke_bringToFront())}simpleSelector(){const e=this.localName()||this.nodeName().toLowerCase();if(this.nodeType()!==Node.ELEMENT_NODE)return e;const t=this.getAttribute("type"),n=this.getAttribute("id"),r=this.getAttribute("class");if("input"===e&&t&&!n&&!r)return e+'[type="'+CSS.escape(t)+'"]';if(n)return e+"#"+CSS.escape(n);if(r){return("div"===e?"":e)+"."+r.trim().split(/\s+/g).map((e=>CSS.escape(e))).join(".")}return e}}!function(e){let t;!function(e){e.UserAgent="user-agent",e.Open="open",e.Closed="closed"}(t=e.ShadowRootTypes||(e.ShadowRootTypes={}))}(Tn||(Tn={}));class Rn{#Cs;#xs;constructor(e,t){this.#Cs=e.model(Pn),this.#xs=t}resolve(e){this.resolvePromise().then(e)}async resolvePromise(){const e=await this.#Cs.pushNodesByBackendIdsToFrontend(new Set([this.#xs]));return e&&e.get(this.#xs)||null}backendNodeId(){return this.#xs}domModel(){return this.#Cs}highlight(){this.#Cs.overlayModel().highlightInOverlay({deferredNode:this,selectorList:void 0})}}class xn{nodeType;nodeName;deferredNode;constructor(e,t,n,r){this.nodeType=n,this.nodeName=r,this.deferredNode=new Rn(e,t)}}class Mn extends Tn{body;documentElement;documentURL;baseURL;constructor(e,t){super(e),this.body=null,this.documentElement=null,this.init(this,!1,t),this.documentURL=t.documentURL||"",this.baseURL=t.baseURL||""}}class Pn extends c{agent;idToDOMNode=new Map;#Ws;#Vs;runtimeModelInternal;#Gs;#Ks;#$s;#Qs;#Xs;constructor(e){super(e),this.agent=e.domAgent(),this.#Ws=null,this.#Vs=new Set,e.registerDOMDispatcher(new Ln(this)),this.runtimeModelInternal=e.model(Cr),this.#Ks=null,e.suspended()||this.agent.invoke_enable({}),o.Runtime.experiments.isEnabled("captureNodeCreationStacks")&&this.agent.invoke_setNodeStackTracesEnabled({enable:!0})}runtimeModel(){return this.runtimeModelInternal}cssModel(){return this.target().model(en)}overlayModel(){return this.target().model(vn)}static cancelSearch(){for(const e of K.instance().models(Pn))e.cancelSearch()}scheduleMutationEvent(e){this.hasEventListeners(wn.DOMMutated)&&(this.#Gs=(this.#Gs||0)+1,Promise.resolve().then(function(e,t){if(!this.hasEventListeners(wn.DOMMutated)||this.#Gs!==t)return;this.dispatchEventToListeners(wn.DOMMutated,e)}.bind(this,e,this.#Gs)))}requestDocument(){return this.#Ws?Promise.resolve(this.#Ws):(this.#Ks||(this.#Ks=this.requestDocumentInternal()),this.#Ks)}async getOwnerNodeForFrame(e){const t=await this.agent.invoke_getFrameOwner({frameId:e});return t.getError()?null:new Rn(this.target(),t.backendNodeId)}async requestDocumentInternal(){const e=await this.agent.invoke_getDocument({});if(e.getError())return null;const{root:t}=e;if(this.#Ks=null,t&&this.setDocument(t),!this.#Ws)return console.error("No document"),null;const n=this.parentModel();if(n&&!this.#$s){await n.requestDocument();const e=this.target().model(jn)?.mainFrame;if(e){const t=await n.agent.invoke_getFrameOwner({frameId:e.id});!t.getError()&&t.nodeId&&(this.#$s=n.nodeForId(t.nodeId))}}if(this.#$s){const e=this.#$s.contentDocument();this.#$s.setContentDocument(this.#Ws),this.#$s.setChildren([]),this.#Ws?(this.#Ws.parentNode=this.#$s,this.dispatchEventToListeners(wn.NodeInserted,this.#Ws)):e&&this.dispatchEventToListeners(wn.NodeRemoved,{node:e,parent:this.#$s})}return this.#Ws}existingDocument(){return this.#Ws}async pushNodeToFrontend(e){await this.requestDocument();const{nodeId:t}=await this.agent.invoke_requestNode({objectId:e});return t?this.nodeForId(t):null}pushNodeByPathToFrontend(e){return this.requestDocument().then((()=>this.agent.invoke_pushNodeByPathToFrontend({path:e}))).then((({nodeId:e})=>e))}async pushNodesByBackendIdsToFrontend(e){await this.requestDocument();const t=[...e],{nodeIds:n}=await this.agent.invoke_pushNodesByBackendIdsToFrontend({backendNodeIds:t});if(!n)return null;const r=new Map;for(let e=0;e{if(!t)return;const n=this.idToDOMNode.get(e);n&&n.setAttributesPayload(t)&&(this.dispatchEventToListeners(wn.AttrModified,{node:n,name:"style"}),this.scheduleMutationEvent(n))}));this.#Vs.clear()}characterDataModified(e,t){const n=this.idToDOMNode.get(e);n?(n.setNodeValueInternal(t),this.dispatchEventToListeners(wn.CharacterDataModified,n),this.scheduleMutationEvent(n)):console.error("nodeId could not be resolved to a node")}nodeForId(e){return e&&this.idToDOMNode.get(e)||null}documentUpdated(){const e=this.#Ks;this.setDocument(null),this.parentModel()&&!e&&this.requestDocument()}setDocument(e){this.idToDOMNode=new Map,this.#Ws=e&&"nodeId"in e?new Mn(this,e):null,An.instance().dispose(this),this.parentModel()||this.dispatchEventToListeners(wn.DocumentUpdated,this)}setDetachedRoot(e){"#document"===e.nodeName?new Mn(this,e):Tn.create(this,null,!1,e)}setChildNodes(e,t){if(!e&&t.length)return void this.setDetachedRoot(t[0]);this.idToDOMNode.get(e)?.setChildrenPayload(t)}childNodeCountUpdated(e,t){const n=this.idToDOMNode.get(e);n?(n.setChildNodeCount(t),this.dispatchEventToListeners(wn.ChildNodeCountUpdated,n),this.scheduleMutationEvent(n)):console.error("nodeId could not be resolved to a node")}childNodeInserted(e,t,n){const r=this.idToDOMNode.get(e),s=this.idToDOMNode.get(t);if(!r)return void console.error("parentId could not be resolved to a node");const i=r.insertChild(s,n);this.idToDOMNode.set(i.id,i),this.dispatchEventToListeners(wn.NodeInserted,i),this.scheduleMutationEvent(i)}childNodeRemoved(e,t){const n=this.idToDOMNode.get(e),r=this.idToDOMNode.get(t);n&&r?(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r)):console.error("parentId or nodeId could not be resolved to a node")}shadowRootPushed(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=Tn.create(this,n.ownerDocument,!0,t);r.parentNode=n,this.idToDOMNode.set(r.id,r),n.shadowRootsInternal.unshift(r),this.dispatchEventToListeners(wn.NodeInserted,r),this.scheduleMutationEvent(r)}shadowRootPopped(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=this.idToDOMNode.get(t);r&&(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r))}pseudoElementAdded(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=Tn.create(this,n.ownerDocument,!1,t);r.parentNode=n,this.idToDOMNode.set(r.id,r);const s=r.pseudoType();if(!s)throw new Error("DOMModel._pseudoElementAdded expects pseudoType to be defined.");const i=n.pseudoElements().get(s);i?i.push(r):n.pseudoElements().set(s,[r]),this.dispatchEventToListeners(wn.NodeInserted,r),this.scheduleMutationEvent(r)}topLayerElementsUpdated(){this.dispatchEventToListeners(wn.TopLayerElementsChanged)}pseudoElementRemoved(e,t){const n=this.idToDOMNode.get(e);if(!n)return;const r=this.idToDOMNode.get(t);r&&(n.removeChild(r),this.unbind(r),this.dispatchEventToListeners(wn.NodeRemoved,{node:r,parent:n}),this.scheduleMutationEvent(r))}distributedNodesUpdated(e,t){const n=this.idToDOMNode.get(e);n&&(n.setDistributedNodePayloads(t),this.dispatchEventToListeners(wn.DistributedNodesChanged,n),this.scheduleMutationEvent(n))}unbind(e){this.idToDOMNode.delete(e.id);const t=e.children();for(let e=0;t&&ee||[]))}querySelector(e,t){return this.agent.invoke_querySelector({nodeId:e,selector:t}).then((({nodeId:e})=>e))}querySelectorAll(e,t){return this.agent.invoke_querySelectorAll({nodeId:e,selector:t}).then((({nodeIds:e})=>e))}getTopLayerElements(){return this.agent.invoke_getTopLayerElements().then((({nodeIds:e})=>e))}markUndoableState(e){An.instance().markUndoableState(this,e||!1)}async nodeForLocation(e,t,n){const r=await this.agent.invoke_getNodeForLocation({x:e,y:t,includeUserAgentShadowDOM:n});return r.getError()||!r.nodeId?null:this.nodeForId(r.nodeId)}async getContainerForNode(e,t,n,r){const{nodeId:s}=await this.agent.invoke_getContainerForNode({nodeId:e,containerName:t,physicalAxes:n,logicalAxes:r});return s?this.nodeForId(s):null}pushObjectAsNodeToFrontend(e){return e.isNode()&&e.objectId?this.pushNodeToFrontend(e.objectId):Promise.resolve(null)}suspendModel(){return this.agent.invoke_disable().then((()=>this.setDocument(null)))}async resumeModel(){await this.agent.invoke_enable({})}dispose(){An.instance().dispose(this)}parentModel(){const e=this.target().parentTarget();return e?e.model(Pn):null}getAgent(){return this.agent}registerNode(e){this.idToDOMNode.set(e.id,e)}}!function(e){e.AttrModified="AttrModified",e.AttrRemoved="AttrRemoved",e.CharacterDataModified="CharacterDataModified",e.DOMMutated="DOMMutated",e.NodeInserted="NodeInserted",e.NodeRemoved="NodeRemoved",e.DocumentUpdated="DocumentUpdated",e.ChildNodeCountUpdated="ChildNodeCountUpdated",e.DistributedNodesChanged="DistributedNodesChanged",e.MarkersChanged="MarkersChanged",e.TopLayerElementsChanged="TopLayerElementsChanged"}(wn||(wn={}));class Ln{#Mr;constructor(e){this.#Mr=e}documentUpdated(){this.#Mr.documentUpdated()}attributeModified({nodeId:e,name:t,value:n}){this.#Mr.attributeModified(e,t,n)}attributeRemoved({nodeId:e,name:t}){this.#Mr.attributeRemoved(e,t)}inlineStyleInvalidated({nodeIds:e}){this.#Mr.inlineStyleInvalidated(e)}characterDataModified({nodeId:e,characterData:t}){this.#Mr.characterDataModified(e,t)}setChildNodes({parentId:e,nodes:t}){this.#Mr.setChildNodes(e,t)}childNodeCountUpdated({nodeId:e,childNodeCount:t}){this.#Mr.childNodeCountUpdated(e,t)}childNodeInserted({parentNodeId:e,previousNodeId:t,node:n}){this.#Mr.childNodeInserted(e,t,n)}childNodeRemoved({parentNodeId:e,nodeId:t}){this.#Mr.childNodeRemoved(e,t)}shadowRootPushed({hostId:e,root:t}){this.#Mr.shadowRootPushed(e,t)}shadowRootPopped({hostId:e,rootId:t}){this.#Mr.shadowRootPopped(e,t)}pseudoElementAdded({parentId:e,pseudoElement:t}){this.#Mr.pseudoElementAdded(e,t)}pseudoElementRemoved({parentId:e,pseudoElementId:t}){this.#Mr.pseudoElementRemoved(e,t)}distributedNodesUpdated({insertionPointId:e,distributedNodes:t}){this.#Mr.distributedNodesUpdated(e,t)}topLayerElementsUpdated(){this.#Mr.topLayerElementsUpdated()}}let En;class An{#Js;#Kr;#Ys;constructor(){this.#Js=[],this.#Kr=0,this.#Ys=null}static instance(e={forceNew:null}){const{forceNew:t}=e;return En&&!t||(En=new An),En}async markUndoableState(e,t){this.#Ys&&e!==this.#Ys&&(this.#Ys.markUndoableState(),this.#Ys=null),t&&this.#Ys===e||(this.#Js=this.#Js.slice(0,this.#Kr),this.#Js.push(e),this.#Kr=this.#Js.length,t?this.#Ys=e:(await e.getAgent().invoke_markUndoableState(),this.#Ys=null))}async undo(){if(0===this.#Kr)return Promise.resolve();--this.#Kr,this.#Ys=null,await this.#Js[this.#Kr].getAgent().invoke_undo()}async redo(){if(this.#Kr>=this.#Js.length)return Promise.resolve();++this.#Kr,this.#Ys=null,await this.#Js[this.#Kr-1].getAgent().invoke_redo()}dispose(e){let n=0;for(let t=0;t{this.#ai.push(e),this.#Zs&&!this.#Zs.finished||this.innerRequestContent()}))}canonicalMimeType(){return this.contentType().canonicalMimeType()||this.mimeType}async searchInContent(e,t,n){if(!this.frameId)return[];if(this.request)return this.request.searchInContent(e,t,n);return(await this.#Er.target().pageAgent().invoke_searchInResource({frameId:this.frameId,url:this.url,query:e,caseSensitive:t,isRegex:n})).result||[]}async populateImageSource(e){const{content:t}=await this.requestContent(),n=this.#ii;e.src=r.ContentProvider.contentAsDataURL(t,this.#kt,n)||this.#mt}requestFinished(){this.#Zs&&this.#Zs.removeEventListener(Te.FinishedLoading,this.requestFinished,this),this.#ai.length&&this.innerRequestContent()}async innerRequestContent(){if(this.#oi)return;this.#oi=!0;let e=null;if(this.request){const t=await this.request.contentData();t.error||(this.#si=t.content,this.#ii=t.encoded,e={content:t.content,isEncoded:t.encoded})}if(!e){const t=await this.#Er.target().pageAgent().invoke_getResourceContent({frameId:this.frameId,url:this.url}),n=t.getError();n?(this.#si=null,e={content:null,error:n,isEncoded:!1}):(this.#si=t.content,e={content:t.content,isEncoded:t.base64Encoded}),this.#ii=t.base64Encoded}null===this.#si&&(this.#ii=!1);for(const t of this.#ai.splice(0))t(e);this.#oi=void 0}hasTextContent(){return!!this.#ei.isTextType()||this.#ei===e.ResourceType.resourceTypes.Other&&(Boolean(this.#si)&&!this.#ii)}frame(){return this.#Ce?this.#Er.frameForId(this.#Ce):null}statusCode(){return this.#Zs?this.#Zs.statusCode:0}}var Fn,Bn=Object.freeze({__proto__:null,Resource:Nn});class Dn extends c{#li;#di;#ci;constructor(e){super(e),this.#li="",this.#di="",this.#ci=new Set}updateSecurityOrigins(e){const t=this.#ci;this.#ci=e;for(const e of t)this.#ci.has(e)||this.dispatchEventToListeners(Fn.SecurityOriginRemoved,e);for(const e of this.#ci)t.has(e)||this.dispatchEventToListeners(Fn.SecurityOriginAdded,e)}securityOrigins(){return[...this.#ci]}mainSecurityOrigin(){return this.#li}unreachableMainSecurityOrigin(){return this.#di}setMainSecurityOrigin(e,t){this.#li=e,this.#di=t||null,this.dispatchEventToListeners(Fn.MainSecurityOriginChanged,{mainSecurityOrigin:this.#li,unreachableMainSecurityOrigin:this.#di})}}!function(e){e.SecurityOriginAdded="SecurityOriginAdded",e.SecurityOriginRemoved="SecurityOriginRemoved",e.MainSecurityOriginChanged="MainSecurityOriginChanged"}(Fn||(Fn={})),c.register(Dn,{capabilities:z.None,autostart:!1});var Un,Hn=Object.freeze({__proto__:null,SecurityOriginManager:Dn,get Events(){return Fn}});class qn extends c{#hi;#ui;constructor(e){super(e),this.#hi="",this.#ui=new Set}updateStorageKeys(e){const t=this.#ui;this.#ui=e;for(const e of t)this.#ui.has(e)||this.dispatchEventToListeners(Un.StorageKeyRemoved,e);for(const e of this.#ui)t.has(e)||this.dispatchEventToListeners(Un.StorageKeyAdded,e)}storageKeys(){return[...this.#ui]}mainStorageKey(){return this.#hi}setMainStorageKey(e){this.#hi=e,this.dispatchEventToListeners(Un.MainStorageKeyChanged,{mainStorageKey:this.#hi})}}!function(e){e.StorageKeyAdded="StorageKeyAdded",e.StorageKeyRemoved="StorageKeyRemoved",e.MainStorageKeyChanged="MainStorageKeyChanged"}(Un||(Un={})),c.register(qn,{capabilities:z.None,autostart:!1});var _n,zn=Object.freeze({__proto__:null,StorageKeyManager:qn,parseStorageKey:function(t){const n=t.split("^"),r={origin:e.ParsedURL.ParsedURL.extractOrigin(n[0]),components:new Map};for(let e=1;e{this.processCachedResources(e.getError()?null:e.frameTree),this.mainFrame&&this.processPendingEvents(this.mainFrame)}))}static frameForRequest(e){const t=ne.forRequest(e),n=t?t.target().model(jn):null;return n&&e.frameId?n.frameForId(e.frameId):null}static frames(){const e=[];for(const t of K.instance().models(jn))e.push(...t.frames());return e}static resourceForURL(e){for(const t of K.instance().models(jn)){const n=t.mainFrame,r=n?n.resourceForURL(e):null;if(r)return r}return null}static reloadAllPages(e,t){for(const n of K.instance().models(jn))n.target().parentTarget()?.type()!==_.Frame&&n.reloadPage(e,t)}async storageKeyForFrame(e){if(!this.framesInternal.has(e))return null;const t=await this.storageAgent.invoke_getStorageKeyForFrame({frameId:e});return"Frame tree node for given frame not found"===t.getError()?null:t.storageKey}domModel(){return this.target().model(Pn)}processCachedResources(e){e&&":"!==e.frame.url&&(this.dispatchEventToListeners(_n.WillLoadCachedResources),this.addFramesRecursively(null,e),this.target().setInspectedURL(e.frame.url)),this.#mi=!0;const t=this.target().model(Cr);t&&(t.setExecutionContextComparator(this.executionContextComparator.bind(this)),t.fireExecutionContextOrderChanged()),this.dispatchEventToListeners(_n.CachedResourcesLoaded,this)}cachedResourcesLoaded(){return this.#mi}addFrame(e,t){this.framesInternal.set(e.id,e),e.isMainFrame()&&(this.mainFrame=e),this.dispatchEventToListeners(_n.FrameAdded,e),this.updateSecurityOrigins(),this.updateStorageKeys()}frameAttached(e,t,n){const r=t&&this.framesInternal.get(t)||null;if(!this.#mi&&r)return null;if(this.framesInternal.has(e))return null;const s=new Wn(this,r,e,null,n||null);return t&&!r&&(s.crossTargetParentFrameId=t),s.isMainFrame()&&this.mainFrame&&this.frameDetached(this.mainFrame.id,!1),this.addFrame(s,!0),s}frameNavigated(e,t){const n=e.parentId&&this.framesInternal.get(e.parentId)||null;if(!this.#mi&&n)return;let r=this.framesInternal.get(e.id)||null;if(!r&&(r=this.frameAttached(e.id,e.parentId||null),console.assert(Boolean(r)),!r))return;this.dispatchEventToListeners(_n.FrameWillNavigate,r),r.navigate(e),t&&(r.backForwardCacheDetails.restoredFromCache="BackForwardCacheRestore"===t),this.dispatchEventToListeners(_n.FrameNavigated,r),r.isPrimaryFrame()&&this.primaryPageChanged(r,"Navigation");const s=r.resources();for(let e=0;e=0,"Unbalanced call to ResourceTreeModel.resumeReload()"),!this.#bi&&this.#fi){const{ignoreCache:e,scriptToEvaluateOnLoad:t}=this.#fi;this.reloadPage(e,t)}}reloadPage(e,t){if(this.#fi||this.dispatchEventToListeners(_n.PageReloadRequested,this),this.#bi)return void(this.#fi={ignoreCache:e,scriptToEvaluateOnLoad:t});this.#fi=null;const n=this.target().model(ne);n&&n.clearRequests(),this.dispatchEventToListeners(_n.WillReloadPage),this.agent.invoke_reload({ignoreCache:e,scriptToEvaluateOnLoad:t})}navigate(e){return this.agent.invoke_navigate({url:e})}async navigationHistory(){const e=await this.agent.invoke_getNavigationHistory();return e.getError()?null:{currentIndex:e.currentIndex,entries:e.entries}}navigateToHistoryEntry(e){this.agent.invoke_navigateToHistoryEntry({entryId:e.id})}setLifecycleEventsEnabled(e){return this.agent.invoke_setLifecycleEventsEnabled({enabled:e})}async fetchAppManifest(){const e=await this.agent.invoke_getAppManifest();return e.getError()?{url:e.url,data:null,errors:[]}:{url:e.url,data:e.data||null,errors:e.errors}}async getInstallabilityErrors(){return(await this.agent.invoke_getInstallabilityErrors()).installabilityErrors||[]}async getAppId(){return this.agent.invoke_getAppId()}executionContextComparator(e,t){function n(e){let t=e;const n=[];for(;t;)n.push(t),t=t.sameTargetParentFrame();return n.reverse()}if(e.target()!==t.target())return Mr.comparator(e,t);const r=e.frameId?n(this.frameForId(e.frameId)):[],s=t.frameId?n(this.frameForId(t.frameId)):[];let i,a;for(let e=0;;e++)if(!r[e]||!s[e]||r[e]!==s[e]){i=r[e],a=s[e];break}return!i&&a?-1:!a&&i?1:i&&a?i.id.localeCompare(a.id):Mr.comparator(e,t)}getSecurityOriginData(){const t=new Set;let n=null,r=null;for(const s of this.framesInternal.values()){const i=s.securityOrigin;if(i&&(t.add(i),s.isMainFrame()&&(n=i,s.unreachableUrl()))){r=new e.ParsedURL.ParsedURL(s.unreachableUrl()).securityOrigin()}}return{securityOrigins:t,mainSecurityOrigin:n,unreachableMainSecurityOrigin:r}}async getStorageKeyData(){const e=new Set;let t=null;for(const{isMainFrame:n,storageKey:r}of await Promise.all([...this.framesInternal.values()].map((e=>e.getStorageKey(!1).then((t=>({isMainFrame:e.isMainFrame(),storageKey:t})))))))n&&(t=r),r&&e.add(r);return{storageKeys:e,mainStorageKey:t}}updateSecurityOrigins(){const e=this.getSecurityOriginData();this.#gi.setMainSecurityOrigin(e.mainSecurityOrigin||"",e.unreachableMainSecurityOrigin||""),this.#gi.updateSecurityOrigins(e.securityOrigins)}async updateStorageKeys(){const e=await this.getStorageKeyData();this.#pi.setMainStorageKey(e.mainStorageKey||""),this.#pi.updateStorageKeys(e.storageKeys)}async getMainStorageKey(){return this.mainFrame?this.mainFrame.getStorageKey(!1):null}getMainSecurityOrigin(){const e=this.getSecurityOriginData();return e.mainSecurityOrigin||e.unreachableMainSecurityOrigin}onBackForwardCacheNotUsed(e){this.mainFrame&&this.mainFrame.id===e.frameId&&this.mainFrame.loaderId===e.loaderId?(this.mainFrame.setBackForwardCacheDetails(e),this.dispatchEventToListeners(_n.BackForwardCacheDetailsUpdated,this.mainFrame)):this.#yi.add(e)}onPrerenderAttemptCompleted(e){this.mainFrame&&this.mainFrame.id===e.initiatingFrameId?(this.mainFrame.setPrerenderFinalStatus(e.finalStatus),this.dispatchEventToListeners(_n.PrerenderingStatusUpdated,this.mainFrame),e.disallowedApiMethod&&this.mainFrame.setPrerenderDisallowedApiMethod(e.disallowedApiMethod)):this.#vi.add(e),this.dispatchEventToListeners(_n.PrerenderAttemptCompleted,e)}processPendingEvents(e){if(e.isMainFrame()){for(const t of this.#yi)if(e.id===t.frameId&&e.loaderId===t.loaderId){e.setBackForwardCacheDetails(t),this.#yi.delete(t);break}for(const t of this.#vi)if(e.id===t.initiatingFrameId){e.setPrerenderFinalStatus(t.finalStatus),t.disallowedApiMethod&&e.setPrerenderDisallowedApiMethod(t.disallowedApiMethod),this.#vi.delete(t);break}}}}!function(e){e.FrameAdded="FrameAdded",e.FrameNavigated="FrameNavigated",e.FrameDetached="FrameDetached",e.FrameResized="FrameResized",e.FrameWillNavigate="FrameWillNavigate",e.PrimaryPageChanged="PrimaryPageChanged",e.ResourceAdded="ResourceAdded",e.WillLoadCachedResources="WillLoadCachedResources",e.CachedResourcesLoaded="CachedResourcesLoaded",e.DOMContentLoaded="DOMContentLoaded",e.LifecycleEvent="LifecycleEvent",e.Load="Load",e.PageReloadRequested="PageReloadRequested",e.WillReloadPage="WillReloadPage",e.InterstitialShown="InterstitialShown",e.InterstitialHidden="InterstitialHidden",e.BackForwardCacheDetailsUpdated="BackForwardCacheDetailsUpdated",e.PrerenderingStatusUpdated="PrerenderingStatusUpdated",e.PrerenderAttemptCompleted="PrerenderAttemptCompleted",e.JavaScriptDialogOpening="JavaScriptDialogOpening"}(_n||(_n={}));class Wn{#$r;#ki;#E;crossTargetParentFrameId;#Te;#u;#mt;#Si;#wi;#Ci;#Ti;#Ri;#xi;#Mi;#Pi;#Li;#Ei;#Ai;resourcesMap;backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};prerenderFinalStatus;prerenderDisallowedApiMethod;constructor(e,n,r,s,i){this.#$r=e,this.#ki=n,this.#E=r,this.crossTargetParentFrameId=null,this.#Te=s&&s.loaderId||"",this.#u=s&&s.name,this.#mt=s&&s.url||t.DevToolsPath.EmptyUrlString,this.#Si=s&&s.domainAndRegistry||"",this.#wi=s&&s.securityOrigin,this.#Ti=s&&s.unreachableUrl||t.DevToolsPath.EmptyUrlString,this.#Ri=s?.adFrameStatus,this.#xi=s&&s.secureContextType,this.#Mi=s&&s.crossOriginIsolatedContextType,this.#Pi=s&&s.gatedAPIFeatures,this.#Li=i,this.#Ei=null,this.#Ai=new Set,this.resourcesMap=new Map,this.prerenderFinalStatus=null,this.prerenderDisallowedApiMethod=null,this.#ki&&this.#ki.#Ai.add(this)}isSecureContext(){return null!==this.#xi&&this.#xi.startsWith("Secure")}getSecureContextType(){return this.#xi}isCrossOriginIsolated(){return null!==this.#Mi&&this.#Mi.startsWith("Isolated")}getCrossOriginIsolatedContextType(){return this.#Mi}getGatedAPIFeatures(){return this.#Pi}getCreationStackTraceData(){return{creationStackTrace:this.#Li,creationStackTraceTarget:this.#Ei||this.resourceTreeModel().target()}}navigate(e){this.#Te=e.loaderId,this.#u=e.name,this.#mt=e.url,this.#Si=e.domainAndRegistry,this.#wi=e.securityOrigin,this.getStorageKey(!0),this.#Ti=e.unreachableUrl||t.DevToolsPath.EmptyUrlString,this.#Ri=e?.adFrameStatus,this.#xi=e.secureContextType,this.#Mi=e.crossOriginIsolatedContextType,this.#Pi=e.gatedAPIFeatures,this.backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};const n=this.resourcesMap.get(this.#mt);this.resourcesMap.clear(),this.removeChildFrames(),n&&n.loaderId===this.#Te&&this.addResource(n)}resourceTreeModel(){return this.#$r}get id(){return this.#E}get name(){return this.#u||""}get url(){return this.#mt}domainAndRegistry(){return this.#Si}async getAdScriptId(e){return(await this.#$r.agent.invoke_getAdScriptId({frameId:e})).adScriptId||null}get securityOrigin(){return this.#wi}getStorageKey(e){return this.#Ci&&!e||(this.#Ci=this.#$r.storageKeyForFrame(this.#E)),this.#Ci}unreachableUrl(){return this.#Ti}get loaderId(){return this.#Te}adFrameType(){return this.#Ri?.adFrameType||"none"}adFrameStatus(){return this.#Ri}get childFrames(){return[...this.#Ai]}sameTargetParentFrame(){return this.#ki}crossTargetParentFrame(){if(!this.crossTargetParentFrameId)return null;const e=this.#$r.target().parentTarget();if(e?.type()!==_.Frame)return null;const t=e.model(jn);return t&&t.framesInternal.get(this.crossTargetParentFrameId)||null}parentFrame(){return this.sameTargetParentFrame()||this.crossTargetParentFrame()}isMainFrame(){return!this.#ki}isOutermostFrame(){return this.#$r.target().parentTarget()?.type()!==_.Frame&&!this.#ki&&!this.crossTargetParentFrameId}isPrimaryFrame(){return!this.#ki&&this.#$r.target()===K.instance().primaryPageTarget()}removeChildFrame(e,t){this.#Ai.delete(e),e.remove(t)}removeChildFrames(){const e=this.#Ai;this.#Ai=new Set;for(const t of e)t.remove(!1)}remove(e){this.removeChildFrames(),this.#$r.framesInternal.delete(this.id),this.#$r.dispatchEventToListeners(_n.FrameDetached,{frame:this,isSwap:e})}addResource(e){this.resourcesMap.get(e.url)!==e&&(this.resourcesMap.set(e.url,e),this.#$r.dispatchEventToListeners(_n.ResourceAdded,e))}addRequest(e){let t=this.resourcesMap.get(e.url());t&&t.request===e||(t=new Nn(this.#$r,e,e.url(),e.documentURL,e.frameId,e.loaderId,e.resourceType(),e.mimeType,null,null),this.resourcesMap.set(t.url,t),this.#$r.dispatchEventToListeners(_n.ResourceAdded,t))}resources(){return Array.from(this.resourcesMap.values())}resourceForURL(e){const t=this.resourcesMap.get(e);if(t)return t;for(const t of this.#Ai){const n=t.resourceForURL(e);if(n)return n}return null}callForFrameResources(e){for(const t of this.resourcesMap.values())if(e(t))return!0;for(const t of this.#Ai)if(t.callForFrameResources(e))return!0;return!1}displayName(){if(this.isOutermostFrame())return s.i18n.lockedString("top");const t=new e.ParsedURL.ParsedURL(this.#mt).displayName;return t?this.#u?this.#u+" ("+t+")":t:s.i18n.lockedString("iframe")}async getOwnerDeferredDOMNode(){const e=this.parentFrame();return e?e.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#E):null}async getOwnerDOMNodeOrDocument(){const e=await this.getOwnerDeferredDOMNode();return e?e.resolvePromise():this.isOutermostFrame()?this.resourceTreeModel().domModel().requestDocument():null}async highlight(){const e=this.parentFrame(),t=this.resourceTreeModel().target().parentTarget(),n=async e=>{const t=await e.getOwnerNodeForFrame(this.#E);t&&e.overlayModel().highlightInOverlay({deferredNode:t,selectorList:""},"all",!0)};if(e)return n(e.resourceTreeModel().domModel());if(t?.type()===_.Frame){const e=t.model(Pn);if(e)return n(e)}const r=await this.resourceTreeModel().domModel().requestDocument();r&&this.resourceTreeModel().domModel().overlayModel().highlightInOverlay({node:r,selectorList:""},"all",!0)}async getPermissionsPolicyState(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getPermissionsPolicyState({frameId:this.#E});return e.getError()?null:e.states}async getOriginTrials(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getOriginTrials({frameId:this.#E});return e.getError()?[]:e.originTrials}setCreationStackTrace(e){this.#Li=e.creationStackTrace,this.#Ei=e.creationStackTraceTarget}setBackForwardCacheDetails(e){this.backForwardCacheDetails.restoredFromCache=!1,this.backForwardCacheDetails.explanations=e.notRestoredExplanations,this.backForwardCacheDetails.explanationsTree=e.notRestoredExplanationsTree}getResourcesMap(){return this.resourcesMap}setPrerenderFinalStatus(e){this.prerenderFinalStatus=e}setPrerenderDisallowedApiMethod(e){this.prerenderDisallowedApiMethod=e}}class Vn{#Er;constructor(e){this.#Er=e}backForwardCacheNotUsed(e){this.#Er.onBackForwardCacheNotUsed(e)}domContentEventFired({timestamp:e}){this.#Er.dispatchEventToListeners(_n.DOMContentLoaded,e)}loadEventFired({timestamp:e}){this.#Er.dispatchEventToListeners(_n.Load,{resourceTreeModel:this.#Er,loadTime:e})}lifecycleEvent({frameId:e,name:t}){this.#Er.dispatchEventToListeners(_n.LifecycleEvent,{frameId:e,name:t})}frameAttached({frameId:e,parentFrameId:t,stack:n}){this.#Er.frameAttached(e,t,n)}frameNavigated({frame:e,type:t}){this.#Er.frameNavigated(e,t)}documentOpened({frame:e}){this.#Er.documentOpened(e)}frameDetached({frameId:e,reason:t}){this.#Er.frameDetached(e,"swap"===t)}frameStartedLoading({}){}frameStoppedLoading({}){}frameRequestedNavigation({}){}frameScheduledNavigation({}){}frameClearedScheduledNavigation({}){}navigatedWithinDocument({}){}frameResized(){this.#Er.dispatchEventToListeners(_n.FrameResized)}javascriptDialogOpening(e){this.#Er.dispatchEventToListeners(_n.JavaScriptDialogOpening,e),e.hasBrowserHandler||this.#Er.agent.invoke_handleJavaScriptDialog({accept:!1})}javascriptDialogClosed({}){}screencastFrame({}){}screencastVisibilityChanged({}){}interstitialShown(){this.#Er.isInterstitialShowing=!0,this.#Er.dispatchEventToListeners(_n.InterstitialShown)}interstitialHidden(){this.#Er.isInterstitialShowing=!1,this.#Er.dispatchEventToListeners(_n.InterstitialHidden)}windowOpen({}){}compilationCacheProduced({}){}fileChooserOpened({}){}downloadWillBegin({}){}downloadProgress(){}}class Gn{#Er;constructor(e){this.#Er=e}ruleSetUpdated(e){}ruleSetRemoved(e){}prerenderAttemptCompleted(e){this.#Er.onPrerenderAttemptCompleted(e)}prefetchStatusUpdated(e){}prerenderStatusUpdated(e){}preloadEnabledStateUpdated(e){}preloadingAttemptSourcesUpdated(){}}c.register(jn,{capabilities:z.DOM,autostart:!0,early:!0});var Kn=Object.freeze({__proto__:null,ResourceTreeModel:jn,get Events(){return _n},ResourceTreeFrame:Wn,PageDispatcher:Vn});const $n={scriptRemovedOrDeleted:"Script removed or deleted.",unableToFetchScriptSource:"Unable to fetch script source."},Qn=s.i18n.registerUIStrings("core/sdk/Script.ts",$n),Xn=s.i18n.getLocalizedString.bind(void 0,Qn);let Jn=null;class Yn{debuggerModel;scriptId;sourceURL;lineOffset;columnOffset;endLine;endColumn;executionContextId;hash;#Oi;#Ni;sourceMapURL;debugSymbols;hasSourceURL;contentLength;originStackTrace;#Fi;#Bi;#Di;#Ui;isModule;constructor(e,t,n,r,s,i,a,o,l,d,c,h,u,g,p,m,f,b,y,v){this.debuggerModel=e,this.scriptId=t,this.sourceURL=n,this.lineOffset=r,this.columnOffset=s,this.endLine=i,this.endColumn=a,this.isModule=p,this.executionContextId=o,this.hash=l,this.#Oi=d,this.#Ni=c,this.sourceMapURL=h,this.debugSymbols=y,this.hasSourceURL=u,this.contentLength=g,this.originStackTrace=m,this.#Fi=f,this.#Bi=b,this.#Di=null,this.#Ui=v}embedderName(){return this.#Ui}target(){return this.debuggerModel.target()}static trimSourceURLComment(e){let t=e.lastIndexOf("//# sourceURL=");if(-1===t&&(t=e.lastIndexOf("//@ sourceURL="),-1===t))return e;const n=e.lastIndexOf("\n",t);if(-1===n)return e;return e.substr(n+1).match(er)?e.substr(0,n):e}isContentScript(){return this.#Oi}codeOffset(){return this.#Fi}isJavaScript(){return"JavaScript"===this.#Bi}isWasm(){return"WebAssembly"===this.#Bi}scriptLanguage(){return this.#Bi}executionContext(){return this.debuggerModel.runtimeModel().executionContext(this.executionContextId)}isLiveEdit(){return this.#Ni}contentURL(){return this.sourceURL}contentType(){return e.ResourceType.resourceTypes.Script}async loadTextContent(){const e=await this.debuggerModel.target().debuggerAgent().invoke_getScriptSource({scriptId:this.scriptId});if(e.getError())throw new Error(e.getError());const{scriptSource:t,bytecode:n}=e;if(n)return{content:n,isEncoded:!0};let r=t||"";return this.hasSourceURL&&this.sourceURL.startsWith("snippet://")&&(r=Yn.trimSourceURLComment(r)),{content:r,isEncoded:!1}}async loadWasmContent(){if(!this.isWasm())throw new Error("Not a wasm script");const t=await this.debuggerModel.target().debuggerAgent().invoke_disassembleWasmModule({scriptId:this.scriptId});if(t.getError())return this.loadTextContent();const{streamId:n,functionBodyOffsets:r,chunk:{lines:s,bytecodeOffsets:i}}=t,a=[],o=[];let l=s.reduce(((e,t)=>e+t.length+1),0);const d="",c=1e9-d.length;if(n)for(;;){const e=await this.debuggerModel.target().debuggerAgent().invoke_nextWasmDisassemblyChunk({streamId:n});if(e.getError())throw new Error(e.getError());const{chunk:{lines:t,bytecodeOffsets:r}}=e;if(l+=t.reduce(((e,t)=>e+t.length+1),0),0===t.length)break;if(l>=c){a.push([d]),o.push([0]);break}a.push(t),o.push(r)}const h=[];for(let e=0;ee){Jn||(Jn={cache:new Map,registry:new FinalizationRegistry((e=>Jn?.cache.delete(e)))});const e=[this.#Bi,this.contentLength,this.lineOffset,this.columnOffset,this.endLine,this.endColumn,this.#Fi,this.hash].join(":"),t=Jn.cache.get(e)?.deref();t?this.#Di=t:(this.#Di=this.requestContentInternal(),Jn.cache.set(e,new WeakRef(this.#Di)),Jn.registry.register(this.#Di,e))}else this.#Di=this.requestContentInternal()}return this.#Di}async requestContentInternal(){if(!this.scriptId)return{content:null,error:Xn($n.scriptRemovedOrDeleted),isEncoded:!1};try{return this.isWasm()?await this.loadWasmContent():await this.loadTextContent()}catch(e){return{content:null,error:Xn($n.unableToFetchScriptSource),isEncoded:!1}}}async getWasmBytecode(){const e=await this.debuggerModel.target().debuggerAgent().invoke_getWasmBytecode({scriptId:this.scriptId});return(await fetch(`data:application/wasm;base64,${e.bytecode}`)).arrayBuffer()}originalContentProvider(){return new r.StaticContentProvider.StaticContentProvider(this.contentURL(),this.contentType(),(()=>this.requestContent()))}async searchInContent(e,t,n){if(!this.scriptId)return[];return((await this.debuggerModel.target().debuggerAgent().invoke_searchInContent({scriptId:this.scriptId,query:e,caseSensitive:t,isRegex:n})).result||[]).map((e=>new r.ContentProvider.SearchMatch(e.lineNumber,e.lineContent)))}appendSourceURLCommentIfNeeded(e){return this.hasSourceURL?e+"\n //# sourceURL="+this.sourceURL:e}async editSource(e){e=Yn.trimSourceURLComment(e),e=this.appendSourceURLCommentIfNeeded(e);const{content:t}=await this.requestContent();if(t===e)return{changed:!1,status:"Ok"};const n=await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({scriptId:this.scriptId,scriptSource:e,allowTopFrameEditing:!0});if(n.getError())throw new Error(`Script#editSource failed for script with id ${this.scriptId}: ${n.getError()}`);return n.getError()||"Ok"!==n.status||(this.#Di=Promise.resolve({content:e,isEncoded:!1})),this.debuggerModel.dispatchEventToListeners(cr.ScriptSourceWasEdited,{script:this,status:n.status}),{changed:!0,status:n.status,exceptionDetails:n.exceptionDetails}}rawLocation(e,t){return this.containsLocation(e,t)?new ur(this.debuggerModel,this.scriptId,e,t):null}isInlineScript(){const e=!this.lineOffset&&!this.columnOffset;return!this.isWasm()&&Boolean(this.sourceURL)&&!e}isAnonymousScript(){return!this.sourceURL}async setBlackboxedRanges(e){return!(await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({scriptId:this.scriptId,positions:e})).getError()}containsLocation(e,t){const n=e===this.lineOffset&&t>=this.columnOffset||e>this.lineOffset,r=e=0:!(r>0)||t(e.start,n.end)<=0}if(0===e.length)return[];e.sort(((e,n)=>e.scriptIdn.scriptId?1:t(e.start,n.start)||t(e.end,n.end)));let r=e[0];const s=[];for(let i=1;ithis.#Hi.setEnabled(e.data)));const n=t.model(jn);n&&n.addEventListener(_n.FrameNavigated,this.onFrameNavigated,this)}sourceMapManager(){return this.#Hi}runtimeModel(){return this.runtimeModelInternal}debuggerEnabled(){return Boolean(this.#Vi)}debuggerId(){return this.#Gi}async enableDebugger(){if(this.#Vi)return;this.#Vi=!0;const t=o.Runtime.Runtime.queryParam("remoteFrontend")||o.Runtime.Runtime.queryParam("ws")?1e7:1e8,n=this.agent.invoke_enable({maxScriptsCacheSize:t});let r;o.Runtime.experiments.isEnabled(o.Runtime.ExperimentName.INSTRUMENTATION_BREAKPOINTS)&&(r=this.agent.invoke_setInstrumentationBreakpoint({instrumentation:"beforeScriptExecution"})),this.pauseOnExceptionStateChanged(),this.asyncStackTracesStateChanged(),e.Settings.Settings.instance().moduleSetting("breakpointsActive").get()||this.breakpointsActiveChanged(),this.dispatchEventToListeners(cr.DebuggerWasEnabled,this);const[s]=await Promise.all([n,r]);this.registerDebugger(s)}async syncDebuggerId(){const e=o.Runtime.Runtime.queryParam("remoteFrontend")||o.Runtime.Runtime.queryParam("ws")?1e7:1e8,t=this.agent.invoke_enable({maxScriptsCacheSize:e});return t.then(this.registerDebugger.bind(this)),t}onFrameNavigated(){or.shouldResyncDebuggerId||(or.shouldResyncDebuggerId=!0)}registerDebugger(e){if(e.getError())return;const{debuggerId:t}=e;lr.set(t,this),this.#Gi=t,this.dispatchEventToListeners(cr.DebuggerIsReadyToPause,this)}isReadyToPause(){return Boolean(this.#Gi)}static async modelForDebuggerId(e){return or.shouldResyncDebuggerId&&(await or.resyncDebuggerIdForModels(),or.shouldResyncDebuggerId=!1),lr.get(e)||null}static async resyncDebuggerIdForModels(){const e=lr.values();for(const t of e)t.debuggerEnabled()&&await t.syncDebuggerId()}async disableDebugger(){this.#Vi&&(this.#Vi=!1,await this.asyncStackTracesStateChanged(),await this.agent.invoke_disable(),this.#ea=!1,this.globalObjectCleared(),this.dispatchEventToListeners(cr.DebuggerWasDisabled,this),"string"==typeof this.#Gi&&lr.delete(this.#Gi),this.#Gi=null)}skipAllPauses(e){this.#Ki&&(clearTimeout(this.#Ki),this.#Ki=0),this.agent.invoke_setSkipAllPauses({skip:e})}skipAllPausesUntilReloadOrTimeout(e){this.#Ki&&clearTimeout(this.#Ki),this.agent.invoke_setSkipAllPauses({skip:!0}),this.#Ki=window.setTimeout(this.skipAllPauses.bind(this,!1),e)}pauseOnExceptionStateChanged(){const t=e.Settings.Settings.instance().moduleSetting("pauseOnCaughtException").get();let n;const r=e.Settings.Settings.instance().moduleSetting("pauseOnUncaughtException").get();n=t&&r?"all":t?"caught":r?"uncaught":"none",this.agent.invoke_setPauseOnExceptions({state:n})}asyncStackTracesStateChanged(){const t=!e.Settings.Settings.instance().moduleSetting("disableAsyncStackTraces").get()&&this.#Vi?32:0;return this.agent.invoke_setAsyncCallStackDepth({maxDepth:t})}breakpointsActiveChanged(){this.agent.invoke_setBreakpointsActive({active:e.Settings.Settings.instance().moduleSetting("breakpointsActive").get()})}setComputeAutoStepRangesCallback(e){this.#Qi=e}async computeAutoStepSkipList(e){let t=[];if(this.#Qi&&this.#qi&&this.#qi.callFrames.length>0){const[n]=this.#qi.callFrames;t=await this.#Qi.call(null,e,n)}return ir(t.map((({start:e,end:t})=>({scriptId:e.scriptId,start:{lineNumber:e.lineNumber,columnNumber:e.columnNumber},end:{lineNumber:t.lineNumber,columnNumber:t.columnNumber}}))))}async stepInto(){const e=await this.computeAutoStepSkipList(ar.StepInto);this.agent.invoke_stepInto({breakOnAsyncCall:!1,skipList:e})}async stepOver(){this.#Zi=this.#qi?.callFrames[0]?.functionLocation()??null;const e=await this.computeAutoStepSkipList(ar.StepOver);this.agent.invoke_stepOver({skipList:e})}async stepOut(){const e=await this.computeAutoStepSkipList(ar.StepOut);0!==e.length?this.agent.invoke_stepOver({skipList:e}):this.agent.invoke_stepOut()}scheduleStepIntoAsync(){this.computeAutoStepSkipList(ar.StepInto).then((e=>{this.agent.invoke_stepInto({breakOnAsyncCall:!0,skipList:e})}))}resume(){this.agent.invoke_resume({terminateOnResume:!1}),this.#ea=!1}pause(){this.#ea=!0,this.skipAllPauses(!1),this.agent.invoke_pause()}async setBreakpointByURL(n,r,s,a){let o;if(this.target().type()===_.Node&&n.startsWith("file://")){const r=e.ParsedURL.ParsedURL.urlToRawPathString(n,i.Platform.isWin());o=`${t.StringUtilities.escapeForRegExp(r)}|${t.StringUtilities.escapeForRegExp(n)}`,i.Platform.isWin()&&r.match(/^.:\\/)&&(o=`[${r[0].toUpperCase()}${r[0].toLowerCase()}]`+o.substr(1))}let l=0;const d=this.#zi.get(n)||[];for(let e=0,t=d.length;eur.fromPayload(this,e)))),{locations:h,breakpointId:c.breakpointId}}async setBreakpointInAnonymousScript(e,t,n,r){const s=await this.agent.invoke_setBreakpointByUrl({lineNumber:t,scriptHash:e,columnNumber:n,condition:r});if(s.getError())return{locations:[],breakpointId:null};let i=[];return s.locations&&(i=s.locations.map((e=>ur.fromPayload(this,e)))),{locations:i,breakpointId:s.breakpointId}}async removeBreakpoint(e){await this.agent.invoke_removeBreakpoint({breakpointId:e})}async getPossibleBreakpoints(e,t,n){const r=await this.agent.invoke_getPossibleBreakpoints({start:e.payload(),end:t?t.payload():void 0,restrictToFunction:n});return r.getError()||!r.locations?[]:r.locations.map((e=>gr.fromPayload(this,e)))}async fetchAsyncStackTrace(e){const t=await this.agent.invoke_getStackTrace({stackTraceId:e});return t.getError()?null:t.stackTrace}breakpointResolved(e,t){this.#Yi.dispatchEventToListeners(e,ur.fromPayload(this,t))}globalObjectCleared(){this.resetDebuggerPausedDetails(),this.reset(),this.dispatchEventToListeners(cr.GlobalObjectCleared,this)}reset(){for(const e of this.#_i.values())this.#Hi.detachSourceMap(e);this.#_i.clear(),this.#zi.clear(),this.#ji=[],this.#Zi=null}scripts(){return Array.from(this.#_i.values())}scriptForId(e){return this.#_i.get(e)||null}scriptsForSourceURL(e){return this.#zi.get(e)||[]}scriptsForExecutionContext(e){const t=[];for(const n of this.#_i.values())n.executionContextId===e.id&&t.push(n);return t}get callFrames(){return this.#qi?this.#qi.callFrames:null}debuggerPausedDetails(){return this.#qi}async setDebuggerPausedDetails(e){return this.#ea=!1,this.#qi=e,!(this.#$i&&!await this.#$i.call(null,e,this.#Zi))&&(this.#Zi=null,this.dispatchEventToListeners(cr.DebuggerPaused,this),this.setSelectedCallFrame(e.callFrames[0]),!0)}resetDebuggerPausedDetails(){this.#ea=!1,this.#qi=null,this.setSelectedCallFrame(null)}setBeforePausedCallback(e){this.#$i=e}setExpandCallFramesCallback(e){this.#Xi=e}setEvaluateOnCallFrameCallback(e){this.evaluateOnCallFrameCallback=e}setSynchronizeBreakpointsCallback(e){this.#Ji=e}async pausedScript(t,n,r,s,i,a){if("instrumentation"===n){const e=this.scriptForId(r.scriptId);return this.#Ji&&e&&await this.#Ji(e),void this.resume()}const o=new fr(this,t,n,r,s,i,a);if(this.#Xi&&(o.callFrames=await this.#Xi.call(null,o.callFrames)),this.continueToLocationCallback){const e=this.continueToLocationCallback;if(this.continueToLocationCallback=null,e(o))return}await this.setDebuggerPausedDetails(o)?e.EventTarget.fireEvent("DevTools.DebuggerPaused"):this.#Zi?this.stepOver():this.stepInto()}resumedScript(){this.resetDebuggerPausedDetails(),this.dispatchEventToListeners(cr.DebuggerResumed,this)}parsedScriptSource(e,t,n,r,s,a,o,l,d,c,h,u,g,p,m,f,b,y,v,I){const k=this.#_i.get(e);if(k)return k;let S=!1;d&&"isDefault"in d&&(S=!d.isDefault);const w=new Yn(this,e,t,n,r,s,a,o,l,S,c,h,u,p,m,f,b,y,v,I);this.registerScript(w),this.dispatchEventToListeners(cr.ParsedScriptSource,w),w.isInlineScript()&&!w.hasSourceURL&&(w.isModule?i.userMetrics.inlineScriptParsed(0):i.userMetrics.inlineScriptParsed(1)),w.sourceMapURL&&!g&&this.#Hi.attachSourceMap(w,w.sourceURL,w.sourceMapURL);return g&&w.isAnonymousScript()&&(this.#ji.push(w),this.collectDiscardedScripts()),w}setSourceMapURL(e,t){this.#Hi.detachSourceMap(e),e.sourceMapURL=t,this.#Hi.attachSourceMap(e,e.sourceURL,e.sourceMapURL)}async setDebugInfoURL(e,t){this.#Xi&&this.#qi&&(this.#qi.callFrames=await this.#Xi.call(null,this.#qi.callFrames)),this.dispatchEventToListeners(cr.DebugInfoAttached,e)}executionContextDestroyed(e){for(const t of this.#_i.values())t.executionContextId===e.id&&this.#Hi.detachSourceMap(t)}registerScript(e){if(this.#_i.set(e.scriptId,e),e.isAnonymousScript())return;let t=this.#zi.get(e.sourceURL);t||(t=[],this.#zi.set(e.sourceURL,t)),t.unshift(e)}unregisterScript(e){console.assert(e.isAnonymousScript()),this.#_i.delete(e.scriptId)}collectDiscardedScripts(){if(this.#ji.length<1e3)return;const e=this.#ji.splice(0,100);for(const t of e)this.unregisterScript(t),this.dispatchEventToListeners(cr.DiscardedAnonymousScriptSource,t)}createRawLocation(e,t,n,r){return this.createRawLocationByScriptId(e.scriptId,t,n,r)}createRawLocationByURL(e,t,n,r){for(const s of this.#zi.get(e)||[])if(!(s.lineOffset>t||s.lineOffset===t&&void 0!==n&&s.columnOffset>n||s.endLinenull===this.#Ta.axNodeForId(e)))}hasUnloadedChildren(){return!(!this.#Na||!this.#Na.length)&&this.#Na.some((e=>null===this.#Ta.axNodeForId(e)))}getFrameId(){return this.#Oa||this.parentNode()?.getFrameId()||null}}(Lr||(Lr={})).TreeUpdated="TreeUpdated";class Or extends c{agent;#Fa;#Ba;#Da;#Ua;#Ha;constructor(e){super(e),e.registerAccessibilityDispatcher(this),this.agent=e.accessibilityAgent(),this.resumeModel(),this.#Fa=new Map,this.#Ba=new Map,this.#Da=new Map,this.#Ua=new Map,this.#Ha=null}clear(){this.#Ha=null,this.#Fa.clear(),this.#Ba.clear(),this.#Da.clear()}async resumeModel(){await this.agent.invoke_enable()}async suspendModel(){await this.agent.invoke_disable()}async requestPartialAXTree(e){const{nodes:t}=await this.agent.invoke_getPartialAXTree({nodeId:e.id,fetchRelatives:!0});if(!t)return;const n=[];for(const e of t)n.push(new Ar(this,e))}loadComplete({root:e}){this.clear(),this.#Ha=new Ar(this,e),this.dispatchEventToListeners(Lr.TreeUpdated,{root:this.#Ha})}nodesUpdated({nodes:e}){this.createNodesFromPayload(e),this.dispatchEventToListeners(Lr.TreeUpdated,{})}createNodesFromPayload(e){return e.map((e=>new Ar(this,e)))}async requestRootNode(e){if(e&&this.#Da.has(e))return this.#Da.get(e);if(!e&&this.#Ha)return this.#Ha;const{node:t}=await this.agent.invoke_getRootAXNode({frameId:e});return t?this.createNodesFromPayload([t])[0]:void 0}async requestAXChildren(e,t){const n=this.#Fa.get(e);if(!n)throw Error("Cannot request children before parent");if(!n.hasUnloadedChildren())return n.children();const r=this.#Ua.get(e);if(r)await r;else{const n=this.agent.invoke_getChildAXNodes({id:e,frameId:t});this.#Ua.set(e,n);const r=await n;r.getError()||(this.createNodesFromPayload(r.nodes),this.#Ua.delete(e))}return n.children()}async requestAndLoadSubTreeToNode(e){const t=[];let n=this.axNodeForDOMNode(e);for(;n;){t.push(n);const e=n.parentNode();if(!e)return t;n=e}const{nodes:r}=await this.agent.invoke_getAXNodeAndAncestors({backendNodeId:e.backendNodeId()});if(!r)return null;return this.createNodesFromPayload(r)}axNodeForId(e){return this.#Fa.get(e)||null}setRootAXNodeForFrameId(e,t){this.#Da.set(e,t)}axNodeForFrameId(e){return this.#Da.get(e)??null}setAXNodeForAXId(e,t){this.#Fa.set(e,t)}axNodeForDOMNode(e){return e?this.#Ba.get(e.backendNodeId())??null:null}setAXNodeForBackendDOMNodeId(e,t){this.#Ba.set(e,t)}getAgent(){return this.agent}}c.register(Or,{capabilities:z.DOM,autostart:!1});var Nr=Object.freeze({__proto__:null,get CoreAxPropertyName(){return Pr},AccessibilityNode:Ar,get Events(){return Lr},AccessibilityModel:Or});class Fr{#qa;titleInternal;enabledInternal;constructor(e,t){this.#qa=e,this.titleInternal=t,this.enabledInternal=!1}category(){return this.#qa}enabled(){return this.enabledInternal}setEnabled(e){this.enabledInternal=e}title(){return this.titleInternal}setTitle(e){this.titleInternal=e}}var Br=Object.freeze({__proto__:null,CategorizedBreakpoint:Fr});class Dr{onMessage;#_a;#za;#ja;#ar;constructor(){this.onMessage=null,this.#_a=null,this.#za="",this.#ja=0,this.#ar=[i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.DispatchMessage,this.dispatchMessage,this),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.DispatchMessageChunk,this.dispatchMessageChunk,this)]}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}sendRawMessage(e){this.onMessage&&i.InspectorFrontendHost.InspectorFrontendHostInstance.sendMessageToBackend(e)}dispatchMessage(e){this.onMessage&&this.onMessage.call(null,e.data)}dispatchMessageChunk(e){const{messageChunk:t,messageSize:n}=e.data;n&&(this.#za="",this.#ja=n),this.#za+=t,this.#za.length===this.#ja&&this.onMessage&&(this.onMessage.call(null,this.#za),this.#za="",this.#ja=0)}async disconnect(){const t=this.#_a;e.EventTarget.removeEventListeners(this.#ar),this.#_a=null,this.onMessage=null,t&&t.call(null,"force disconnect")}}class Ur{#Wa;onMessage;#_a;#Va;#Ga;#Ka;constructor(e,t){this.#Wa=new WebSocket(e),this.#Wa.onerror=this.onError.bind(this),this.#Wa.onopen=this.onOpen.bind(this),this.#Wa.onmessage=e=>{this.onMessage&&this.onMessage.call(null,e.data)},this.#Wa.onclose=this.onClose.bind(this),this.onMessage=null,this.#_a=null,this.#Va=t,this.#Ga=!1,this.#Ka=[]}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}onError(){this.#Va&&this.#Va.call(null),this.#_a&&this.#_a.call(null,"connection failed"),this.close()}onOpen(){if(this.#Ga=!0,this.#Wa){this.#Wa.onerror=console.error;for(const e of this.#Ka)this.#Wa.send(e)}this.#Ka=[]}onClose(){this.#Va&&this.#Va.call(null),this.#_a&&this.#_a.call(null,"websocket closed"),this.close()}close(e){this.#Wa&&(this.#Wa.onerror=null,this.#Wa.onopen=null,this.#Wa.onclose=e||null,this.#Wa.onmessage=null,this.#Wa.close(),this.#Wa=null),this.#Va=null}sendRawMessage(e){this.#Ga&&this.#Wa?this.#Wa.send(e):this.#Ka.push(e)}disconnect(){return new Promise((e=>{this.close((()=>{this.#_a&&this.#_a.call(null,"force disconnect"),e()}))}))}}class Hr{onMessage;#_a;constructor(){this.onMessage=null,this.#_a=null}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}sendRawMessage(e){window.setTimeout(this.respondWithError.bind(this,e),0)}respondWithError(e){const t=JSON.parse(e),n={message:"This is a stub connection, can't dispatch message.",code:a.InspectorBackend.DevToolsStubErrorCode,data:t};this.onMessage&&this.onMessage.call(null,{id:t.id,error:n})}async disconnect(){this.#_a&&this.#_a.call(null,"force disconnect"),this.#_a=null,this.onMessage=null}}class qr{#$a;#Qa;onMessage;#_a;constructor(e,t){this.#$a=e,this.#Qa=t,this.onMessage=null,this.#_a=null}setOnMessage(e){this.onMessage=e}setOnDisconnect(e){this.#_a=e}getOnDisconnect(){return this.#_a}sendRawMessage(e){const t=JSON.parse(e);t.sessionId||(t.sessionId=this.#Qa),this.#$a.sendRawMessage(JSON.stringify(t))}getSessionId(){return this.#Qa}async disconnect(){this.#_a&&this.#_a.call(null,"force disconnect"),this.#_a=null,this.onMessage=null}}function _r(e){const t=o.Runtime.Runtime.queryParam("ws"),n=o.Runtime.Runtime.queryParam("wss");if(t||n){const r=t?"ws":"wss";let s=t||n;i.InspectorFrontendHost.InspectorFrontendHostInstance.isHostedMode()&&s.startsWith("/")&&(s=`${window.location.host}${s}`);return new Ur(`${r}://${s}`,e)}return i.InspectorFrontendHost.InspectorFrontendHostInstance.isHostedMode()?new Hr:new Dr}var zr,jr=Object.freeze({__proto__:null,MainConnection:Dr,WebSocketConnection:Ur,StubConnection:Hr,ParallelConnection:qr,initMainConnection:async function(e,t){a.InspectorBackend.Connection.setFactory(_r.bind(null,t)),await e(),i.InspectorFrontendHost.InspectorFrontendHostInstance.connectionReady(),i.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(i.InspectorFrontendHostAPI.Events.ReattachRootTarget,(()=>{const t=K.instance().rootTarget();if(t){const e=t.router();e&&e.connection().disconnect()}e()}))}});class Wr extends c{#Xa;#Ja;#Ya;#Za=new Map;#eo=new Map;#to=new Map;#no=new Map;#ro=null;constructor(e){super(e),this.#Xa=e.targetManager(),this.#Ja=e,this.#Ya=e.targetAgent(),e.registerTargetDispatcher(this);const t=this.#Xa.browserTarget();t?t!==e&&t.targetAgent().invoke_autoAttachRelated({targetId:e.id(),waitForDebuggerOnStart:!0}):this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),e.parentTarget()?.type()===_.Frame||i.InspectorFrontendHost.isUnderTest()||(this.#Ya.invoke_setDiscoverTargets({discover:!0}),this.#Ya.invoke_setRemoteLocations({locations:[{host:"localhost",port:9229}]}))}static install(e){Wr.attachCallback=e,c.register(Wr,{capabilities:z.Target,autostart:!0})}childTargets(){return Array.from(this.#eo.values())}async suspendModel(){await this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0})}async resumeModel(){await this.#Ya.invoke_setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0})}dispose(){for(const e of this.#eo.keys())this.detachedFromTarget({sessionId:e,targetId:void 0})}targetCreated({targetInfo:e}){this.#Za.set(e.targetId,e),this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetCreated,e)}targetInfoChanged({targetInfo:e}){this.#Za.set(e.targetId,e);const t=this.#to.get(e.targetId);if(t)if("prerender"!==t.targetInfo()?.subtype||e.subtype)t.updateTargetInfo(e);else{const n=t.model(jn);t.updateTargetInfo(e),n&&n.mainFrame&&n.primaryPageChanged(n.mainFrame,"Activation")}this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetInfoChanged,e)}targetDestroyed({targetId:e}){this.#Za.delete(e),this.fireAvailableTargetsChanged(),this.dispatchEventToListeners(zr.TargetDestroyed,e)}targetCrashed({targetId:e,status:t,errorCode:n}){}fireAvailableTargetsChanged(){K.instance().dispatchEventToListeners($.AvailableTargetsChanged,[...this.#Za.values()])}async getParentTargetId(){return this.#ro||(this.#ro=(await this.#Ja.targetAgent().invoke_getTargetInfo({})).targetInfo.targetId),this.#ro}async attachedToTarget({sessionId:t,targetInfo:n,waitingForDebugger:r}){if(this.#ro===n.targetId)return;let s=_.Browser,i="";if("worker"===n.type&&n.title&&n.title!==n.url)i=n.title;else if(!["page","iframe","webview"].includes(n.type))if("chrome://print/"===n.url||n.url.startsWith("chrome://")&&n.url.endsWith(".top-chrome/"))s=_.Frame;else{const t=e.ParsedURL.ParsedURL.fromString(n.url);i=t?t.lastPathComponentWithFragment():"#"+ ++Wr.lastAnonymousTargetId,"devtools"===t?.scheme&&"other"===n.type&&(s=_.Frame)}"iframe"===n.type||"webview"===n.type||"background_page"===n.type||"app"===n.type||"popup_page"===n.type||"page"===n.type?s=_.Frame:"worker"===n.type?s=_.Worker:"shared_worker"===n.type?s=_.SharedWorker:"service_worker"===n.type?s=_.ServiceWorker:"auction_worklet"===n.type&&(s=_.AuctionWorklet);const a=this.#Xa.createTarget(n.targetId,i,s,this.#Ja,t,void 0,void 0,n);this.#eo.set(t,a),this.#to.set(a.id(),a),Wr.attachCallback&&await Wr.attachCallback({target:a,waitingForDebugger:r}),r&&a.runtimeAgent().invoke_runIfWaitingForDebugger()}detachedFromTarget({sessionId:e}){if(this.#no.has(e))this.#no.delete(e);else{const t=this.#eo.get(e);t&&(t.dispose("target terminated"),this.#eo.delete(e),this.#to.delete(t.id()))}}receivedMessageFromTarget({}){}async createParallelConnection(e){const t=await this.getParentTargetId(),{connection:n,sessionId:r}=await this.createParallelConnectionAndSessionForTarget(this.#Ja,t);return n.setOnMessage(e),this.#no.set(r,n),{connection:n,sessionId:r}}async createParallelConnectionAndSessionForTarget(e,t){const n=e.targetAgent(),r=e.router(),s=(await n.invoke_attachToTarget({targetId:t,flatten:!0})).sessionId,i=new qr(r.connection(),s);return r.registerSession(e,s,i),i.setOnDisconnect((()=>{r.unregisterSession(s),n.invoke_detachFromTarget({sessionId:s})})),{connection:i,sessionId:s}}targetInfos(){return Array.from(this.#Za.values())}static lastAnonymousTargetId=0;static attachCallback}!function(e){e.TargetCreated="TargetCreated",e.TargetDestroyed="TargetDestroyed",e.TargetInfoChanged="TargetInfoChanged"}(zr||(zr={}));var Vr=Object.freeze({__proto__:null,ChildTargetManager:Wr,get Events(){return zr}});const Gr={couldNotLoadContentForSS:"Could not load content for {PH1} ({PH2})"},Kr=s.i18n.registerUIStrings("core/sdk/CompilerSourceMappingContentProvider.ts",Gr),$r=s.i18n.getLocalizedString.bind(void 0,Kr);var Qr,Xr,Jr=Object.freeze({__proto__:null,CompilerSourceMappingContentProvider:class{#so;#io;#ao;constructor(e,t,n){this.#so=e,this.#io=t,this.#ao=n}contentURL(){return this.#so}contentType(){return this.#io}async requestContent(){try{const{content:e}=await Ht.instance().loadResource(this.#so,this.#ao);return{content:e,isEncoded:!1}}catch(e){const t=$r(Gr.couldNotLoadContentForSS,{PH1:this.#so,PH2:e.message});return console.error(t),{content:null,error:t,isEncoded:!1}}}async searchInContent(e,t,n){const{content:s}=await this.requestContent();return"string"!=typeof s?[]:r.TextUtils.performSearchInContent(s,e,t,n)}}});!function(e){e.Result="result",e.Command="command",e.System="system",e.QueryObjectResult="queryObjectResult"}(Qr||(Qr={})),function(e){e.CSS="css",e.ConsoleAPI="console-api"}(Xr||(Xr={}));const Yr={profileD:"Profile {PH1}"},Zr=s.i18n.registerUIStrings("core/sdk/CPUProfilerModel.ts",Yr),es=s.i18n.getLocalizedString.bind(void 0,Zr);class ts extends c{#oo;#lo;#do;#co;#ho;#uo;registeredConsoleProfileMessages=[];constructor(e){super(e),this.#oo=!1,this.#lo=1,this.#do=new Map,this.#co=e.profilerAgent(),this.#ho=null,e.registerProfilerDispatcher(this),this.#co.invoke_enable(),this.#uo=e.model(or)}runtimeModel(){return this.#uo.runtimeModel()}debuggerModel(){return this.#uo}consoleProfileStarted({id:e,location:t,title:n}){n||(n=es(Yr.profileD,{PH1:this.#lo++}),this.#do.set(e,n));const r=this.createEventDataFrom(e,t,n);this.dispatchEventToListeners(ns.ConsoleProfileStarted,r)}consoleProfileFinished({id:e,location:t,profile:n,title:r}){r||(r=this.#do.get(e),this.#do.delete(e));const s={...this.createEventDataFrom(e,t,r),cpuProfile:n};this.registeredConsoleProfileMessages.push(s),this.dispatchEventToListeners(ns.ConsoleProfileFinished,s)}createEventDataFrom(e,t,n){const r=ur.fromPayload(this.#uo,t);return{id:this.target().id()+"."+e,scriptLocation:r,title:n||"",cpuProfilerModel:this}}isRecordingProfile(){return this.#oo}startRecording(){this.#oo=!0;return this.#co.invoke_setSamplingInterval({interval:100}),this.#co.invoke_start()}stopRecording(){return this.#oo=!1,this.#co.invoke_stop().then((e=>e.profile||null))}startPreciseCoverage(e,t){this.#ho=t;return this.#co.invoke_startPreciseCoverage({callCount:!1,detailed:e,allowTriggeredUpdates:!0})}async takePreciseCoverage(){const e=await this.#co.invoke_takePreciseCoverage();return{timestamp:e&&e.timestamp||0,coverage:e&&e.result||[]}}stopPreciseCoverage(){return this.#ho=null,this.#co.invoke_stopPreciseCoverage()}preciseCoverageDeltaUpdate({timestamp:e,occasion:t,result:n}){this.#ho&&this.#ho(e,t,n)}}var ns;!function(e){e.ConsoleProfileStarted="ConsoleProfileStarted",e.ConsoleProfileFinished="ConsoleProfileFinished"}(ns||(ns={})),c.register(ts,{capabilities:z.JS,autostart:!0});var rs,ss=Object.freeze({__proto__:null,CPUProfilerModel:ts,get Events(){return ns}});class is extends c{#go;constructor(e){super(e),e.registerLogDispatcher(this),this.#go=e.logAgent(),this.#go.invoke_enable(),i.InspectorFrontendHost.isUnderTest()||this.#go.invoke_startViolationsReport({config:[{name:"longTask",threshold:200},{name:"longLayout",threshold:30},{name:"blockedEvent",threshold:100},{name:"blockedParser",threshold:-1},{name:"handler",threshold:150},{name:"recurringHandler",threshold:50},{name:"discouragedAPIUse",threshold:-1}]})}entryAdded({entry:e}){this.dispatchEventToListeners(rs.EntryAdded,{logModel:this,entry:e})}requestClear(){this.#go.invoke_clear()}}(rs||(rs={})).EntryAdded="EntryAdded",c.register(is,{capabilities:z.Log,autostart:!0});var as=Object.freeze({__proto__:null,LogModel:is,get Events(){return rs}});const os={navigatedToS:"Navigated to {PH1}",bfcacheNavigation:"Navigation to {PH1} was restored from back/forward cache (see https://web.dev/bfcache/)",profileSStarted:"Profile ''{PH1}'' started.",profileSFinished:"Profile ''{PH1}'' finished.",failedToSaveToTempVariable:"Failed to save to temp variable."},ls=s.i18n.registerUIStrings("core/sdk/ConsoleModel.ts",os),ds=s.i18n.getLocalizedString.bind(void 0,ls);class cs extends c{#po;#mo;#fo;#bo;#yo;#vo;#Io;#ko;constructor(n){super(n),this.#po=[],this.#mo=new t.MapUtilities.Multimap,this.#fo=new Map,this.#bo=0,this.#yo=0,this.#vo=0,this.#Io=0,this.#ko=new WeakMap;const r=n.model(jn);if(!r||r.cachedResourcesLoaded())return void this.initTarget(n);const s=r.addEventListener(_n.CachedResourcesLoaded,(()=>{e.EventTarget.removeEventListeners([s]),this.initTarget(n)}))}initTarget(e){const t=[],n=e.model(ts);n&&(t.push(n.addEventListener(ns.ConsoleProfileStarted,this.consoleProfileStarted.bind(this,n))),t.push(n.addEventListener(ns.ConsoleProfileFinished,this.consoleProfileFinished.bind(this,n))));const r=e.model(jn);r&&e.parentTarget()?.type()!==_.Frame&&t.push(r.addEventListener(_n.PrimaryPageChanged,this.primaryPageChanged,this));const s=e.model(Cr);s&&(t.push(s.addEventListener(Rr.ExceptionThrown,this.exceptionThrown.bind(this,s))),t.push(s.addEventListener(Rr.ExceptionRevoked,this.exceptionRevoked.bind(this,s))),t.push(s.addEventListener(Rr.ConsoleAPICalled,this.consoleAPICalled.bind(this,s))),e.parentTarget()?.type()!==_.Frame&&t.push(s.debuggerModel().addEventListener(cr.GlobalObjectCleared,this.clearIfNecessary,this)),t.push(s.addEventListener(Rr.QueryObjectRequested,this.queryObjectRequested.bind(this,s)))),this.#ko.set(e,t)}targetRemoved(t){const n=t.model(Cr);n&&this.#fo.delete(n),e.EventTarget.removeEventListeners(this.#ko.get(t)||[])}async evaluateCommandInConsole(t,n,r,s){const a=await t.evaluate({expression:r,objectGroup:"console",includeCommandLineAPI:s,silent:!1,returnByValue:!1,generatePreview:!0,replMode:!0,allowUnsafeEvalBlockedByCSP:!1},e.Settings.Settings.instance().moduleSetting("consoleUserActivationEval").get(),!1);i.userMetrics.actionTaken(i.UserMetrics.Action.ConsoleEvaluated),"error"in a||(await e.Console.Console.instance().showPromise(),this.dispatchEventToListeners(hs.CommandEvaluated,{result:a.object,commandMessage:n,exceptionDetails:a.exceptionDetails}))}addCommandMessage(e,t){const n=new gs(e.runtimeModel,"javascript",null,t,{type:Qr.Command});return n.setExecutionContextId(e.id),this.addMessage(n),n}addMessage(e){e.setPageLoadSequenceNumber(this.#Io),e.source===Xr.ConsoleAPI&&"clear"===e.type&&this.clearIfNecessary(),this.#po.push(e),this.#mo.set(e.timestamp,e);const t=e.runtimeModel(),n=e.getExceptionId();if(n&&t){let r=this.#fo.get(t);r||(r=new Map,this.#fo.set(t,r)),r.set(n,e)}this.incrementErrorWarningCount(e),this.dispatchEventToListeners(hs.MessageAdded,e)}exceptionThrown(e,t){const n=t.data,r=function(e){if(!e)return;return{requestId:e.requestId||void 0,issueId:e.issueId||void 0}}(n.details.exceptionMetaData),s=gs.fromException(e,n.details,void 0,n.timestamp,void 0,r);s.setExceptionId(n.details.exceptionId),this.addMessage(s)}exceptionRevoked(e,t){const n=t.data,r=this.#fo.get(e),s=r?r.get(n):null;s&&(this.#yo--,s.level="verbose",this.dispatchEventToListeners(hs.MessageUpdated,s))}consoleAPICalled(e,t){const n=t.data;let r="info";"debug"===n.type?r="verbose":"error"===n.type||"assert"===n.type?r="error":"warning"===n.type?r="warning":"info"!==n.type&&"log"!==n.type||(r="info");let s="";n.args.length&&n.args[0].unserializableValue?s=n.args[0].unserializableValue:!n.args.length||"object"==typeof n.args[0].value&&null!==n.args[0].value?n.args.length&&n.args[0].description&&(s=n.args[0].description):s=String(n.args[0].value);const i=n.stackTrace&&n.stackTrace.callFrames.length?n.stackTrace.callFrames[0]:null,a={type:n.type,url:i?.url,line:i?.lineNumber,column:i?.columnNumber,parameters:n.args,stackTrace:n.stackTrace,timestamp:n.timestamp,executionContextId:n.executionContextId,context:n.context},o=new gs(e,Xr.ConsoleAPI,r,s,a);for(const e of this.#mo.get(o.timestamp).values())if(o.isEqual(e))return;this.addMessage(o)}queryObjectRequested(e,t){const{objects:n,executionContextId:r}=t.data,s={type:Qr.QueryObjectResult,parameters:[n],executionContextId:r},i=new gs(e,Xr.ConsoleAPI,"info","",s);this.addMessage(i)}clearIfNecessary(){e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()||this.clear(),++this.#Io}primaryPageChanged(t){if(e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()){const{frame:n}=t.data;n.backForwardCacheDetails.restoredFromCache?e.Console.Console.instance().log(ds(os.bfcacheNavigation,{PH1:n.url})):e.Console.Console.instance().log(ds(os.navigatedToS,{PH1:n.url}))}}consoleProfileStarted(e,t){const{data:n}=t;this.addConsoleProfileMessage(e,"profile",n.scriptLocation,ds(os.profileSStarted,{PH1:n.title}))}consoleProfileFinished(e,t){const{data:n}=t;this.addConsoleProfileMessage(e,"profileEnd",n.scriptLocation,ds(os.profileSFinished,{PH1:n.title}))}addConsoleProfileMessage(e,t,n,r){const s=n.script(),i=[{functionName:"",scriptId:n.scriptId,url:s?s.contentURL():"",lineNumber:n.lineNumber,columnNumber:n.columnNumber||0}];this.addMessage(new gs(e.runtimeModel(),Xr.ConsoleAPI,"info",r,{type:t,stackTrace:{callFrames:i}}))}incrementErrorWarningCount(e){if("violation"!==e.source)switch(e.level){case"warning":this.#bo++;break;case"error":this.#yo++}else this.#vo++}messages(){return this.#po}static allMessagesUnordered(){const e=[];for(const t of K.instance().targets()){const n=t.model(cs)?.messages()||[];e.push(...n)}return e}static requestClearMessages(){for(const e of K.instance().models(is))e.requestClear();for(const e of K.instance().models(Cr))e.discardConsoleEntries();for(const e of K.instance().targets())e.model(cs)?.clear()}clear(){this.#po=[],this.#mo.clear(),this.#fo.clear(),this.#yo=0,this.#bo=0,this.#vo=0,this.dispatchEventToListeners(hs.ConsoleCleared)}errors(){return this.#yo}static allErrors(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.errors()||0;return e}warnings(){return this.#bo}static allWarnings(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.warnings()||0;return e}violations(){return this.#vo}static allViolations(){let e=0;for(const t of K.instance().targets())e+=t.model(cs)?.violations()||0;return e}async saveToTempVariable(t,n){if(!n||!t)return void o(null);const r=t,s=await r.globalObject("",!1);if("error"in s||Boolean(s.exceptionDetails)||!s.object)return void o("object"in s&&s.object||null);const i=s.object,a=await i.callFunction((function(e){const t="temp";let n=1;for(;t+n in this;)++n;const r=t+n;return this[r]=e,r}),[Le.toCallArgument(n)]);if(i.release(),a.wasThrown||!a.object||"string"!==a.object.type)o(a.object||null);else{const e=a.object.value,t=this.addCommandMessage(r,e);this.evaluateCommandInConsole(r,t,e,!1)}function o(t){let n=ds(os.failedToSaveToTempVariable);t&&(n=n+" "+t.description),e.Console.Console.instance().error(n)}a.object&&a.object.release()}}var hs;function us(e,t){if(!e!=!t)return!1;if(!e||!t)return!0;const n=e.callFrames,r=t.callFrames;if(n.length!==r.length)return!1;for(let e=0,t=n.length;et.includes(e)));if(-1===n||n===e.length-1)return{callFrame:null,type:null};const r=e[n].url===br?"LOGPOINT":"CONDITIONAL_BREAKPOINT";return{callFrame:e[n+1],type:r}}}c.register(cs,{capabilities:z.JS,autostart:!0});const ps=new Map([["xml","xml"],["javascript","javascript"],["network","network"],[Xr.ConsoleAPI,"console-api"],["storage","storage"],["appcache","appcache"],["rendering","rendering"],[Xr.CSS,"css"],["security","security"],["deprecation","deprecation"],["worker","worker"],["violation","violation"],["intervention","intervention"],["recommendation","recommendation"],["other","other"]]);var ms=Object.freeze({__proto__:null,ConsoleModel:cs,get Events(){return hs},ConsoleMessage:gs,MessageSourceDisplayName:ps,get FrontendMessageSource(){return Xr},get FrontendMessageType(){return Qr}});class fs extends c{#Mo;#Po;constructor(e){super(e),this.#Mo=new Map,this.#Po=new Map}addBlockedCookie(e,t){const n=e.key(),r=this.#Mo.get(n);this.#Mo.set(n,e),t?this.#Po.set(e,t):this.#Po.delete(e),r&&this.#Po.delete(r)}getCookieToBlockedReasonsMap(){return this.#Po}async getCookies(e){const t=await this.target().networkAgent().invoke_getCookies({urls:e});if(t.getError())return[];return t.cookies.map(F.fromProtocolCookie).concat(Array.from(this.#Mo.values()))}async deleteCookie(e){await this.deleteCookies([e])}async clear(e,t){const n=await this.getCookiesForDomain(e||null);if(t){const e=n.filter((e=>e.matchesSecurityOrigin(t)));await this.deleteCookies(e)}else await this.deleteCookies(n)}async saveCookie(e){let t,n=e.domain();n.startsWith(".")||(n=""),e.expires()&&(t=Math.floor(Date.parse(`${e.expires()}`)/1e3));const r=o.Runtime.experiments.isEnabled("experimentalCookieFeatures"),s={name:e.name(),value:e.value(),url:e.url()||void 0,domain:n,path:e.path(),secure:e.secure(),httpOnly:e.httpOnly(),sameSite:e.sameSite(),expires:t,priority:e.priority(),partitionKey:e.partitionKey(),sourceScheme:r?e.sourceScheme():(i=e.sourceScheme(),"Unset"===i?i:void 0),sourcePort:r?e.sourcePort():void 0};var i;const a=await this.target().networkAgent().invoke_setCookie(s);return!(a.getError()||!a.success)&&a.success}getCookiesForDomain(t){const n=[];const r=this.target().model(jn);return r&&(r.mainFrame&&r.mainFrame.unreachableUrl()&&n.push(r.mainFrame.unreachableUrl()),r.forAllResources((function(r){const s=e.ParsedURL.ParsedURL.fromString(r.documentURL);return!s||t&&s.securityOrigin()!==t||n.push(r.url),!1}))),this.getCookies(n)}async deleteCookies(e){const t=this.target().networkAgent();this.#Mo.clear(),this.#Po.clear(),await Promise.all(e.map((e=>t.invoke_deleteCookies({name:e.name(),url:void 0,domain:e.domain(),path:e.path()}))))}}c.register(fs,{capabilities:z.Network,autostart:!1});var bs=Object.freeze({__proto__:null,CookieModel:fs});class ys extends A{id;self;positionTicks;deoptReason;constructor(e,t,n){super(e.callFrame||{functionName:e.functionName,scriptId:e.scriptId,url:e.url,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber-1},n),this.id=e.id,this.self=(e.hitCount||0)*t,this.positionTicks=e.positionTicks,this.deoptReason=e.deoptReason&&"no reason"!==e.deoptReason?e.deoptReason:null}}var vs=Object.freeze({__proto__:null,CPUProfileNode:ys,CPUProfileDataModel:class extends O{profileStartTime;profileEndTime;timestamps;samples;lines;totalHitCount;profileHead;#Lo;gcNode;programNode;idleNode;#Eo;#Ao;constructor(e,t){super(t);Boolean(e.head)?(this.profileStartTime=1e3*e.startTime,this.profileEndTime=1e3*e.endTime,this.timestamps=e.timestamps,this.compatibilityConversionHeadToNodes(e)):(this.profileStartTime=e.startTime/1e3,this.profileEndTime=e.endTime/1e3,this.timestamps=this.convertTimeDeltas(e)),this.samples=e.samples,this.lines=e.lines,this.totalHitCount=0,this.profileHead=this.translateProfileTree(e.nodes),this.initialize(this.profileHead),this.extractMetaNodes(),this.samples&&(this.sortSamples(),this.normalizeTimestamps(),this.fixMissingSamples())}compatibilityConversionHeadToNodes(e){if(!e.head||e.nodes)return;const t=[];!function e(n){return t.push(n),n.children=n.children.map(e),n.id}(e.head),e.nodes=t,delete e.head}convertTimeDeltas(e){if(!e.timeDeltas)return[];let t=e.startTime;const n=new Array(e.timeDeltas.length);for(let r=0;re+(t.hitCount||0)),0);const r=(this.profileEndTime-this.profileStartTime)/this.totalHitCount,s=Boolean(e.Settings.Settings.instance().moduleSetting("showNativeFunctionsInJSProfile").get()),i=t[0],a=new Map([[i.id,i.id]]);this.#Lo=new Map;const o=new ys(i,r,this.target());if(this.#Lo.set(i.id,o),!i.children)throw new Error("Missing children for root");const l=i.children.map((()=>o)),d=i.children.map((e=>n.get(e)));for(;d.length;){let e=l.pop();const t=d.pop();if(!t||!e)continue;t.children||(t.children=[]);const i=new ys(t,r,this.target());s||!((c=t).callFrame?Boolean(c.callFrame.url)&&c.callFrame.url.startsWith("native "):Boolean(c.url)&&c.url.startsWith("native "))?(e.children.push(i),e=i):e.self+=i.self,a.set(t.id,e.id),l.push.apply(l,t.children.map((()=>e))),d.push.apply(d,t.children.map((e=>n.get(e)))),this.#Lo.set(t.id,i)}var c;return this.samples&&(this.samples=this.samples.map((e=>a.get(e)))),o}sortSamples(){if(!this.timestamps||!this.samples)return;const e=this.timestamps,t=this.samples,n=e.map(((e,t)=>t));n.sort(((t,n)=>e[t]-e[n])),this.timestamps=[],this.samples=[];for(let r=0;r=s));I++){const t=i[I];if(t===p)continue;v=o.get(t);let r=o.get(p);if(v!==l){if(r===l&&m){const e=b[h],t=g-e;y[h-1]+=t,n(m.depth+1,l,e,t,t-y[h]),--h,r=m,p=r.id,m=null}for(;v&&v.depth>r.depth;)u.push(v),v=v.parent;for(;r!==v;){const e=b[h],t=g-e;y[h-1]+=t,n(r.depth,r,e,t,t-y[h]),--h,v&&v.depth===r.depth&&(u.push(v),v=v.parent),r=r.parent}for(;u.length;){const t=u.pop();v=t,e(t.depth,t,g),b[++h]=g,y[h]=0}p=t}else m=r,e(m.depth+1,l,g),b[++h]=g,y[h]=0,p=t}if(g=a[I]||this.profileEndTime,m&&o.get(p)===l){const e=b[h],t=g-e;y[h-1]+=t,n(m.depth+1,v,e,t,t-y[h]),--h,p=m.id}for(let e=o.get(p);e&&e.parent;e=e.parent){const t=b[h],r=g-t;y[h-1]+=r,n(e.depth,e,t,r,r-y[h]),--h}}nodeByIndex(e){return this.samples&&this.#Lo.get(this.samples[e])||null}nodes(){return this.#Lo?[...this.#Lo.values()]:null}}});class Is extends c{#Oo;#No;#jr;#Fo;#Bo;#Do;#Uo;#Ho;#qo;#_o;constructor(t){super(t),this.#Oo=t.emulationAgent(),this.#No=t.deviceOrientationAgent(),this.#jr=t.model(en),this.#Fo=t.model(vn),this.#Fo&&this.#Fo.addEventListener(In.InspectModeWillBeToggled,(()=>{this.updateTouch()}),this);const n=e.Settings.Settings.instance().moduleSetting("javaScriptDisabled");n.addChangeListener((async()=>await this.#Oo.invoke_setScriptExecutionDisabled({value:n.get()}))),n.get()&&this.#Oo.invoke_setScriptExecutionDisabled({value:!0});const r=e.Settings.Settings.instance().moduleSetting("emulation.touch");r.addChangeListener((()=>{const e=r.get();this.overrideEmulateTouch("force"===e)}));const s=e.Settings.Settings.instance().moduleSetting("emulation.idleDetection");s.addChangeListener((async()=>{const e=s.get();if("none"===e)return void await this.clearIdleOverride();const t=JSON.parse(e);await this.setIdleOverride(t)}));const i=e.Settings.Settings.instance().moduleSetting("emulatedCSSMedia"),a=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeatureColorGamut"),o=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersColorScheme"),l=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeatureForcedColors"),d=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersContrast"),c=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersReducedData"),h=e.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersReducedMotion");this.#Bo=new Map([["type",i.get()],["color-gamut",a.get()],["prefers-color-scheme",o.get()],["forced-colors",l.get()],["prefers-contrast",d.get()],["prefers-reduced-data",c.get()],["prefers-reduced-motion",h.get()]]),i.addChangeListener((()=>{this.#Bo.set("type",i.get()),this.updateCssMedia()})),a.addChangeListener((()=>{this.#Bo.set("color-gamut",a.get()),this.updateCssMedia()})),o.addChangeListener((()=>{this.#Bo.set("prefers-color-scheme",o.get()),this.updateCssMedia()})),l.addChangeListener((()=>{this.#Bo.set("forced-colors",l.get()),this.updateCssMedia()})),d.addChangeListener((()=>{this.#Bo.set("prefers-contrast",d.get()),this.updateCssMedia()})),c.addChangeListener((()=>{this.#Bo.set("prefers-reduced-data",c.get()),this.updateCssMedia()})),h.addChangeListener((()=>{this.#Bo.set("prefers-reduced-motion",h.get()),this.updateCssMedia()})),this.updateCssMedia();const u=e.Settings.Settings.instance().moduleSetting("emulateAutoDarkMode");u.addChangeListener((()=>{const e=u.get();o.setDisabled(e),o.set(e?"dark":""),this.emulateAutoDarkMode(e)})),u.get()&&(o.setDisabled(!0),o.set("dark"),this.emulateAutoDarkMode(!0));const g=e.Settings.Settings.instance().moduleSetting("emulatedVisionDeficiency");g.addChangeListener((()=>this.emulateVisionDeficiency(g.get()))),g.get()&&this.emulateVisionDeficiency(g.get());const p=e.Settings.Settings.instance().moduleSetting("localFontsDisabled");p.addChangeListener((()=>this.setLocalFontsDisabled(p.get()))),p.get()&&this.setLocalFontsDisabled(p.get());const m=e.Settings.Settings.instance().moduleSetting("avifFormatDisabled"),f=e.Settings.Settings.instance().moduleSetting("webpFormatDisabled"),b=()=>{const e=[];m.get()&&e.push("avif"),f.get()&&e.push("webp"),this.setDisabledImageTypes(e)};m.addChangeListener(b),f.addChangeListener(b),(m.get()||f.get())&&b(),this.#Ho=!0,this.#Do=!1,this.#Uo=!1,this.#qo=!1,this.#_o={enabled:!1,configuration:"mobile"}}setTouchEmulationAllowed(e){this.#Ho=e}supportsDeviceEmulation(){return this.target().hasAllCapabilities(z.DeviceEmulation)}async resetPageScaleFactor(){await this.#Oo.invoke_resetPageScaleFactor()}async emulateDevice(e){e?await this.#Oo.invoke_setDeviceMetricsOverride(e):await this.#Oo.invoke_clearDeviceMetricsOverride()}overlayModel(){return this.#Fo}async emulateLocation(e){if(!e||e.error)await Promise.all([this.#Oo.invoke_clearGeolocationOverride(),this.#Oo.invoke_setTimezoneOverride({timezoneId:""}),this.#Oo.invoke_setLocaleOverride({locale:""}),this.#Oo.invoke_setUserAgentOverride({userAgent:ue.instance().currentUserAgent()})]);else{function t(e,t){const n=t.getError();return n?Promise.reject({type:e,message:n}):Promise.resolve()}await Promise.all([this.#Oo.invoke_setGeolocationOverride({latitude:e.latitude,longitude:e.longitude,accuracy:ks.defaultGeoMockAccuracy}).then((e=>t("emulation-set-location",e))),this.#Oo.invoke_setTimezoneOverride({timezoneId:e.timezoneId}).then((e=>t("emulation-set-timezone",e))),this.#Oo.invoke_setLocaleOverride({locale:e.locale}).then((e=>t("emulation-set-locale",e))),this.#Oo.invoke_setUserAgentOverride({userAgent:ue.instance().currentUserAgent(),acceptLanguage:e.locale}).then((e=>t("emulation-set-user-agent",e)))])}}async emulateDeviceOrientation(e){e?await this.#No.invoke_setDeviceOrientationOverride({alpha:e.alpha,beta:e.beta,gamma:e.gamma}):await this.#No.invoke_clearDeviceOrientationOverride()}async setIdleOverride(e){await this.#Oo.invoke_setIdleOverride(e)}async clearIdleOverride(){await this.#Oo.invoke_clearIdleOverride()}async emulateCSSMedia(e,t){await this.#Oo.invoke_setEmulatedMedia({media:e,features:t}),this.#jr&&this.#jr.mediaQueryResultChanged()}async emulateAutoDarkMode(e){e&&(this.#Bo.set("prefers-color-scheme","dark"),await this.updateCssMedia()),await this.#Oo.invoke_setAutoDarkModeOverride({enabled:e||void 0})}async emulateVisionDeficiency(e){await this.#Oo.invoke_setEmulatedVisionDeficiency({type:e})}setLocalFontsDisabled(e){this.#jr&&this.#jr.setLocalFontsEnabled(!e)}setDisabledImageTypes(e){this.#Oo.invoke_setDisabledImageTypes({imageTypes:e})}async setCPUThrottlingRate(e){await this.#Oo.invoke_setCPUThrottlingRate({rate:e})}async setHardwareConcurrency(e){if(e<1)throw new Error("hardwareConcurrency must be a positive value");await this.#Oo.invoke_setHardwareConcurrencyOverride({hardwareConcurrency:e})}async emulateTouch(e,t){this.#Do=e&&this.#Ho,this.#Uo=t&&this.#Ho,await this.updateTouch()}async overrideEmulateTouch(e){this.#qo=e&&this.#Ho,await this.updateTouch()}async updateTouch(){let e={enabled:this.#Do,configuration:this.#Uo?"mobile":"desktop"};this.#qo&&(e={enabled:!0,configuration:"mobile"}),this.#Fo&&this.#Fo.inspectModeEnabled()&&(e={enabled:!1,configuration:"mobile"}),(this.#_o.enabled||e.enabled)&&(this.#_o.enabled&&e.enabled&&this.#_o.configuration===e.configuration||(this.#_o=e,await this.#Oo.invoke_setTouchEmulationEnabled({enabled:e.enabled,maxTouchPoints:1}),await this.#Oo.invoke_setEmitTouchEventsForMouse({enabled:e.enabled,configuration:e.configuration})))}async updateCssMedia(){const e=this.#Bo.get("type")??"",t=[{name:"color-gamut",value:this.#Bo.get("color-gamut")??""},{name:"prefers-color-scheme",value:this.#Bo.get("prefers-color-scheme")??""},{name:"forced-colors",value:this.#Bo.get("forced-colors")??""},{name:"prefers-contrast",value:this.#Bo.get("prefers-contrast")??""},{name:"prefers-reduced-data",value:this.#Bo.get("prefers-reduced-data")??""},{name:"prefers-reduced-motion",value:this.#Bo.get("prefers-reduced-motion")??""}];return this.emulateCSSMedia(e,t)}}class ks{latitude;longitude;timezoneId;locale;error;constructor(e,t,n,r,s){this.latitude=e,this.longitude=t,this.timezoneId=n,this.locale=r,this.error=s}static parseSetting(e){if(e){const[t,n,r,s]=e.split(":"),[i,a]=t.split("@");return new ks(parseFloat(i),parseFloat(a),n,r,Boolean(s))}return new ks(0,0,"","",!1)}static parseUserInput(e,t,n,r){if(!e&&!t)return null;const{valid:s}=ks.latitudeValidator(e),{valid:i}=ks.longitudeValidator(t);if(!s&&!i)return null;const a=s?parseFloat(e):-1,o=i?parseFloat(t):-1;return new ks(a,o,n,r,!1)}static latitudeValidator(e){const t=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&t>=-90&&t<=90,errorMessage:void 0}}static longitudeValidator(e){const t=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&t>=-180&&t<=180,errorMessage:void 0}}static timezoneIdValidator(e){return{valid:""===e||/[a-zA-Z]/.test(e),errorMessage:void 0}}static localeValidator(e){return{valid:""===e||/[a-zA-Z]{2}/.test(e),errorMessage:void 0}}toSetting(){return`${this.latitude}@${this.longitude}:${this.timezoneId}:${this.locale}:${this.error||""}`}static defaultGeoMockAccuracy=150}class Ss{alpha;beta;gamma;constructor(e,t,n){this.alpha=e,this.beta=t,this.gamma=n}static parseSetting(e){if(e){const t=JSON.parse(e);return new Ss(t.alpha,t.beta,t.gamma)}return new Ss(0,0,0)}static parseUserInput(e,t,n){if(!e&&!t&&!n)return null;const{valid:r}=Ss.alphaAngleValidator(e),{valid:s}=Ss.betaAngleValidator(t),{valid:i}=Ss.gammaAngleValidator(n);if(!r&&!s&&!i)return null;const a=r?parseFloat(e):-1,o=s?parseFloat(t):-1,l=i?parseFloat(n):-1;return new Ss(a,o,l)}static angleRangeValidator(e,t){const n=parseFloat(e);return{valid:/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(e)&&n>=t.minimum&&n{this.#Wo=n=>{e(n),t(n)}}:e=>{this.#Wo=e});const n=await e.runtimeAgent().invoke_evaluate({expression:"navigator.hardwareConcurrency",returnByValue:!0,silent:!0,throwOnSideEffect:!0}),r=n.getError();if(r)throw new Error(r);const{result:s,exceptionDetails:i}=n;if(i)throw new Error(i.text);return s.value}modelAdded(e){if(this.#zo!==xs.NoThrottling&&e.setCPUThrottlingRate(this.#zo),void 0!==this.#jo&&e.setHardwareConcurrency(this.#jo),this.#Wo){const e=this.#Wo;this.#Wo=void 0,this.getHardwareConcurrency().then(e)}}modelRemoved(e){}}var Rs,xs;!function(e){e.RateChanged="RateChanged",e.HardwareConcurrencyChanged="HardwareConcurrencyChanged"}(Rs||(Rs={})),function(e){e[e.NoThrottling=1]="NoThrottling",e[e.MidTierMobile=4]="MidTierMobile",e[e.LowEndMobile=6]="LowEndMobile"}(xs||(xs={}));var Ms=Object.freeze({__proto__:null,CPUThrottlingManager:Ts,get Events(){return Rs},throttlingManager:function(){return Ts.instance()},get CPUThrottlingRates(){return xs}});const Ps=new Set(["inherit","initial","unset"]),Ls=/[\x20-\x7E]{4}/,Es=new RegExp(`(?:'(${Ls.source})')|(?:"(${Ls.source})")\\s+(${/[+-]?(?:\d*\.)?\d+(?:[eE]\d+)?/.source})`);const As=/^"(.+)"|'(.+)'$/;function Os(e){return e.split(",").map((e=>e.trim()))}function Ns(e){return e.replaceAll(/(\/\*(?:.|\s)*?\*\/)/g,"")}var Fs=Object.freeze({__proto__:null,parseFontVariationSettings:function(e){if(Ps.has(e.trim())||"normal"===e.trim())return[];const t=[];for(const n of Os(Ns(e))){const e=n.match(Es);e&&t.push({tag:e[1]||e[2],value:parseFloat(e[3])})}return t},parseFontFamily:function(e){if(Ps.has(e.trim()))return[];const t=[];for(const n of Os(Ns(e))){const e=n.match(As);e?t.push(e[1]||e[2]):t.push(n)}return t},splitByComma:Os,stripComments:Ns});const Bs={trustedTypeViolations:"Trusted Type Violations",sinkViolations:"Sink Violations",policyViolations:"Policy Violations",animation:"Animation",canvas:"Canvas",geolocation:"Geolocation",notification:"Notification",parse:"Parse",script:"Script",timer:"Timer",window:"Window",webaudio:"WebAudio",media:"Media",pictureinpicture:"Picture-in-Picture",clipboard:"Clipboard",control:"Control",device:"Device",domMutation:"DOM Mutation",dragDrop:"Drag / drop",keyboard:"Keyboard",load:"Load",mouse:"Mouse",pointer:"Pointer",touch:"Touch",xhr:"XHR",setTimeoutOrIntervalFired:"{PH1} fired",scriptFirstStatement:"Script First Statement",scriptBlockedByContentSecurity:"Script Blocked by Content Security Policy",requestAnimationFrame:"Request Animation Frame",cancelAnimationFrame:"Cancel Animation Frame",animationFrameFired:"Animation Frame Fired",webglErrorFired:"WebGL Error Fired",webglWarningFired:"WebGL Warning Fired",setInnerhtml:"Set `innerHTML`",createCanvasContext:"Create canvas context",createAudiocontext:"Create `AudioContext`",closeAudiocontext:"Close `AudioContext`",resumeAudiocontext:"Resume `AudioContext`",suspendAudiocontext:"Suspend `AudioContext`",webglErrorFiredS:"WebGL Error Fired ({PH1})",scriptBlockedDueToContent:"Script blocked due to Content Security Policy directive: {PH1}",worker:"Worker"},Ds=s.i18n.registerUIStrings("core/sdk/DOMDebuggerModel.ts",Bs),Us=s.i18n.getLocalizedString.bind(void 0,Ds);class Hs extends c{agent;#ba;#Mr;#Vo;#Go;suspended=!1;constructor(t){super(t),this.agent=t.domdebuggerAgent(),this.#ba=t.model(Cr),this.#Mr=t.model(Pn),this.#Mr.addEventListener(wn.DocumentUpdated,this.documentUpdated,this),this.#Mr.addEventListener(wn.NodeRemoved,this.nodeRemoved,this),this.#Vo=[],this.#Go=e.Settings.Settings.instance().createLocalSetting("domBreakpoints",[]),this.#Mr.existingDocument()&&this.documentUpdated()}runtimeModel(){return this.#ba}async suspendModel(){this.suspended=!0}async resumeModel(){this.suspended=!1}async eventListeners(e){if(console.assert(e.runtimeModel()===this.#ba),!e.objectId)return[];const t=await this.agent.invoke_getEventListeners({objectId:e.objectId}),n=[];for(const r of t.listeners||[]){const t=this.#ba.debuggerModel().createRawLocationByScriptId(r.scriptId,r.lineNumber,r.columnNumber);t&&n.push(new js(this,e,r.type,r.useCapture,r.passive,r.once,r.handler?this.#ba.createRemoteObject(r.handler):null,r.originalHandler?this.#ba.createRemoteObject(r.originalHandler):null,t,null))}return n}retrieveDOMBreakpoints(){this.#Mr.requestDocument()}domBreakpoints(){return this.#Vo.slice()}hasDOMBreakpoint(e,t){return this.#Vo.some((n=>n.node===e&&n.type===t))}setDOMBreakpoint(e,t){for(const n of this.#Vo)if(n.node===e&&n.type===t)return this.toggleDOMBreakpoint(n,!0),n;const n=new zs(this,e,t,!0);return this.#Vo.push(n),this.saveDOMBreakpoints(),this.enableDOMBreakpoint(n),this.dispatchEventToListeners(qs.DOMBreakpointAdded,n),n}removeDOMBreakpoint(e,t){this.removeDOMBreakpoints((n=>n.node===e&&n.type===t))}removeAllDOMBreakpoints(){this.removeDOMBreakpoints((e=>!0))}toggleDOMBreakpoint(e,t){t!==e.enabled&&(e.enabled=t,t?this.enableDOMBreakpoint(e):this.disableDOMBreakpoint(e),this.dispatchEventToListeners(qs.DOMBreakpointToggled,e))}enableDOMBreakpoint(e){e.node.id&&(this.agent.invoke_setDOMBreakpoint({nodeId:e.node.id,type:e.type}),e.node.setMarker(_s,!0))}disableDOMBreakpoint(e){e.node.id&&(this.agent.invoke_removeDOMBreakpoint({nodeId:e.node.id,type:e.type}),e.node.setMarker(_s,!!this.nodeHasBreakpoints(e.node)||null))}nodeHasBreakpoints(e){for(const t of this.#Vo)if(t.node===e&&t.enabled)return!0;return!1}resolveDOMBreakpointData(e){const t=e.type,n=this.#Mr.nodeForId(e.nodeId);if(!t||!n)return null;let r=null,s=!1;return"subtree-modified"===t&&(s=e.insertion||!1,r=this.#Mr.nodeForId(e.targetNodeId)),{type:t,node:n,targetNode:r,insertion:s}}currentURL(){const e=this.#Mr.existingDocument();return e?e.documentURL:t.DevToolsPath.EmptyUrlString}async documentUpdated(){if(this.suspended)return;const e=this.#Vo;this.#Vo=[],this.dispatchEventToListeners(qs.DOMBreakpointsRemoved,e);const n=await this.#Mr.requestDocument(),r=n?n.documentURL:t.DevToolsPath.EmptyUrlString;for(const e of this.#Go.get())e.url===r&&this.#Mr.pushNodeByPathToFrontend(e.path).then(s.bind(this,e));function s(e,t){const n=t?this.#Mr.nodeForId(t):null;if(!n)return;const r=new zs(this,n,e.type,e.enabled);this.#Vo.push(r),e.enabled&&this.enableDOMBreakpoint(r),this.dispatchEventToListeners(qs.DOMBreakpointAdded,r)}}removeDOMBreakpoints(e){const t=[],n=[];for(const r of this.#Vo)e(r)?(t.push(r),r.enabled&&(r.enabled=!1,this.disableDOMBreakpoint(r))):n.push(r);t.length&&(this.#Vo=n,this.saveDOMBreakpoints(),this.dispatchEventToListeners(qs.DOMBreakpointsRemoved,t))}nodeRemoved(e){if(this.suspended)return;const{node:t}=e.data,n=t.children()||[];this.removeDOMBreakpoints((e=>e.node===t||-1!==n.indexOf(e.node)))}saveDOMBreakpoints(){const e=this.currentURL(),t=this.#Go.get().filter((t=>t.url!==e));for(const n of this.#Vo)t.push({url:e,path:n.node.path(),type:n.type,enabled:n.enabled});this.#Go.set(t)}}var qs;!function(e){e.DOMBreakpointAdded="DOMBreakpointAdded",e.DOMBreakpointToggled="DOMBreakpointToggled",e.DOMBreakpointsRemoved="DOMBreakpointsRemoved"}(qs||(qs={}));const _s="breakpoint-marker";class zs{domDebuggerModel;node;type;enabled;constructor(e,t,n,r){this.domDebuggerModel=e,this.node=t,this.type=n,this.enabled=r}}class js{#Ko;#$o;#p;#Qo;#Xo;#Jo;#Yo;#Zo;#na;#el;#tl;#nl;constructor(e,n,r,s,i,a,o,l,d,c,h){this.#Ko=e,this.#$o=n,this.#p=r,this.#Qo=s,this.#Xo=i,this.#Jo=a,this.#Yo=o,this.#Zo=l||o,this.#na=d;const u=d.script();this.#el=u?u.contentURL():t.DevToolsPath.EmptyUrlString,this.#tl=c,this.#nl=h||js.Origin.Raw}domDebuggerModel(){return this.#Ko}type(){return this.#p}useCapture(){return this.#Qo}passive(){return this.#Xo}once(){return this.#Jo}handler(){return this.#Yo}location(){return this.#na}sourceURL(){return this.#el}originalHandler(){return this.#Zo}canRemove(){return Boolean(this.#tl)||this.#nl!==js.Origin.FrameworkUser}remove(){if(!this.canRemove())return Promise.resolve(void 0);if(this.#nl!==js.Origin.FrameworkUser){function e(e,t,n){this.removeEventListener(e,t,n),this["on"+e]&&(this["on"+e]=void 0)}return this.#$o.callFunction(e,[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo)]).then((()=>{}))}if(this.#tl){function e(e,t,n,r){this.call(null,e,t,n,r)}return this.#tl.callFunction(e,[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo),Le.toCallArgument(this.#Xo)]).then((()=>{}))}return Promise.resolve(void 0)}canTogglePassive(){return this.#nl!==js.Origin.FrameworkUser}togglePassive(){return this.#$o.callFunction((function(e,t,n,r){this.removeEventListener(e,t,{capture:n}),this.addEventListener(e,t,{capture:n,passive:!r})}),[Le.toCallArgument(this.#p),Le.toCallArgument(this.#Zo),Le.toCallArgument(this.#Qo),Le.toCallArgument(this.#Xo)]).then((()=>{}))}origin(){return this.#nl}markAsFramework(){this.#nl=js.Origin.Framework}isScrollBlockingType(){return"touchstart"===this.#p||"touchmove"===this.#p||"mousewheel"===this.#p||"wheel"===this.#p}}!function(e){let t;!function(e){e.Raw="Raw",e.Framework="Framework",e.FrameworkUser="FrameworkUser"}(t=e.Origin||(e.Origin={}))}(js||(js={}));class Ws extends Fr{#p;constructor(e,t,n){super(e,t),this.#p=n}type(){return this.#p}}class Vs extends Fr{instrumentationName;eventName;eventTargetNames;constructor(e,t,n,r,s){super(r,s),this.instrumentationName=e,this.eventName=t,this.eventTargetNames=n}setEnabled(e){if(this.enabled()!==e){super.setEnabled(e);for(const e of K.instance().models(Hs))this.updateOnModel(e)}}updateOnModel(e){if(this.instrumentationName)this.enabled()?e.agent.invoke_setInstrumentationBreakpoint({eventName:this.instrumentationName}):e.agent.invoke_removeInstrumentationBreakpoint({eventName:this.instrumentationName});else for(const t of this.eventTargetNames)this.enabled()?e.agent.invoke_setEventListenerBreakpoint({eventName:this.eventName,targetName:t}):e.agent.invoke_removeEventListenerBreakpoint({eventName:this.eventName,targetName:t})}static listener="listener:";static instrumentation="instrumentation:"}let Gs;class Ks{#rl;#sl;#il;#al;constructor(){this.#rl=e.Settings.Settings.instance().createLocalSetting("xhrBreakpoints",[]),this.#sl=new Map;for(const e of this.#rl.get())this.#sl.set(e.url,e.enabled);this.#il=[],this.#il.push(new Ws(Us(Bs.trustedTypeViolations),Us(Bs.sinkViolations),"trustedtype-sink-violation")),this.#il.push(new Ws(Us(Bs.trustedTypeViolations),Us(Bs.policyViolations),"trustedtype-policy-violation")),this.#al=[],this.createInstrumentationBreakpoints(Us(Bs.animation),["requestAnimationFrame","cancelAnimationFrame","requestAnimationFrame.callback"]),this.createInstrumentationBreakpoints(Us(Bs.canvas),["canvasContextCreated","webglErrorFired","webglWarningFired"]),this.createInstrumentationBreakpoints(Us(Bs.geolocation),["Geolocation.getCurrentPosition","Geolocation.watchPosition"]),this.createInstrumentationBreakpoints(Us(Bs.notification),["Notification.requestPermission"]),this.createInstrumentationBreakpoints(Us(Bs.parse),["Element.setInnerHTML","Document.write"]),this.createInstrumentationBreakpoints(Us(Bs.script),["scriptFirstStatement","scriptBlockedByCSP"]),this.createInstrumentationBreakpoints(Us(Bs.timer),["setTimeout","clearTimeout","setInterval","clearInterval","setTimeout.callback","setInterval.callback"]),this.createInstrumentationBreakpoints(Us(Bs.window),["DOMWindow.close"]),this.createInstrumentationBreakpoints(Us(Bs.webaudio),["audioContextCreated","audioContextClosed","audioContextResumed","audioContextSuspended"]),this.createEventListenerBreakpoints(Us(Bs.media),["play","pause","playing","canplay","canplaythrough","seeking","seeked","timeupdate","ended","ratechange","durationchange","volumechange","loadstart","progress","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","waiting"],["audio","video"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["enterpictureinpicture","leavepictureinpicture"],["video"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["resize"],["PictureInPictureWindow"]),this.createEventListenerBreakpoints(Us(Bs.pictureinpicture),["enter"],["documentPictureInPicture"]),this.createEventListenerBreakpoints(Us(Bs.clipboard),["copy","cut","paste","beforecopy","beforecut","beforepaste"],["*"]),this.createEventListenerBreakpoints(Us(Bs.control),["resize","scroll","scrollend","zoom","focus","blur","select","change","submit","reset"],["*"]),this.createEventListenerBreakpoints(Us(Bs.device),["deviceorientation","devicemotion"],["*"]),this.createEventListenerBreakpoints(Us(Bs.domMutation),["DOMActivate","DOMFocusIn","DOMFocusOut","DOMAttrModified","DOMCharacterDataModified","DOMNodeInserted","DOMNodeInsertedIntoDocument","DOMNodeRemoved","DOMNodeRemovedFromDocument","DOMSubtreeModified","DOMContentLoaded"],["*"]),this.createEventListenerBreakpoints(Us(Bs.dragDrop),["drag","dragstart","dragend","dragenter","dragover","dragleave","drop"],["*"]),this.createEventListenerBreakpoints(Us(Bs.keyboard),["keydown","keyup","keypress","input"],["*"]),this.createEventListenerBreakpoints(Us(Bs.load),["load","beforeunload","unload","abort","error","hashchange","popstate","navigate","navigatesuccess","navigateerror","currentchange","navigateto","navigatefrom","finish","dispose"],["*"]),this.createEventListenerBreakpoints(Us(Bs.mouse),["auxclick","click","dblclick","mousedown","mouseup","mouseover","mousemove","mouseout","mouseenter","mouseleave","mousewheel","wheel","contextmenu"],["*"]),this.createEventListenerBreakpoints(Us(Bs.pointer),["pointerover","pointerout","pointerenter","pointerleave","pointerdown","pointerup","pointermove","pointercancel","gotpointercapture","lostpointercapture","pointerrawupdate"],["*"]),this.createEventListenerBreakpoints(Us(Bs.touch),["touchstart","touchmove","touchend","touchcancel"],["*"]),this.createEventListenerBreakpoints(Us(Bs.worker),["message","messageerror"],["*"]),this.createEventListenerBreakpoints(Us(Bs.xhr),["readystatechange","load","loadstart","loadend","abort","error","progress","timeout"],["xmlhttprequest","xmlhttprequestupload"]);for(const[e,t]of[["setTimeout.callback",Us(Bs.setTimeoutOrIntervalFired,{PH1:"setTimeout"})],["setInterval.callback",Us(Bs.setTimeoutOrIntervalFired,{PH1:"setInterval"})],["scriptFirstStatement",Us(Bs.scriptFirstStatement)],["scriptBlockedByCSP",Us(Bs.scriptBlockedByContentSecurity)],["requestAnimationFrame",Us(Bs.requestAnimationFrame)],["cancelAnimationFrame",Us(Bs.cancelAnimationFrame)],["requestAnimationFrame.callback",Us(Bs.animationFrameFired)],["webglErrorFired",Us(Bs.webglErrorFired)],["webglWarningFired",Us(Bs.webglWarningFired)],["Element.setInnerHTML",Us(Bs.setInnerhtml)],["canvasContextCreated",Us(Bs.createCanvasContext)],["Geolocation.getCurrentPosition","getCurrentPosition"],["Geolocation.watchPosition","watchPosition"],["Notification.requestPermission","requestPermission"],["DOMWindow.close","window.close"],["Document.write","document.write"],["audioContextCreated",Us(Bs.createAudiocontext)],["audioContextClosed",Us(Bs.closeAudiocontext)],["audioContextResumed",Us(Bs.resumeAudiocontext)],["audioContextSuspended",Us(Bs.suspendAudiocontext)]]){const n=this.resolveEventListenerBreakpointInternal("instrumentation:"+e);n&&n.setTitle(t)}K.instance().observeModels(Hs,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return Gs&&!t||(Gs=new Ks),Gs}cspViolationBreakpoints(){return this.#il.slice()}createInstrumentationBreakpoints(e,t){for(const n of t)this.#al.push(new Vs(n,"",[],e,n))}createEventListenerBreakpoints(e,t,n){for(const r of t)this.#al.push(new Vs("",r,n,e,r))}resolveEventListenerBreakpointInternal(e,t){const n="instrumentation:",r="listener:";let s="";if(e.startsWith(n))s=e.substring(n.length),e="";else{if(!e.startsWith(r))return null;e=e.substring(r.length)}t=(t||"*").toLowerCase();let i=null;for(const n of this.#al)s&&n.instrumentationName===s&&(i=n),e&&n.eventName===e&&-1!==n.eventTargetNames.indexOf(t)&&(i=n),!i&&e&&n.eventName===e&&-1!==n.eventTargetNames.indexOf("*")&&(i=n);return i}eventListenerBreakpoints(){return this.#al.slice()}resolveEventListenerBreakpointTitle(e){const t=e.eventName;if("instrumentation:webglErrorFired"===t&&e.webglErrorName){let t=e.webglErrorName;return t=t.replace(/^.*(0x[0-9a-f]+).*$/i,"$1"),Us(Bs.webglErrorFiredS,{PH1:t})}if("instrumentation:scriptBlockedByCSP"===t&&e.directiveText)return Us(Bs.scriptBlockedDueToContent,{PH1:e.directiveText});const n=this.resolveEventListenerBreakpointInternal(t,e.targetName);return n?e.targetName?e.targetName+"."+n.title():n.title():""}resolveEventListenerBreakpoint(e){return this.resolveEventListenerBreakpointInternal(e.eventName,e.targetName)}updateCSPViolationBreakpoints(){const e=this.#il.filter((e=>e.enabled())).map((e=>e.type()));for(const t of K.instance().models(Hs))this.updateCSPViolationBreakpointsForModel(t,e)}updateCSPViolationBreakpointsForModel(e,t){e.agent.invoke_setBreakOnCSPViolation({violationTypes:t})}xhrBreakpoints(){return this.#sl}saveXHRBreakpoints(){const e=[];for(const t of this.#sl.keys())e.push({url:t,enabled:this.#sl.get(t)||!1});this.#rl.set(e)}addXHRBreakpoint(e,t){if(this.#sl.set(e,t),t)for(const t of K.instance().models(Hs))t.agent.invoke_setXHRBreakpoint({url:e});this.saveXHRBreakpoints()}removeXHRBreakpoint(e){const t=this.#sl.get(e);if(this.#sl.delete(e),t)for(const t of K.instance().models(Hs))t.agent.invoke_removeXHRBreakpoint({url:e});this.saveXHRBreakpoints()}toggleXHRBreakpoint(e,t){this.#sl.set(e,t);for(const n of K.instance().models(Hs))t?n.agent.invoke_setXHRBreakpoint({url:e}):n.agent.invoke_removeXHRBreakpoint({url:e});this.saveXHRBreakpoints()}modelAdded(e){for(const t of this.#sl.keys())this.#sl.get(t)&&e.agent.invoke_setXHRBreakpoint({url:t});for(const t of this.#al)t.enabled()&&t.updateOnModel(e);const t=this.#il.filter((e=>e.enabled())).map((e=>e.type()));this.updateCSPViolationBreakpointsForModel(e,t)}modelRemoved(e){}}c.register(Hs,{capabilities:z.DOM,autostart:!1});var $s=Object.freeze({__proto__:null,DOMDebuggerModel:Hs,get Events(){return qs},DOMBreakpoint:zs,get EventListener(){return js},CSPViolationBreakpoint:Ws,DOMEventListenerBreakpoint:Vs,DOMDebuggerManager:Ks});const Qs={auctionWorklet:"Ad Auction Worklet",beforeBidderWorkletBiddingStart:"Bidder Bidding Phase Start",beforeBidderWorkletReportingStart:"Bidder Reporting Phase Start",beforeSellerWorkletScoringStart:"Seller Scoring Phase Start",beforeSellerWorkletReportingStart:"Seller Reporting Phase Start"},Xs=s.i18n.registerUIStrings("core/sdk/EventBreakpointsModel.ts",Qs),Js=s.i18n.getLocalizedString.bind(void 0,Xs);class Ys extends c{agent;constructor(e){super(e),this.agent=e.eventBreakpointsAgent()}}class Zs extends Fr{instrumentationName;constructor(e,t){super(t,function(e){switch(e){case"beforeBidderWorkletBiddingStart":return Js(Qs.beforeBidderWorkletBiddingStart);case"beforeBidderWorkletReportingStart":return Js(Qs.beforeBidderWorkletReportingStart);case"beforeSellerWorkletScoringStart":return Js(Qs.beforeSellerWorkletScoringStart);case"beforeSellerWorkletReportingStart":return Js(Qs.beforeSellerWorkletReportingStart)}}(e)),this.instrumentationName=e}setEnabled(e){if(this.enabled()!==e){super.setEnabled(e);for(const e of K.instance().models(Ys))this.updateOnModel(e)}}updateOnModel(e){this.enabled()?e.agent.invoke_setInstrumentationBreakpoint({eventName:this.instrumentationName}):e.agent.invoke_removeInstrumentationBreakpoint({eventName:this.instrumentationName})}static instrumentationPrefix="instrumentation:"}let ei;class ti{#al=[];constructor(){this.createInstrumentationBreakpoints(Js(Qs.auctionWorklet),["beforeBidderWorkletBiddingStart","beforeBidderWorkletReportingStart","beforeSellerWorkletScoringStart","beforeSellerWorkletReportingStart"]),K.instance().observeModels(Ys,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return ei&&!t||(ei=new ti),ei}createInstrumentationBreakpoints(e,t){for(const n of t)this.#al.push(new Zs(n,e))}eventListenerBreakpoints(){return this.#al.slice()}resolveEventListenerBreakpointTitle(e){const t=this.resolveEventListenerBreakpoint(e);return t?t.title():null}resolveEventListenerBreakpoint(e){const t=e.eventName;if(!t.startsWith(Zs.instrumentationPrefix))return null;const n=t.substring(Zs.instrumentationPrefix.length);return this.#al.find((e=>e.instrumentationName===n))||null}modelAdded(e){for(const t of this.#al)t.enabled()&&t.updateOnModel(e)}modelRemoved(e){}}c.register(Ys,{capabilities:z.EventBreakpoints,autostart:!1});var ni=Object.freeze({__proto__:null,EventBreakpointsModel:Ys,EventBreakpointsManager:ti});class ri{#ol;#ll;#dl;#cl;#hl;#ul;#gl;#pl;#ml;#fl;#bl;#yl;#vl=[];constructor(e){this.#ol=e,this.#ll=new Map,this.#dl=new Map,this.#cl=Number(1/0),this.#hl=Number(-1/0),this.#ul=[],this.#gl=[],this.#pl=new Map,this.#ml=new Map,this.#fl=new Map,this.#bl=new Map,this.#yl=new Map}static isTopLevelEvent(e){return vi(e,li)&&"RunTask"===e.name||vi(e,ai)||vi(e,oi)&&"Program"===e.name}static extractId(e){const t=e.scope||"";if(void 0===e.id2)return t&&e.id?`${t}@${e.id}`:e.id;const n=e.id2;if("object"==typeof n&&"global"in n!="local"in n)return void 0!==n.global?`:${t}:${n.global}`:`:${t}:${e.pid}:${n.local}`;console.error(`Unexpected id2 field at ${e.ts/1e3}, one and only one of 'local' and 'global' should be present.`)}static browserMainThread(t){const n=t.sortedProcesses();if(!n.length)return null;const r="CrBrowserMain",s=[],i=[];for(const e of n)e.name().toLowerCase().endsWith("browser")&&s.push(e),i.push(...e.sortedThreads().filter((e=>e.name()===r)));if(1===i.length)return i[0];if(1===s.length)return s[0].threadByName(r);const a=t.devToolsMetadataEvents().filter((e=>"TracingStartedInBrowser"===e.name));return 1===a.length?a[0].thread:(e.Console.Console.instance().error("Failed to find browser main thread in trace, some timeline features may be unavailable"),null)}allRawEvents(){return this.#vl}devToolsMetadataEvents(){return this.#ul}addEvents(e){for(let t=0;te.#kl!==t.#kl?e.#kl-t.#kl:e.name().localeCompare(t.name())))}setName(e){this.#u=e}name(){return this.#u}id(){return this.idInternal}setSortIndex(e){this.#kl=e}getModel(){return this.model}}class fi extends mi{threads;#Sl;constructor(e,t){super(e,t),this.threads=new Map,this.#Sl=new Map}threadById(e){let t=this.threads.get(e);return t||(t=new bi(this,e),this.threads.set(e,t)),t}threadByName(e){return this.#Sl.get(e)||null}setThreadByName(e,t){this.#Sl.set(e,t)}addEvent(e){return this.threadById(e.tid).addEvent(e)}sortedThreads(){return mi.sort([...this.threads.values()])}}class bi extends mi{#wl;#Cl;#Tl;#Rl;constructor(e,t){super(e.getModel(),t),this.#wl=e,this.#Cl=[],this.#Tl=[],this.#Rl=null}#xl(e,t){return e.phase===t}tracingComplete(){this.#Tl.sort(di.compareStartTime),this.#Cl.sort(di.compareStartTime);const e=[],t=new Set;for(let n=0;n!t.has(n)))}addEvent(e){const t="O"===e.ph?ui.fromPayload(e,this):hi.fromPayload(e,this);if(ri.isTopLevelEvent(t)){const e=this.#Rl;if(e&&(e.endTime||0)>t.startTime)return null;this.#Rl=t}return this.#Cl.push(t),t}addAsyncEvent(e){this.#Tl.push(e)}setName(e){super.setName(e),this.#wl.setThreadByName(e,this)}process(){return this.#wl}events(){return this.#Cl}asyncEvents(){return this.#Tl}removeEventsByName(e){const t=[];return this.#Cl=this.#Cl.filter((n=>!!n&&(n.name!==e||(t.push(n),!1)))),t}}const yi=new Map;function vi(e,t){if(e instanceof di)return e.hasCategory(t);let n=yi.get(e.cat);return n||(n=new Set(e.cat.split(",")||[])),n.has(t)}var Ii=Object.freeze({__proto__:null,TracingModel:ri,eventPhasesOfInterestForTraceBounds:si,MetadataEvent:ii,LegacyTopLevelEventCategory:ai,DevToolsMetadataEventCategory:oi,DevToolsTimelineEventCategory:li,eventHasPayload:function(e){return"rawPayload"in e},Event:di,ConstructedEvent:ci,PayloadEvent:hi,ObjectSnapshot:ui,AsyncEvent:gi,Process:fi,Thread:bi,timesForEventInMilliseconds:function(e){if(e instanceof di)return{startTime:l.Types.Timing.MilliSeconds(e.startTime),endTime:e.endTime?l.Types.Timing.MilliSeconds(e.endTime):void 0,duration:l.Types.Timing.MilliSeconds(e.duration||0),selfTime:l.Types.Timing.MilliSeconds(e.selfTime)};const t=e.dur?l.Helpers.Timing.microSecondsToMilliseconds(e.dur):l.Types.Timing.MilliSeconds(0);return{startTime:l.Helpers.Timing.microSecondsToMilliseconds(e.ts),endTime:l.Helpers.Timing.microSecondsToMilliseconds(l.Types.Timing.MicroSeconds(e.ts+(e.dur||0))),duration:e.dur?l.Helpers.Timing.microSecondsToMilliseconds(e.dur):l.Types.Timing.MilliSeconds(0),selfTime:t}},eventHasCategory:vi,phaseForEvent:function(e){return e instanceof di?e.phase:e.ph},threadIDForEvent:function(e){return e instanceof di?e.thread.idInternal:e.tid},eventIsFromNewEngine:function(e){return null!==e&&!(e instanceof di)}});const ki="disabled-by-default-devtools.screenshot",Si={Screenshot:"Screenshot"};class wi{#Ml;timestamp;index;#Pl;#Ll;constructor(e,t,n){this.#Ml=e,this.timestamp=t,this.index=n,this.#Ll=null,this.#Pl=null}static fromSnapshot(e,t,n){const r=new wi(e,t.startTime,n);return r.#Pl=t,r}static fromTraceEvent(e,t,n){const r=l.Helpers.Timing.microSecondsToMilliseconds(t.ts),s=new wi(e,r,n);return s.#Ll=t,s}model(){return this.#Ml}imageDataPromise(){return this.#Ll?Promise.resolve(this.#Ll.args.snapshot):this.#Pl?Promise.resolve(this.#Pl.getSnapshot()):Promise.resolve(null)}}var Ci=Object.freeze({__proto__:null,FilmStripModel:class{#Ve;#El;#Al;constructor(e,t){this.#Ve=[],this.#El=0,this.#Al=0,this.reset(e,t)}hasFrames(){return this.#Ve.length>0}reset(e,t){this.#El=t||e.minimumRecordTime(),this.#Al=e.maximumRecordTime()-this.#El,this.#Ve=[];const n=ri.browserMainThread(e);if(!n)return;const r=n.events();for(let e=0;et.timestampe.update()))),await new Promise((e=>window.setTimeout(e,Pi)))}}var Mi;(Mi||(Mi={})).MemoryChanged="MemoryChanged";const Pi=2e3;class Li{#E;modelsInternal;#Bl;#Dl;constructor(e){this.#E=e,this.modelsInternal=new Set,this.#Bl=0;const t=12e4/Pi;this.#Dl=new Ei(t)}id(){return this.#E}models(){return this.modelsInternal}runtimeModel(){return this.modelsInternal.values().next().value||null}heapProfilerModel(){const e=this.runtimeModel();return e&&e.heapProfilerModel()}async update(){const e=this.runtimeModel(),t=e&&await e.heapUsage();t&&(this.#Bl=t.usedSize,this.#Dl.add(this.#Bl),xi.instance().dispatchEventToListeners(Mi.MemoryChanged,this))}samplesCount(){return this.#Dl.count()}usedHeapSize(){return this.#Bl}usedHeapSizeGrowRate(){return this.#Dl.fitSlope()}isMainThread(){const e=this.runtimeModel();return!!e&&"main"===e.target().id()}}class Ei{#Ul;#Hl;#Kr;#ql;#_l;#zl;#jl;#Wl;#Vl;constructor(e){this.#Ul=0|e,this.reset()}reset(){this.#Hl=Date.now(),this.#Kr=0,this.#ql=[],this.#_l=[],this.#zl=0,this.#jl=0,this.#Wl=0,this.#Vl=0}count(){return this.#ql.length}add(e,t){const n="number"==typeof t?t:Date.now()-this.#Hl,r=e;if(this.#ql.length===this.#Ul){const e=this.#ql[this.#Kr],t=this.#_l[this.#Kr];this.#zl-=e,this.#jl-=t,this.#Wl-=e*e,this.#Vl-=e*t}this.#zl+=n,this.#jl+=r,this.#Wl+=n*n,this.#Vl+=n*r,this.#ql[this.#Kr]=n,this.#_l[this.#Kr]=r,this.#Kr=(this.#Kr+1)%this.#Ul}fitSlope(){const e=this.count();return e<2?0:(this.#Vl-this.#zl*this.#jl/e)/(this.#Wl-this.#zl*this.#zl/e)}}var Ai=Object.freeze({__proto__:null,IsolateManager:xi,get Events(){return Mi},MemoryTrendWindowMs:12e4,Isolate:Li,MemoryTrend:Ei});class Oi extends c{#Gl=!1;#ma=!1;constructor(e){super(e),this.ensureEnabled()}async ensureEnabled(){if(this.#ma)return;this.#ma=!0,this.target().registerAuditsDispatcher(this);const e=this.target().auditsAgent();await e.invoke_enable()}issueAdded(e){this.dispatchEventToListeners("IssueAdded",{issuesModel:this,inspectorIssue:e.issue})}dispose(){super.dispose(),this.#Gl=!0}getTargetIfNotDisposed(){return this.#Gl?null:this.target()}}c.register(Oi,{capabilities:z.Audits,autostart:!0});var Ni,Fi=Object.freeze({__proto__:null,IssuesModel:Oi});!function(e){let t;!function(e){e.NonFastScrollable="NonFastScrollable",e.TouchEventHandler="TouchEventHandler",e.WheelEventHandler="WheelEventHandler",e.RepaintsOnScroll="RepaintsOnScroll",e.MainThreadScrollingReason="MainThreadScrollingReason"}(t=e.ScrollRectType||(e.ScrollRectType={}))}(Ni||(Ni={}));var Bi=Object.freeze({__proto__:null,get Layer(){return Ni},StickyPositionConstraint:class{#Kl;#$l;#Ql;#Xl;constructor(e,t){this.#Kl=t.stickyBoxRect,this.#$l=t.containingBlockRect,this.#Ql=null,e&&t.nearestLayerShiftingStickyBox&&(this.#Ql=e.layerById(t.nearestLayerShiftingStickyBox)),this.#Xl=null,e&&t.nearestLayerShiftingContainingBlock&&(this.#Xl=e.layerById(t.nearestLayerShiftingContainingBlock))}stickyBoxRect(){return this.#Kl}containingBlockRect(){return this.#$l}nearestLayerShiftingStickyBox(){return this.#Ql}nearestLayerShiftingContainingBlock(){return this.#Xl}},LayerTreeBase:class{#e;#Mr;layersById;#Jl;#Yl;#Zl;#ed;constructor(e){this.#e=e,this.#Mr=e?e.model(Pn):null,this.layersById=new Map,this.#Jl=null,this.#Yl=null,this.#Zl=new Map}target(){return this.#e}root(){return this.#Jl}setRoot(e){this.#Jl=e}contentRoot(){return this.#Yl}setContentRoot(e){this.#Yl=e}forEachLayer(e,t){return!(!t&&!(t=this.root()))&&(e(t)||t.children().some(this.forEachLayer.bind(this,e)))}layerById(e){return this.layersById.get(e)||null}async resolveBackendNodeIds(e){if(!e.size||!this.#Mr)return;const t=await this.#Mr.pushNodesByBackendIdsToFrontend(e);if(t)for(const e of t.keys())this.#Zl.set(e,t.get(e)||null)}backendNodeIdToNode(){return this.#Zl}setViewportSize(e){this.#ed=e}viewportSize(){return this.#ed}nodeForId(e){return this.#Mr?this.#Mr.nodeForId(e):null}}});class Di{id;url;startTime;loadTime;contentLoadTime;mainRequest;constructor(e){this.id=++Di.lastIdentifier,this.url=e.url(),this.startTime=e.startTime,this.mainRequest=e}static forRequest(e){return Ui.get(e)||null}bindRequest(e){Ui.set(e,this)}static lastIdentifier=0}const Ui=new WeakMap;var Hi=Object.freeze({__proto__:null,PageLoad:Di});class qi extends c{layerTreeAgent;constructor(e){super(e),this.layerTreeAgent=e.layerTreeAgent()}async loadSnapshotFromFragments(e){const{snapshotId:t}=await this.layerTreeAgent.invoke_loadSnapshot({tiles:e});return t?new _i(this,t):null}loadSnapshot(e){const t={x:0,y:0,picture:e};return this.loadSnapshotFromFragments([t])}async makeSnapshot(e){const{snapshotId:t}=await this.layerTreeAgent.invoke_makeSnapshot({layerId:e});return t?new _i(this,t):null}}class _i{#td;#nd;#rd;constructor(e,t){this.#td=e,this.#nd=t,this.#rd=1}release(){console.assert(this.#rd>0,"release is already called on the object"),--this.#rd||this.#td.layerTreeAgent.invoke_releaseSnapshot({snapshotId:this.#nd})}addReference(){++this.#rd,console.assert(this.#rd>0,"Referencing a dead object")}async replay(e,t,n){return(await this.#td.layerTreeAgent.invoke_replaySnapshot({snapshotId:this.#nd,fromStep:t,toStep:n,scale:e||1})).dataURL}async profile(e){return(await this.#td.layerTreeAgent.invoke_profileSnapshot({snapshotId:this.#nd,minRepeatCount:5,minDuration:1,clipRect:e||void 0})).timings}async commandLog(){const e=await this.#td.layerTreeAgent.invoke_snapshotCommandLog({snapshotId:this.#nd});return e.commandLog?e.commandLog.map(((e,t)=>new zi(e,t))):null}}class zi{method;params;commandIndex;constructor(e,t){this.method=e.method,this.params=e.params,this.commandIndex=t}}c.register(qi,{capabilities:z.DOM,autostart:!1});var ji=Object.freeze({__proto__:null,PaintProfilerModel:qi,PaintProfilerSnapshot:_i,PaintProfilerLogItem:zi});class Wi extends c{#Ts;#sd;#id;constructor(e){super(e),this.#Ts=e.performanceAgent(),this.#sd=new Map([["TaskDuration","CumulativeTime"],["ScriptDuration","CumulativeTime"],["LayoutDuration","CumulativeTime"],["RecalcStyleDuration","CumulativeTime"],["LayoutCount","CumulativeCount"],["RecalcStyleCount","CumulativeCount"]]),this.#id=new Map}enable(){return this.#Ts.invoke_enable({})}disable(){return this.#Ts.invoke_disable()}async requestMetrics(){const e=await this.#Ts.invoke_getMetrics()||[],n=new Map,r=performance.now();for(const s of e.metrics){let e,i=this.#id.get(s.name);switch(i||(i={lastValue:void 0,lastTimestamp:void 0},this.#id.set(s.name,i)),this.#sd.get(s.name)){case"CumulativeTime":e=i.lastTimestamp&&i.lastValue?t.NumberUtilities.clamp(1e3*(s.value-i.lastValue)/(r-i.lastTimestamp),0,1):0,i.lastValue=s.value,i.lastTimestamp=r;break;case"CumulativeCount":e=i.lastTimestamp&&i.lastValue?Math.max(0,1e3*(s.value-i.lastValue)/(r-i.lastTimestamp)):0,i.lastValue=s.value,i.lastTimestamp=r;break;default:e=s.value}n.set(s.name,e)}return{metrics:n,timestamp:r}}}c.register(Wi,{capabilities:z.DOM,autostart:!1});var Vi,Gi=Object.freeze({__proto__:null,PerformanceMetricsModel:Wi});class Ki extends c{agent;loaderIds=[];targetJustAttached=!0;lastPrimaryPageModel=null;documents=new Map;getFeatureFlagsPromise;constructor(e){super(e),e.registerPreloadDispatcher(new $i(this)),this.agent=e.preloadAgent(),this.agent.invoke_enable(),this.getFeatureFlagsPromise=this.getFeatureFlags();const t=e.targetInfo();void 0!==t&&"prerender"===t.subtype&&(this.lastPrimaryPageModel=K.instance().primaryPageTarget()?.model(Ki)||null),K.instance().addModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this)}dispose(){super.dispose(),K.instance().removeModelListener(jn,_n.PrimaryPageChanged,this.onPrimaryPageChanged,this),this.agent.invoke_disable()}ensureDocumentPreloadingData(e){void 0===this.documents.get(e)&&this.documents.set(e,new Qi)}currentLoaderId(){if(this.targetJustAttached)return null;if(0===this.loaderIds.length)throw new Error("unreachable");return this.loaderIds[this.loaderIds.length-1]}currentDocument(){const e=this.currentLoaderId();return null===e?null:this.documents.get(e)||null}getRuleSetById(e){return this.currentDocument()?.ruleSets.getById(e)||null}getAllRuleSets(){return this.currentDocument()?.ruleSets.getAll()||[]}getPreloadingAttemptById(e){const t=this.currentDocument();return null===t?null:t.preloadingAttempts.getById(e,t.sources)||null}getPreloadingAttempts(e){const t=this.currentDocument();return null===t?[]:t.preloadingAttempts.getAll(e,t.sources)}getPreloadingAttemptsOfPreviousPage(){if(this.loaderIds.length<=1)return[];const e=this.documents.get(this.loaderIds[this.loaderIds.length-2]);return void 0===e?[]:e.preloadingAttempts.getAll(null,e.sources)}onPrimaryPageChanged(e){const{frame:t,type:n}=e.data;if(null===this.lastPrimaryPageModel&&"Activation"===n)return;if(null!==this.lastPrimaryPageModel&&"Activation"!==n)return;if(null!==this.lastPrimaryPageModel&&"Activation"===n){this.loaderIds=this.lastPrimaryPageModel.loaderIds;for(const[e,t]of this.lastPrimaryPageModel.documents.entries())this.ensureDocumentPreloadingData(e),this.documents.get(e)?.mergePrevious(t)}this.lastPrimaryPageModel=null;const r=t.loaderId;this.loaderIds.push(r),this.loaderIds=this.loaderIds.slice(-2),this.ensureDocumentPreloadingData(r);for(const e of this.documents.keys())this.loaderIds.includes(e)||this.documents.delete(e);this.dispatchEventToListeners(Vi.ModelUpdated)}onRuleSetUpdated(e){const t=e.ruleSet,n=t.loaderId;null===this.currentLoaderId()&&(this.loaderIds=[n],this.targetJustAttached=!1),this.ensureDocumentPreloadingData(n),this.documents.get(n)?.ruleSets.upsert(t),this.dispatchEventToListeners(Vi.ModelUpdated)}onRuleSetRemoved(e){const t=e.id;for(const e of this.documents.values())e.ruleSets.delete(t);this.dispatchEventToListeners(Vi.ModelUpdated)}onPreloadingAttemptSourcesUpdated(e){const t=e.loaderId;this.ensureDocumentPreloadingData(t);const n=this.documents.get(t);void 0!==n&&(n.sources.update(e.preloadingAttemptSources),n.preloadingAttempts.maybeRegisterNotTriggered(n.sources),this.dispatchEventToListeners(Vi.ModelUpdated))}onPrefetchStatusUpdated(e){const t=e.key.loaderId;this.ensureDocumentPreloadingData(t);const n={action:"Prefetch",key:e.key,status:Ji(e.status),prefetchStatus:e.prefetchStatus||null};this.documents.get(t)?.preloadingAttempts.upsert(n),this.dispatchEventToListeners(Vi.ModelUpdated)}onPrerenderStatusUpdated(e){const t=e.key.loaderId;this.ensureDocumentPreloadingData(t);const n={action:"Prerender",key:e.key,status:Ji(e.status),prerenderStatus:e.prerenderStatus||null};this.documents.get(t)?.preloadingAttempts.upsert(n),this.dispatchEventToListeners(Vi.ModelUpdated)}async getFeatureFlags(){const e=this.target().systemInfo().invoke_getFeatureState({featureState:"PreloadingHoldback"}),t=this.target().systemInfo().invoke_getFeatureState({featureState:"PrerenderHoldback"});return{preloadingHoldback:(await e).featureEnabled,prerender2Holdback:(await t).featureEnabled}}async onPreloadEnabledStateUpdated(e){const t=await this.getFeatureFlagsPromise,n={featureFlagPreloadingHoldback:t.preloadingHoldback,featureFlagPrerender2Holdback:t.prerender2Holdback,...e};this.dispatchEventToListeners(Vi.WarningsUpdated,n)}}c.register(Ki,{capabilities:z.DOM,autostart:!1}),function(e){e.ModelUpdated="ModelUpdated",e.WarningsUpdated="WarningsUpdated"}(Vi||(Vi={}));class $i{model;constructor(e){this.model=e}ruleSetUpdated(e){this.model.onRuleSetUpdated(e)}ruleSetRemoved(e){this.model.onRuleSetRemoved(e)}preloadingAttemptSourcesUpdated(e){this.model.onPreloadingAttemptSourcesUpdated(e)}prefetchStatusUpdated(e){this.model.onPrefetchStatusUpdated(e)}prerenderAttemptCompleted(e){}prerenderStatusUpdated(e){this.model.onPrerenderStatusUpdated(e)}preloadEnabledStateUpdated(e){this.model.onPreloadEnabledStateUpdated(e)}}class Qi{ruleSets=new Xi;preloadingAttempts=new Zi;sources=new ea;mergePrevious(e){if(!this.ruleSets.isEmpty()||!this.sources.isEmpty())throw new Error("unreachable");this.ruleSets=e.ruleSets,this.preloadingAttempts.mergePrevious(e.preloadingAttempts),this.sources=e.sources}}class Xi{map=new Map;isEmpty(){return 0===this.map.size}getById(e){return this.map.get(e)||null}getAll(){return Array.from(this.map.entries()).map((([e,t])=>({id:e,value:t})))}upsert(e){this.map.set(e.id,e)}delete(e){this.map.delete(e)}}function Ji(e){switch(e){case"Pending":return"Pending";case"Running":return"Running";case"Ready":return"Ready";case"Success":return"Success";case"Failure":return"Failure";case"NotSupported":return"NotSupported"}throw new Error("unreachable")}function Yi(e){let t,n;switch(e.action){case"Prefetch":t="Prefetch";break;case"Prerender":t="Prerender"}switch(e.targetHint){case void 0:n="undefined";break;case"Blank":n="Blank";break;case"Self":n="Self"}return`${e.loaderId}:${t}:${e.url}:${n}`}class Zi{map=new Map;enrich(e,t){let n=[],r=[];return null!==t&&(n=t.ruleSetIds,r=t.nodeIds),{...e,ruleSetIds:n,nodeIds:r}}getById(e,t){const n=this.map.get(e)||null;return null===n?null:this.enrich(n,t.getById(e))}getAll(e,t){return[...this.map.entries()].map((([e,n])=>({id:e,value:this.enrich(n,t.getById(e))}))).filter((({value:t})=>!e||t.ruleSetIds.includes(e)))}upsert(e){const t=Yi(e.key);this.map.set(t,e)}maybeRegisterNotTriggered(e){for(const[t,{key:n}]of e.entries()){if(void 0!==this.map.get(t))continue;let e;switch(n.action){case"Prefetch":e={action:"Prefetch",key:n,status:"NotTriggered",prefetchStatus:null};break;case"Prerender":e={action:"Prerender",key:n,status:"NotTriggered",prerenderStatus:null}}this.map.set(t,e)}}mergePrevious(e){for(const[t,n]of this.map.entries())e.map.set(t,n);this.map=e.map}}class ea{map=new Map;entries(){return this.map.entries()}isEmpty(){return 0===this.map.size}getById(e){return this.map.get(e)||null}update(e){this.map=new Map(e.map((e=>[Yi(e.key),e])))}}var ta=Object.freeze({__proto__:null,PreloadingModel:Ki,get Events(){return Vi}});class na extends c{#Ts;#ad;#od;constructor(e){super(e),this.#Ts=e.pageAgent(),this.#ad=null,this.#od=null,e.registerPageDispatcher(this)}startScreencast(e,t,n,r,s,i,a){this.#ad=i,this.#od=a,this.#Ts.invoke_startScreencast({format:e,quality:t,maxWidth:n,maxHeight:r,everyNthFrame:s})}stopScreencast(){this.#ad=null,this.#od=null,this.#Ts.invoke_stopScreencast()}async captureScreenshot(e,t,n,r){const s={format:e,quality:t,fromSurface:!0};switch(n){case"fromClip":s.captureBeyondViewport=!0,s.clip=r;break;case"fullpage":s.captureBeyondViewport=!0;break;case"fromViewport":s.captureBeyondViewport=!1;break;default:throw new Error("Unexpected or unspecified screnshotMode")}await vn.muteHighlight();const i=await this.#Ts.invoke_captureScreenshot(s);return await vn.unmuteHighlight(),i.data}async fetchLayoutMetrics(){const e=await this.#Ts.invoke_getLayoutMetrics();return e.getError()?null:{viewportX:e.cssVisualViewport.pageX,viewportY:e.cssVisualViewport.pageY,viewportScale:e.cssVisualViewport.scale,contentWidth:e.cssContentSize.width,contentHeight:e.cssContentSize.height}}screencastFrame({data:e,metadata:t,sessionId:n}){this.#Ts.invoke_screencastFrameAck({sessionId:n}),this.#ad&&this.#ad.call(null,e,t)}screencastVisibilityChanged({visible:e}){this.#od&&this.#od.call(null,e)}backForwardCacheNotUsed(e){}domContentEventFired(e){}loadEventFired(e){}lifecycleEvent(e){}navigatedWithinDocument(e){}frameAttached(e){}frameNavigated(e){}documentOpened(e){}frameDetached(e){}frameStartedLoading(e){}frameStoppedLoading(e){}frameRequestedNavigation(e){}frameScheduledNavigation(e){}frameClearedScheduledNavigation(e){}frameResized(){}javascriptDialogOpening(e){}javascriptDialogClosed(e){}interstitialShown(){}interstitialHidden(){}windowOpen(e){}fileChooserOpened(e){}compilationCacheProduced(e){}downloadWillBegin(e){}downloadProgress(){}prerenderAttemptCompleted(e){}prefetchStatusUpdated(e){}prerenderStatusUpdated(e){}}c.register(na,{capabilities:z.ScreenCapture,autostart:!1});var ra=Object.freeze({__proto__:null,ScreenCaptureModel:na});class sa extends c{enabled=!1;storageAgent;storageKeyManager;bucketsById=new Map;trackedStorageKeys=new Set;constructor(e){super(e),e.registerStorageDispatcher(this),this.storageAgent=e.storageAgent(),this.storageKeyManager=e.model(qn)}getBuckets(){return new Set(this.bucketsById.values())}getBucketsForStorageKey(e){const t=[...this.bucketsById.values()];return new Set(t.filter((({bucket:t})=>t.storageKey===e)))}getDefaultBucketForStorageKey(e){return[...this.bucketsById.values()].find((({bucket:t})=>t.storageKey===e&&void 0===t.name))??null}getBucketById(e){return this.bucketsById.get(e)??null}getBucketByName(e,t){if(!t)return this.getDefaultBucketForStorageKey(e);return[...this.bucketsById.values()].find((({bucket:n})=>n.storageKey===e&&n.name===t))??null}deleteBucket(e){this.storageAgent.invoke_deleteStorageBucket({bucket:e})}enable(){if(!this.enabled){if(this.storageKeyManager){this.storageKeyManager.addEventListener(Un.StorageKeyAdded,this.storageKeyAdded,this),this.storageKeyManager.addEventListener(Un.StorageKeyRemoved,this.storageKeyRemoved,this);for(const e of this.storageKeyManager.storageKeys())this.addStorageKey(e)}this.enabled=!0}}storageKeyAdded(e){this.addStorageKey(e.data)}storageKeyRemoved(e){this.removeStorageKey(e.data)}addStorageKey(e){if(this.trackedStorageKeys.has(e))throw new Error("Can't call addStorageKey for a storage key if it has already been added.");this.trackedStorageKeys.add(e),this.storageAgent.invoke_setStorageBucketTracking({storageKey:e,enable:!0})}removeStorageKey(e){if(!this.trackedStorageKeys.has(e))throw new Error("Can't call removeStorageKey for a storage key if it hasn't already been added.");const t=this.getBucketsForStorageKey(e);for(const e of t)this.bucketRemoved(e);this.trackedStorageKeys.delete(e),this.storageAgent.invoke_setStorageBucketTracking({storageKey:e,enable:!1})}bucketAdded(e){this.bucketsById.set(e.id,e),this.dispatchEventToListeners("BucketAdded",{model:this,bucketInfo:e})}bucketRemoved(e){this.bucketsById.delete(e.id),this.dispatchEventToListeners("BucketRemoved",{model:this,bucketInfo:e})}bucketChanged(e){this.dispatchEventToListeners("BucketChanged",{model:this,bucketInfo:e})}bucketInfosAreEqual(e,t){return e.bucket.storageKey===t.bucket.storageKey&&e.id===t.id&&e.bucket.name===t.bucket.name&&e.expiration===t.expiration&&e.quota===t.quota&&e.persistent===t.persistent&&e.durability===t.durability}storageBucketCreatedOrUpdated({bucketInfo:e}){const t=this.getBucketById(e.id);t?this.bucketInfosAreEqual(t,e)||this.bucketChanged(e):this.bucketAdded(e)}storageBucketDeleted({bucketId:e}){const t=this.getBucketById(e);if(!t)throw new Error(`Received an event that Storage Bucket '${e}' was deleted, but it wasn't in the StorageBucketsModel.`);this.bucketRemoved(t)}interestGroupAccessed(e){}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}cacheStorageListUpdated(e){}cacheStorageContentUpdated(e){}sharedStorageAccessed(e){}}c.register(sa,{capabilities:z.Storage,autostart:!1});var ia=Object.freeze({__proto__:null,StorageBucketsModel:sa});const aa={serviceworkercacheagentError:"`ServiceWorkerCacheAgent` error deleting cache entry {PH1} in cache: {PH2}"},oa=s.i18n.registerUIStrings("core/sdk/ServiceWorkerCacheModel.ts",aa),la=s.i18n.getLocalizedString.bind(void 0,oa);class da extends c{cacheAgent;#ld;#dd;#cd=new Map;#hd=new Set;#ud=new Set;#gd=new e.Throttler.Throttler(2e3);#ma=!1;#pd=!1;constructor(e){super(e),e.registerStorageDispatcher(this),this.cacheAgent=e.cacheStorageAgent(),this.#ld=e.storageAgent(),this.#dd=e.model(sa)}enable(){if(!this.#ma){this.#dd.addEventListener("BucketAdded",this.storageBucketAdded,this),this.#dd.addEventListener("BucketRemoved",this.storageBucketRemoved,this);for(const e of this.#dd.getBuckets())this.addStorageBucket(e.bucket);this.#ma=!0}}clearForStorageKey(e){for(const[t,n]of this.#cd.entries())n.storageKey===e&&(this.#cd.delete(t),this.cacheRemoved(n));for(const t of this.#dd.getBucketsForStorageKey(e))this.loadCacheNames(t.bucket)}refreshCacheNames(){for(const e of this.#cd.values())this.cacheRemoved(e);this.#cd.clear();const e=this.#dd.getBuckets();for(const t of e)this.loadCacheNames(t.bucket)}async deleteCache(e){const t=await this.cacheAgent.invoke_deleteCache({cacheId:e.cacheId});t.getError()?console.error(`ServiceWorkerCacheAgent error deleting cache ${e.toString()}: ${t.getError()}`):(this.#cd.delete(e.cacheId),this.cacheRemoved(e))}async deleteCacheEntry(t,n){const r=await this.cacheAgent.invoke_deleteEntry({cacheId:t.cacheId,request:n});r.getError()&&e.Console.Console.instance().error(la(aa.serviceworkercacheagentError,{PH1:t.toString(),PH2:String(r.getError())}))}loadCacheData(e,t,n,r,s){this.requestEntries(e,t,n,r,s)}loadAllCacheData(e,t,n){this.requestAllEntries(e,t,n)}caches(){const e=new Array;for(const t of this.#cd.values())e.push(t);return e}dispose(){for(const e of this.#cd.values())this.cacheRemoved(e);this.#cd.clear(),this.#ma&&(this.#dd.removeEventListener("BucketAdded",this.storageBucketAdded,this),this.#dd.removeEventListener("BucketRemoved",this.storageBucketRemoved,this))}addStorageBucket(e){this.loadCacheNames(e),this.#hd.has(e.storageKey)||(this.#hd.add(e.storageKey),this.#ld.invoke_trackCacheStorageForStorageKey({storageKey:e.storageKey}))}removeStorageBucket(e){let t=0;for(const[n,r]of this.#cd.entries())e.storageKey===r.storageKey&&t++,r.inBucket(e)&&(t--,this.#cd.delete(n),this.cacheRemoved(r));0===t&&(this.#hd.delete(e.storageKey),this.#ld.invoke_untrackCacheStorageForStorageKey({storageKey:e.storageKey}))}async loadCacheNames(e){const t=await this.cacheAgent.invoke_requestCacheNames({storageBucket:e});t.getError()||this.updateCacheNames(e,t.caches)}updateCacheNames(e,t){const n=new Set,r=new Map,s=new Map;for(const e of t){const t=e.storageBucket??this.#dd.getDefaultBucketForStorageKey(e.storageKey)?.bucket;if(!t)continue;const s=new ha(this,t,e.cacheName,e.cacheId);n.add(s.cacheId),this.#cd.has(s.cacheId)||(r.set(s.cacheId,s),this.#cd.set(s.cacheId,s))}this.#cd.forEach((function(t){t.inBucket(e)&&!n.has(t.cacheId)&&(s.set(t.cacheId,t),this.#cd.delete(t.cacheId))}),this),r.forEach(this.cacheAdded,this),s.forEach(this.cacheRemoved,this)}storageBucketAdded({data:{bucketInfo:{bucket:e}}}){this.addStorageBucket(e)}storageBucketRemoved({data:{bucketInfo:{bucket:e}}}){this.removeStorageBucket(e)}cacheAdded(e){this.dispatchEventToListeners(ca.CacheAdded,{model:this,cache:e})}cacheRemoved(e){this.dispatchEventToListeners(ca.CacheRemoved,{model:this,cache:e})}async requestEntries(e,t,n,r,s){const i=await this.cacheAgent.invoke_requestEntries({cacheId:e.cacheId,skipCount:t,pageSize:n,pathFilter:r});i.getError()?console.error("ServiceWorkerCacheAgent error while requesting entries: ",i.getError()):s(i.cacheDataEntries,i.returnCount)}async requestAllEntries(e,t,n){const r=await this.cacheAgent.invoke_requestEntries({cacheId:e.cacheId,pathFilter:t});r.getError()?console.error("ServiceWorkerCacheAgent error while requesting entries: ",r.getError()):n(r.cacheDataEntries,r.returnCount)}cacheStorageListUpdated({bucketId:e}){const t=this.#dd.getBucketById(e)?.bucket;t&&(this.#ud.add(t),this.#gd.schedule((()=>{const e=Array.from(this.#ud,(e=>this.loadCacheNames(e)));return this.#ud.clear(),Promise.all(e)}),this.#pd))}cacheStorageContentUpdated({bucketId:e,cacheName:t}){const n=this.#dd.getBucketById(e)?.bucket;n&&this.dispatchEventToListeners(ca.CacheStorageContentUpdated,{storageBucket:n,cacheName:t})}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}interestGroupAccessed(e){}sharedStorageAccessed(e){}storageBucketCreatedOrUpdated(e){}storageBucketDeleted(e){}setThrottlerSchedulesAsSoonAsPossibleForTest(){this.#pd=!0}}var ca;!function(e){e.CacheAdded="CacheAdded",e.CacheRemoved="CacheRemoved",e.CacheStorageContentUpdated="CacheStorageContentUpdated"}(ca||(ca={}));class ha{#$r;storageKey;storageBucket;cacheName;cacheId;constructor(e,t,n,r){this.#$r=e,this.storageBucket=t,this.storageKey=t.storageKey,this.cacheName=n,this.cacheId=r}inBucket(e){return this.storageKey===e.storageKey&&this.storageBucket.name===e.name}equals(e){return this.cacheId===e.cacheId}toString(){return this.storageKey+this.cacheName}async requestCachedResponse(e,t){const n=await this.#$r.cacheAgent.invoke_requestCachedResponse({cacheId:this.cacheId,requestURL:e,requestHeaders:t});return n.getError()?null:n.response}}c.register(da,{capabilities:z.Storage,autostart:!1});var ua=Object.freeze({__proto__:null,ServiceWorkerCacheModel:da,get Events(){return ca},Cache:ha});const ga={running:"running",starting:"starting",stopped:"stopped",stopping:"stopping",activated:"activated",activating:"activating",installed:"installed",installing:"installing",new:"new",redundant:"redundant",sSS:"{PH1} #{PH2} ({PH3})"},pa=s.i18n.registerUIStrings("core/sdk/ServiceWorkerManager.ts",ga),ma=s.i18n.getLocalizedString.bind(void 0,pa),fa=s.i18n.getLazilyComputedLocalizedString.bind(void 0,pa);class ba extends c{#Ts;#md;#ma;#fd;serviceWorkerNetworkRequestsPanelStatus;constructor(t){super(t),t.registerServiceWorkerDispatcher(new va(this)),this.#Ts=t.serviceWorkerAgent(),this.#md=new Map,this.#ma=!1,this.enable(),this.#fd=e.Settings.Settings.instance().createSetting("serviceWorkerUpdateOnReload",!1),this.#fd.get()&&this.forceUpdateSettingChanged(),this.#fd.addChangeListener(this.forceUpdateSettingChanged,this),new wa(t,this),this.serviceWorkerNetworkRequestsPanelStatus={isOpen:!1,openedAt:0}}async enable(){this.#ma||(this.#ma=!0,await this.#Ts.invoke_enable())}async disable(){this.#ma&&(this.#ma=!1,this.#md.clear(),await this.#Ts.invoke_enable())}registrations(){return this.#md}hasRegistrationForURLs(e){for(const t of this.#md.values())if(e.filter((e=>e&&e.startsWith(t.scopeURL))).length===e.length)return!0;return!1}findVersion(e){for(const t of this.registrations().values()){const n=t.versions.get(e);if(n)return n}return null}deleteRegistration(e){const t=this.#md.get(e);if(t){if(t.isRedundant())return this.#md.delete(e),void this.dispatchEventToListeners(ya.RegistrationDeleted,t);t.deleting=!0;for(const e of t.versions.values())this.stopWorker(e.id);this.unregister(t.scopeURL)}}async updateRegistration(e){const t=this.#md.get(e);t&&await this.#Ts.invoke_updateRegistration({scopeURL:t.scopeURL})}async deliverPushMessage(t,n){const r=this.#md.get(t);if(!r)return;const s=e.ParsedURL.ParsedURL.extractOrigin(r.scopeURL);await this.#Ts.invoke_deliverPushMessage({origin:s,registrationId:t,data:n})}async dispatchSyncEvent(t,n,r){const s=this.#md.get(t);if(!s)return;const i=e.ParsedURL.ParsedURL.extractOrigin(s.scopeURL);await this.#Ts.invoke_dispatchSyncEvent({origin:i,registrationId:t,tag:n,lastChance:r})}async dispatchPeriodicSyncEvent(t,n){const r=this.#md.get(t);if(!r)return;const s=e.ParsedURL.ParsedURL.extractOrigin(r.scopeURL);await this.#Ts.invoke_dispatchPeriodicSyncEvent({origin:s,registrationId:t,tag:n})}async unregister(e){await this.#Ts.invoke_unregister({scopeURL:e})}async startWorker(e){await this.#Ts.invoke_startWorker({scopeURL:e})}async skipWaiting(e){await this.#Ts.invoke_skipWaiting({scopeURL:e})}async stopWorker(e){await this.#Ts.invoke_stopWorker({versionId:e})}async inspectWorker(e){await this.#Ts.invoke_inspectWorker({versionId:e})}workerRegistrationUpdated(e){for(const t of e){let e=this.#md.get(t.registrationId);e?(e.update(t),e.shouldBeRemoved()?(this.#md.delete(e.id),this.dispatchEventToListeners(ya.RegistrationDeleted,e)):this.dispatchEventToListeners(ya.RegistrationUpdated,e)):(e=new Sa(t),this.#md.set(t.registrationId,e),this.dispatchEventToListeners(ya.RegistrationUpdated,e))}}workerVersionUpdated(e){const t=new Set;for(const n of e){const e=this.#md.get(n.registrationId);e&&(e.updateVersion(n),t.add(e))}for(const e of t)e.shouldBeRemoved()?(this.#md.delete(e.id),this.dispatchEventToListeners(ya.RegistrationDeleted,e)):this.dispatchEventToListeners(ya.RegistrationUpdated,e)}workerErrorReported(e){const t=this.#md.get(e.registrationId);t&&(t.errors.push(e),this.dispatchEventToListeners(ya.RegistrationErrorAdded,{registration:t,error:e}))}forceUpdateOnReloadSetting(){return this.#fd}forceUpdateSettingChanged(){const e=this.#fd.get();this.#Ts.invoke_setForceUpdateOnPageLoad({forceUpdateOnPageLoad:e})}}var ya;!function(e){e.RegistrationUpdated="RegistrationUpdated",e.RegistrationErrorAdded="RegistrationErrorAdded",e.RegistrationDeleted="RegistrationDeleted"}(ya||(ya={}));class va{#$;constructor(e){this.#$=e}workerRegistrationUpdated({registrations:e}){this.#$.workerRegistrationUpdated(e)}workerVersionUpdated({versions:e}){this.#$.workerVersionUpdated(e)}workerErrorReported({errorMessage:e}){this.#$.workerErrorReported(e)}}class Ia{runningStatus;status;last_updated_timestamp;previousState;constructor(e,t,n,r){this.runningStatus=e,this.status=t,this.last_updated_timestamp=r,this.previousState=n}}class ka{id;scriptURL;parsedURL;securityOrigin;scriptLastModified;scriptResponseTime;controlledClients;targetId;currentState;registration;constructor(e,t){this.registration=e,this.update(t)}update(t){this.id=t.versionId,this.scriptURL=t.scriptURL;const n=new e.ParsedURL.ParsedURL(t.scriptURL);this.securityOrigin=n.securityOrigin(),this.currentState=new Ia(t.runningStatus,t.status,this.currentState,Date.now()),this.scriptLastModified=t.scriptLastModified,this.scriptResponseTime=t.scriptResponseTime,t.controlledClients?this.controlledClients=t.controlledClients.slice():this.controlledClients=[],this.targetId=t.targetId||null}isStartable(){return!this.registration.isDeleted&&this.isActivated()&&this.isStopped()}isStoppedAndRedundant(){return"stopped"===this.runningStatus&&"redundant"===this.status}isStopped(){return"stopped"===this.runningStatus}isStarting(){return"starting"===this.runningStatus}isRunning(){return"running"===this.runningStatus}isStopping(){return"stopping"===this.runningStatus}isNew(){return"new"===this.status}isInstalling(){return"installing"===this.status}isInstalled(){return"installed"===this.status}isActivating(){return"activating"===this.status}isActivated(){return"activated"===this.status}isRedundant(){return"redundant"===this.status}get status(){return this.currentState.status}get runningStatus(){return this.currentState.runningStatus}mode(){return this.isNew()||this.isInstalling()?ka.Modes.Installing:this.isInstalled()?ka.Modes.Waiting:this.isActivating()||this.isActivated()?ka.Modes.Active:ka.Modes.Redundant}}!function(e){let t;e.RunningStatus={running:fa(ga.running),starting:fa(ga.starting),stopped:fa(ga.stopped),stopping:fa(ga.stopping)},e.Status={activated:fa(ga.activated),activating:fa(ga.activating),installed:fa(ga.installed),installing:fa(ga.installing),new:fa(ga.new),redundant:fa(ga.redundant)},function(e){e.Installing="installing",e.Waiting="waiting",e.Active="active",e.Redundant="redundant"}(t=e.Modes||(e.Modes={}))}(ka||(ka={}));class Sa{#bd;id;scopeURL;securityOrigin;isDeleted;versions;deleting;errors;constructor(e){this.update(e),this.versions=new Map,this.deleting=!1,this.errors=[]}update(t){this.#bd=Symbol("fingerprint"),this.id=t.registrationId,this.scopeURL=t.scopeURL;const n=new e.ParsedURL.ParsedURL(t.scopeURL);this.securityOrigin=n.securityOrigin(),this.isDeleted=t.isDeleted}fingerprint(){return this.#bd}versionsByMode(){const e=new Map;for(const t of this.versions.values())e.set(t.mode(),t);return e}updateVersion(e){this.#bd=Symbol("fingerprint");let t=this.versions.get(e.versionId);return t?(t.update(e),t):(t=new ka(this,e),this.versions.set(e.versionId,t),t)}isRedundant(){for(const e of this.versions.values())if(!e.isStoppedAndRedundant())return!1;return!0}shouldBeRemoved(){return this.isRedundant()&&(!this.errors.length||this.deleting)}canBeRemoved(){return this.isDeleted||this.deleting}clearErrors(){this.#bd=Symbol("fingerprint"),this.errors=[]}}class wa{#h;#yd;#vd;constructor(e,t){this.#h=e,this.#yd=t,this.#vd=new Map,t.addEventListener(ya.RegistrationUpdated,this.registrationsUpdated,this),t.addEventListener(ya.RegistrationDeleted,this.registrationsUpdated,this),K.instance().addModelListener(Cr,Rr.ExecutionContextCreated,this.executionContextCreated,this)}registrationsUpdated(){this.#vd.clear();const e=this.#yd.registrations().values();for(const t of e)for(const e of t.versions.values())e.targetId&&this.#vd.set(e.targetId,e);this.updateAllContextLabels()}executionContextCreated(e){const t=e.data,n=this.serviceWorkerTargetId(t.target());n&&this.updateContextLabel(t,this.#vd.get(n)||null)}serviceWorkerTargetId(e){return e.parentTarget()!==this.#h||e.type()!==_.ServiceWorker?null:e.id()}updateAllContextLabels(){for(const e of K.instance().targets()){const t=this.serviceWorkerTargetId(e);if(!t)continue;const n=this.#vd.get(t)||null,r=e.model(Cr),s=r?r.executionContexts():[];for(const e of s)this.updateContextLabel(e,n)}}updateContextLabel(t,n){if(!n)return void t.setLabel("");const r=e.ParsedURL.ParsedURL.fromString(t.origin),s=r?r.lastPathComponentWithFragment():t.name,i=ka.Status[n.status];t.setLabel(ma(ga.sSS,{PH1:s,PH2:n.id,PH3:i()}))}}c.register(ba,{capabilities:z.ServiceWorker,autostart:!0});var Ca=Object.freeze({__proto__:null,ServiceWorkerManager:ba,get Events(){return ya},ServiceWorkerVersionState:Ia,get ServiceWorkerVersion(){return ka},ServiceWorkerRegistration:Sa});const Ta=new Map,Ra=new Map;async function xa(e,t){const n=Ta.get(e)?.get(t);if(void 0!==n)return n;const r=K.instance().primaryPageTarget()?.model(Pn);if(!r)return null;const s=(await r.pushNodesByBackendIdsToFrontend(new Set([t])))?.get(t)||null,i=Ta.get(e)||new Map;return i.set(t,s),Ta.set(e,i),s}const Ma=new Map,Pa=new Map;var La=Object.freeze({__proto__:null,_TEST_clearCache:function(){Ta.clear(),Ra.clear(),Ma.clear(),Pa.clear()},domNodeForBackendNodeID:xa,domNodesForMultipleBackendNodeIds:async function(e,t){const n=Ra.get(e)?.get(t);if(n)return n;const r=K.instance().primaryPageTarget()?.model(Pn);if(!r)return new Map;const s=await r.pushNodesByBackendIdsToFrontend(t)||new Map,i=Ra.get(e)||new Map;return i.set(t,s),Ra.set(e,i),s},sourcesForLayoutShift:async function(e,t){const n=Ma.get(e)?.get(t);if(n)return n;const r=t.args.data?.impacted_nodes;if(!r)return[];const s=[];await Promise.all(r.map((async t=>{const n=await xa(e,t.node_id);n&&s.push({previousRect:new DOMRect(t.old_rect[0],t.old_rect[1],t.old_rect[2],t.old_rect[3]),currentRect:new DOMRect(t.new_rect[0],t.new_rect[1],t.new_rect[2],t.new_rect[3]),node:n})})));const i=Ma.get(e)||new Map;return i.set(t,s),Ma.set(e,i),s},normalizedImpactedNodesForLayoutShift:async function(e,t){const n=Pa.get(e)?.get(t);if(n)return n;const r=t.args?.data?.impacted_nodes;if(!r)return[];let s=null;const i=K.instance().primaryPageTarget(),a=await(i?.runtimeAgent().invoke_evaluate({expression:"window.devicePixelRatio"}));if("number"===a?.result.type&&(s=a?.result.value??null),!s)return r;const o=[];for(const e of r){const t={...e};for(let n=0;n{setTimeout((()=>e(void 0)),1e3)}))]):void 0,n=Ts.instance().cpuThrottlingRate(),r=ue.instance().networkConditions(),s="function"==typeof r.title?r.title():r.title;return{source:"DevTools",startTime:e?new Date(e).toJSON():void 0,cpuThrottling:n,networkThrottling:s,hardwareConcurrency:t}}catch{return}}});class Ea extends c{#Id;#kd;#Sd;#wd;#Cd;constructor(e){super(e),this.#Id=e.tracingAgent(),e.registerTracingDispatcher(new Aa(this)),this.#kd=null,this.#Sd=0,this.#wd=0}bufferUsage(e,t,n){this.#Sd=void 0===t?null:t,this.#kd&&this.#kd.tracingBufferUsage(e||n||0)}eventsCollected(e){this.#kd&&(this.#kd.traceEventsCollected(e),this.#wd+=e.length,this.#Sd?(this.#wd>this.#Sd&&(this.#wd=this.#Sd),this.#kd.eventsRetrievalProgress(this.#wd/this.#Sd)):this.#kd.eventsRetrievalProgress(0))}tracingComplete(){this.#Sd=0,this.#wd=0,this.#kd&&(this.#kd.tracingComplete(),this.#kd=null),this.#Cd=!1}async start(e,t,n){if(this.#kd)throw new Error("Tracing is already started");this.#kd=e;const r={bufferUsageReportingInterval:500,categories:t,options:n,transferMode:"ReportEvents"},s=await this.#Id.invoke_start(r);return s.getError()&&(this.#kd=null),s}stop(){if(!this.#kd)throw new Error("Tracing is not started");if(this.#Cd)throw new Error("Tracing is already being stopped");this.#Cd=!0,this.#Id.invoke_end()}}class Aa{#Td;constructor(e){this.#Td=e}bufferUsage({value:e,eventCount:t,percentFull:n}){this.#Td.bufferUsage(e,t,n)}dataCollected({value:e}){this.#Td.eventsCollected(e)}tracingComplete(){this.#Td.tracingComplete()}}c.register(Ea,{capabilities:z.Tracing,autostart:!1});var Oa=Object.freeze({__proto__:null,TracingManager:Ea});class Na extends c{#Ts;constructor(e){super(e),this.#Ts=e.webAuthnAgent(),e.registerWebAuthnDispatcher(new Fa(this))}setVirtualAuthEnvEnabled(e){return e?this.#Ts.invoke_enable({enableUI:!0}):this.#Ts.invoke_disable()}async addAuthenticator(e){return(await this.#Ts.invoke_addVirtualAuthenticator({options:e})).authenticatorId}async removeAuthenticator(e){await this.#Ts.invoke_removeVirtualAuthenticator({authenticatorId:e})}async setAutomaticPresenceSimulation(e,t){await this.#Ts.invoke_setAutomaticPresenceSimulation({authenticatorId:e,enabled:t})}async getCredentials(e){return(await this.#Ts.invoke_getCredentials({authenticatorId:e})).credentials}async removeCredential(e,t){await this.#Ts.invoke_removeCredential({authenticatorId:e,credentialId:t})}credentialAdded(e){this.dispatchEventToListeners("CredentialAdded",e)}credentialAsserted(e){this.dispatchEventToListeners("CredentialAsserted",e)}}class Fa{#$r;constructor(e){this.#$r=e}credentialAdded(e){this.#$r.credentialAdded(e)}credentialAsserted(e){this.#$r.credentialAsserted(e)}}c.register(Na,{capabilities:z.WebAuthn,autostart:!1});var Ba=Object.freeze({__proto__:null,WebAuthnModel:Na});export{Nr as AccessibilityModel,vs as CPUProfileDataModel,ss as CPUProfilerModel,Ms as CPUThrottlingManager,Qe as CSSContainerQuery,ze as CSSFontFace,Je as CSSLayer,wt as CSSMatchedStyles,tt as CSSMedia,E as CSSMetadata,hn as CSSModel,lt as CSSProperty,Fs as CSSPropertyParser,We as CSSQuery,yt as CSSRule,rt as CSSScope,ct as CSSStyleDeclaration,Mt as CSSStyleSheetHeader,it as CSSSupports,Br as CategorizedBreakpoint,Vr as ChildTargetManager,Jr as CompilerSourceMappingContentProvider,jr as Connections,ms as ConsoleModel,U as Cookie,bs as CookieModel,j as CookieParser,$s as DOMDebuggerModel,On as DOMModel,Ir as DebuggerModel,ws as EmulationModel,ni as EventBreakpointsModel,Ci as FilmStripModel,Ti as FrameAssociated,At as FrameManager,wr as HeapProfilerModel,Nt as IOModel,Ai as IsolateManager,Fi as IssuesModel,Bi as LayerTreeBase,as as LogModel,me as NetworkManager,Pe as NetworkRequest,gn as OverlayColorGenerator,Cn as OverlayModel,mn as OverlayPersistentHighlighter,Hi as PageLoad,zt as PageResourceLoader,ji as PaintProfiler,Gi as PerformanceMetricsModel,ta as PreloadingModel,N as ProfileTreeModel,qe as RemoteObject,Bn as Resource,Kn as ResourceTreeModel,Er as RuntimeModel,h as SDKModel,ra as ScreenCaptureModel,tr as Script,Hn as SecurityOriginManager,Ie as ServerTiming,ua as ServiceWorkerCacheModel,Ca as ServiceWorkerManager,Xt as SourceMap,Zt as SourceMapManager,ia as StorageBucketsModel,zn as StorageKeyManager,V as Target,Q as TargetManager,La as TraceSDKServices,Oa as TracingManager,Ii as TracingModel,Ba as WebAuthnModel}; diff --git a/packages/debugger-frontend/package.json b/packages/debugger-frontend/package.json index 4c100152f8edbf..0d42d555212e39 100644 --- a/packages/debugger-frontend/package.json +++ b/packages/debugger-frontend/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/debugger-frontend", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Debugger frontend for React Native based on Chrome DevTools", "keywords": [ "react-native", @@ -10,7 +10,7 @@ "bugs": "https://github.com/facebook/react-native/issues", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/debugger-frontend" }, "license": "BSD-3-Clause", diff --git a/packages/dev-middleware/package.json b/packages/dev-middleware/package.json index f1700a2fcf8760..dafb0ac74dacb1 100644 --- a/packages/dev-middleware/package.json +++ b/packages/dev-middleware/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/dev-middleware", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Dev server middleware for React Native", "keywords": [ "react-native", @@ -10,7 +10,7 @@ "bugs": "https://github.com/facebook/react-native/issues", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/dev-middleware" }, "license": "MIT", @@ -23,7 +23,7 @@ ], "dependencies": { "@isaacs/ttlcache": "^1.4.1", - "@react-native/debugger-frontend": "0.74.0", + "@react-native/debugger-frontend": "0.75.0-main", "@rnx-kit/chromium-edge-launcher": "^1.0.0", "chrome-launcher": "^0.15.2", "connect": "^3.6.5", diff --git a/packages/dev-middleware/src/__tests__/InspectorProxyCustomMessageHandler-test.js b/packages/dev-middleware/src/__tests__/InspectorProxyCustomMessageHandler-test.js new file mode 100644 index 00000000000000..5f3f8b7798d875 --- /dev/null +++ b/packages/dev-middleware/src/__tests__/InspectorProxyCustomMessageHandler-test.js @@ -0,0 +1,310 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import {createAndConnectTarget} from './InspectorProtocolUtils'; +import {withAbortSignalForEachTest} from './ResourceUtils'; +import {baseUrlForServer, createServer} from './ServerUtils'; +import until from 'wait-for-expect'; + +// WebSocket is unreliable when using fake timers. +jest.useRealTimers(); + +jest.setTimeout(10000); + +describe('inspector proxy device message middleware', () => { + const autoCleanup = withAbortSignalForEachTest(); + const page = { + id: 'page1', + app: 'bar-app', + title: 'bar-title', + vm: 'bar-vm', + }; + + afterEach(() => { + jest.clearAllMocks(); + }); + + test('middleware is created with device, debugger, and page information', async () => { + const createCustomMessageHandler = jest.fn().mockImplementation(() => null); + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: createCustomMessageHandler, + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Ensure the middleware was created with the device information + await until(() => + expect(createCustomMessageHandler).toBeCalledWith( + expect.objectContaining({ + page: expect.objectContaining({ + ...page, + capabilities: expect.any(Object), + }), + device: expect.objectContaining({ + appId: expect.any(String), + id: expect.any(String), + name: expect.any(String), + sendMessage: expect.any(Function), + }), + debugger: expect.objectContaining({ + userAgent: null, + sendMessage: expect.any(Function), + }), + }), + ), + ); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); + + test('send message functions are passing messages to sockets', async () => { + const handleDebuggerMessage = jest.fn(); + const handleDeviceMessage = jest.fn(); + const createCustomMessageHandler = jest.fn().mockImplementation(() => ({ + handleDebuggerMessage, + handleDeviceMessage, + })); + + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: createCustomMessageHandler, + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Ensure the middleware was created with the send message methods + await until(() => + expect(createCustomMessageHandler).toBeCalledWith( + expect.objectContaining({ + device: expect.objectContaining({ + sendMessage: expect.any(Function), + }), + debugger: expect.objectContaining({ + sendMessage: expect.any(Function), + }), + }), + ), + ); + + // Send a message to the device + createCustomMessageHandler.mock.calls[0][0].device.sendMessage({ + id: 1, + }); + // Ensure the device received the message + await until(() => + expect(device.wrappedEvent).toBeCalledWith({ + event: 'wrappedEvent', + payload: { + pageId: page.id, + wrappedEvent: JSON.stringify({id: 1}), + }, + }), + ); + + // Send a message to the debugger + createCustomMessageHandler.mock.calls[0][0].debugger.sendMessage({ + id: 2, + }); + // Ensure the debugger received the message + await until(() => + expect(debugger_.handle).toBeCalledWith({ + id: 2, + }), + ); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); + + test('device message is passed to message middleware', async () => { + const handleDeviceMessage = jest.fn(); + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: () => ({ + handleDeviceMessage, + handleDebuggerMessage() {}, + }), + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Send a message from the device, and ensure the middleware received it + device.sendWrappedEvent(page.id, {id: 1337}); + + // Ensure the debugger received the message + await until(() => expect(debugger_.handle).toBeCalledWith({id: 1337})); + // Ensure the middleware received the message + await until(() => expect(handleDeviceMessage).toBeCalled()); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); + + test('device message stops propagating when handled by middleware', async () => { + const handleDeviceMessage = jest.fn(); + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: () => ({ + handleDeviceMessage, + handleDebuggerMessage() {}, + }), + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Stop the first message from propagating by returning true (once) from middleware + handleDeviceMessage.mockReturnValueOnce(true); + + // Send the first message which should NOT be received by the debugger + device.sendWrappedEvent(page.id, {id: -1}); + await until(() => expect(handleDeviceMessage).toBeCalled()); + + // Send the second message which should be received by the debugger + device.sendWrappedEvent(page.id, {id: 1337}); + + // Ensure only the last message was received by the debugger + await until(() => expect(debugger_.handle).toBeCalledWith({id: 1337})); + // Ensure the first message was not received by the debugger + expect(debugger_.handle).not.toBeCalledWith({id: -1}); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); + + test('debugger message is passed to message middleware', async () => { + const handleDebuggerMessage = jest.fn(); + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: () => ({ + handleDeviceMessage() {}, + handleDebuggerMessage, + }), + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Send a message from the debugger + const message = { + method: 'Runtime.enable', + id: 1337, + }; + debugger_.send(message); + + // Ensure the device received the message + await until(() => expect(device.wrappedEvent).toBeCalled()); + // Ensure the middleware received the message + await until(() => expect(handleDebuggerMessage).toBeCalledWith(message)); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); + + test('debugger message stops propagating when handled by middleware', async () => { + const handleDebuggerMessage = jest.fn(); + const {server} = await createServer({ + logger: undefined, + projectRoot: '', + unstable_customInspectorMessageHandler: () => ({ + handleDeviceMessage() {}, + handleDebuggerMessage, + }), + }); + + let device, debugger_; + try { + ({device, debugger_} = await createAndConnectTarget( + serverRefUrls(server), + autoCleanup.signal, + page, + )); + + // Stop the first message from propagating by returning true (once) from middleware + handleDebuggerMessage.mockReturnValueOnce(true); + + // Send the first emssage which should not be received by the device + debugger_.send({id: -1}); + // Send the second message which should be received by the device + debugger_.send({id: 1337}); + + // Ensure only the last message was received by the device + await until(() => + expect(device.wrappedEvent).toBeCalledWith({ + event: 'wrappedEvent', + payload: {pageId: page.id, wrappedEvent: JSON.stringify({id: 1337})}, + }), + ); + // Ensure the first message was not received by the device + expect(device.wrappedEvent).not.toBeCalledWith({id: -1}); + } finally { + device?.close(); + debugger_?.close(); + await closeServer(server); + } + }); +}); + +function serverRefUrls(server: http$Server | https$Server) { + return { + serverBaseUrl: baseUrlForServer(server, 'http'), + serverBaseWsUrl: baseUrlForServer(server, 'ws'), + }; +} + +async function closeServer(server: http$Server | https$Server): Promise { + return new Promise(resolve => server.close(() => resolve())); +} diff --git a/packages/dev-middleware/src/__tests__/InspectorProxyHttpApi-test.js b/packages/dev-middleware/src/__tests__/InspectorProxyHttpApi-test.js index e601f219f06324..e5501b8e3ceb66 100644 --- a/packages/dev-middleware/src/__tests__/InspectorProxyHttpApi-test.js +++ b/packages/dev-middleware/src/__tests__/InspectorProxyHttpApi-test.js @@ -14,11 +14,13 @@ import type { JsonVersionResponse, } from '../inspector-proxy/types'; -import {fetchJson} from './FetchUtils'; +import {fetchJson, fetchLocal} from './FetchUtils'; import {createDeviceMock} from './InspectorDeviceUtils'; import {withAbortSignalForEachTest} from './ResourceUtils'; import {withServerForEachTest} from './ServerUtils'; +import nullthrows from 'nullthrows'; + // Must be greater than or equal to PAGES_POLLING_INTERVAL in `InspectorProxy.js`. const PAGES_POLLING_DELAY = 1000; @@ -309,5 +311,67 @@ describe('inspector proxy HTTP API', () => { } }); }); + + test('handles Unicode data safely', async () => { + const device = await createDeviceMock( + `${serverRef.serverBaseWsUrl}/inspector/device?device=device1&name=foo&app=bar`, + autoCleanup.signal, + ); + try { + device.getPages.mockImplementation(() => [ + { + app: 'bar-app 📱', + id: 'page1 🛂', + title: 'bar-title 📰', + vm: 'bar-vm 🤖', + }, + ]); + + jest.advanceTimersByTime(PAGES_POLLING_DELAY); + + const json = await fetchJson( + `${serverRef.serverBaseUrl}${endpoint}`, + ); + expect(json).toEqual([ + expect.objectContaining({ + description: 'bar-app 📱', + deviceName: 'foo', + id: 'device1-page1 🛂', + title: 'bar-title 📰', + vm: 'bar-vm 🤖', + }), + ]); + } finally { + device.close(); + } + }); + + test('includes a valid Content-Length header', async () => { + // NOTE: This test is needed because chrome://inspect's HTTP client is picky + // and doesn't accept responses without a Content-Length header. + const device = await createDeviceMock( + `${serverRef.serverBaseWsUrl}/inspector/device?device=device1&name=foo&app=bar`, + autoCleanup.signal, + ); + try { + device.getPages.mockImplementation(() => [ + { + app: 'bar-app', + id: 'page1', + title: 'bar-title', + vm: 'bar-vm', + }, + ]); + + jest.advanceTimersByTime(PAGES_POLLING_DELAY); + + const response = await fetchLocal( + `${serverRef.serverBaseUrl}${endpoint}`, + ); + expect(response.headers.get('Content-Length')).not.toBeNull(); + } finally { + device.close(); + } + }); }); }); diff --git a/packages/dev-middleware/src/__tests__/getDevToolsFrontendUrl-test.js b/packages/dev-middleware/src/__tests__/getDevToolsFrontendUrl-test.js index 3d0818efc25760..a6fe45b710bf8a 100644 --- a/packages/dev-middleware/src/__tests__/getDevToolsFrontendUrl-test.js +++ b/packages/dev-middleware/src/__tests__/getDevToolsFrontendUrl-test.js @@ -14,16 +14,16 @@ import getDevToolsFrontendUrl from '../utils/getDevToolsFrontendUrl'; describe('getDevToolsFrontendUrl', () => { const webSocketDebuggerUrl = 'ws://localhost:8081/inspector/debug?device=1a9372c&page=-1'; + const devServerUrl = 'http://localhost:8081'; - describe('given an absolute devServerUrl', () => { - const devServerUrl = 'http://localhost:8081'; + const experiments = { + enableNetworkInspector: false, + enableNewDebugger: false, + enableOpenDebuggerRedirect: false, + }; - it('should return a valid url for all experiments off', async () => { - const experiments = { - enableNetworkInspector: false, - enableNewDebugger: false, - enableOpenDebuggerRedirect: false, - }; + describe('relative: false (default)', () => { + test('should return a valid url for all experiments off', async () => { const actual = getDevToolsFrontendUrl( experiments, webSocketDebuggerUrl, @@ -33,18 +33,13 @@ describe('getDevToolsFrontendUrl', () => { expect(url.host).toBe('localhost:8081'); expect(url.pathname).toBe('/debugger-frontend/rn_inspector.html'); expect(url.searchParams.get('ws')).toBe( - 'localhost:8081/inspector/debug?device=1a9372c&page=-1', + '/inspector/debug?device=1a9372c&page=-1', ); }); - it('should return a valid url for enableNetworkInspector experiment on', async () => { - const experiments = { - enableNetworkInspector: true, - enableNewDebugger: true, - enableOpenDebuggerRedirect: false, - }; + test('should return a valid url for enableNetworkInspector experiment on', async () => { const actual = getDevToolsFrontendUrl( - experiments, + {...experiments, enableNetworkInspector: true, enableNewDebugger: true}, webSocketDebuggerUrl, devServerUrl, ); @@ -53,14 +48,26 @@ describe('getDevToolsFrontendUrl', () => { expect(url.pathname).toBe('/debugger-frontend/rn_inspector.html'); expect(url.searchParams.get('unstable_enableNetworkPanel')).toBe('true'); expect(url.searchParams.get('ws')).toBe( - 'localhost:8081/inspector/debug?device=1a9372c&page=-1', + '/inspector/debug?device=1a9372c&page=-1', ); }); - }); - describe('given a relative devServerUrl', () => { - const relativeDevServerUrl = ''; + test('should return a full WS URL if on a different host than the dev server', () => { + const otherWebSocketDebuggerUrl = + 'ws://localhost:9000/inspector/debug?device=1a9372c&page=-1'; + const actual = getDevToolsFrontendUrl( + experiments, + otherWebSocketDebuggerUrl, + devServerUrl, + ); + const url = new URL(actual); + expect(url.searchParams.get('ws')).toBe( + 'localhost:9000/inspector/debug?device=1a9372c&page=-1', + ); + }); + }); + describe('relative: true', () => { function assertValidRelativeURL(relativeURL: string): URL { const anyBaseURL = new URL('https://www.example.com'); try { @@ -71,40 +78,53 @@ describe('getDevToolsFrontendUrl', () => { } } - it('should return a valid url for all experiments off', async () => { - const experiments = { - enableNetworkInspector: false, - enableNewDebugger: false, - enableOpenDebuggerRedirect: false, - }; + test('should return a valid url for all experiments off', async () => { const actual = getDevToolsFrontendUrl( experiments, webSocketDebuggerUrl, - relativeDevServerUrl, + devServerUrl, + { + relative: true, + }, ); const url = assertValidRelativeURL(actual); expect(url.pathname).toBe('/debugger-frontend/rn_inspector.html'); expect(url.searchParams.get('ws')).toBe( - 'localhost:8081/inspector/debug?device=1a9372c&page=-1', + '/inspector/debug?device=1a9372c&page=-1', ); }); - it('should return a valid url for enableNetworkInspector experiment on', async () => { - const experiments = { - enableNetworkInspector: true, - enableNewDebugger: true, - enableOpenDebuggerRedirect: false, - }; + test('should return a valid url for enableNetworkInspector experiment on', async () => { const actual = getDevToolsFrontendUrl( - experiments, + {...experiments, enableNetworkInspector: true, enableNewDebugger: true}, webSocketDebuggerUrl, - relativeDevServerUrl, + devServerUrl, + { + relative: true, + }, ); const url = assertValidRelativeURL(actual); expect(url.pathname).toBe('/debugger-frontend/rn_inspector.html'); expect(url.searchParams.get('unstable_enableNetworkPanel')).toBe('true'); expect(url.searchParams.get('ws')).toBe( - 'localhost:8081/inspector/debug?device=1a9372c&page=-1', + '/inspector/debug?device=1a9372c&page=-1', + ); + }); + + test('should return a full WS URL if on a different host than the dev server', () => { + const otherWebSocketDebuggerUrl = + 'ws://localhost:8082/inspector/debug?device=1a9372c&page=-1'; + const actual = getDevToolsFrontendUrl( + experiments, + otherWebSocketDebuggerUrl, + devServerUrl, + { + relative: true, + }, + ); + const url = assertValidRelativeURL(actual); + expect(url.searchParams.get('ws')).toBe( + 'localhost:8082/inspector/debug?device=1a9372c&page=-1', ); }); }); diff --git a/packages/dev-middleware/src/createDevMiddleware.js b/packages/dev-middleware/src/createDevMiddleware.js index e6c9dc1f7d93e2..8766811b8885ba 100644 --- a/packages/dev-middleware/src/createDevMiddleware.js +++ b/packages/dev-middleware/src/createDevMiddleware.js @@ -9,6 +9,7 @@ * @oncall react_native */ +import type {CreateCustomMessageHandlerFn} from './inspector-proxy/CustomMessageHandler'; import type {BrowserLauncher} from './types/BrowserLauncher'; import type {EventReporter} from './types/EventReporter'; import type {Experiments, ExperimentsConfig} from './types/Experiments'; @@ -61,11 +62,12 @@ type Options = $ReadOnly<{ unstable_experiments?: ExperimentsConfig, /** - * An interface for using a modified inspector proxy implementation. + * Create custom handler to add support for unsupported CDP events, or debuggers. + * This handler is instantiated per logical device and debugger pair. * * This is an unstable API with no semver guarantees. */ - unstable_InspectorProxy?: Class, + unstable_customInspectorMessageHandler?: CreateCustomMessageHandlerFn, }>; type DevMiddlewareAPI = $ReadOnly<{ @@ -80,16 +82,16 @@ export default function createDevMiddleware({ unstable_browserLauncher = DefaultBrowserLauncher, unstable_eventReporter, unstable_experiments: experimentConfig = {}, - unstable_InspectorProxy, + unstable_customInspectorMessageHandler, }: Options): DevMiddlewareAPI { const experiments = getExperiments(experimentConfig); - const InspectorProxyClass = unstable_InspectorProxy ?? InspectorProxy; - const inspectorProxy = new InspectorProxyClass( + const inspectorProxy = new InspectorProxy( projectRoot, serverBaseUrl, unstable_eventReporter, experiments, + unstable_customInspectorMessageHandler, ); const middleware = connect() diff --git a/packages/dev-middleware/src/index.flow.js b/packages/dev-middleware/src/index.flow.js index c662838fea10ce..7afbbdbd8894b3 100644 --- a/packages/dev-middleware/src/index.flow.js +++ b/packages/dev-middleware/src/index.flow.js @@ -13,6 +13,8 @@ export {default as createDevMiddleware} from './createDevMiddleware'; export type {BrowserLauncher, LaunchedBrowser} from './types/BrowserLauncher'; export type {EventReporter, ReportableEvent} from './types/EventReporter'; - -export {default as unstable_InspectorProxy} from './inspector-proxy/InspectorProxy'; -export {default as unstable_Device} from './inspector-proxy/Device'; +export type { + CustomMessageHandler, + CustomMessageHandlerConnection, + CreateCustomMessageHandlerFn, +} from './inspector-proxy/CustomMessageHandler'; diff --git a/packages/dev-middleware/src/inspector-proxy/CustomMessageHandler.js b/packages/dev-middleware/src/inspector-proxy/CustomMessageHandler.js new file mode 100644 index 00000000000000..1c3dd473b7c118 --- /dev/null +++ b/packages/dev-middleware/src/inspector-proxy/CustomMessageHandler.js @@ -0,0 +1,54 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {JSONSerializable, Page} from './types'; + +type ExposedDevice = $ReadOnly<{ + appId: string, + id: string, + name: string, + sendMessage: (message: JSONSerializable) => void, +}>; + +type ExposedDebugger = $ReadOnly<{ + userAgent: string | null, + sendMessage: (message: JSONSerializable) => void, +}>; + +export type CustomMessageHandlerConnection = $ReadOnly<{ + page: Page, + device: ExposedDevice, + debugger: ExposedDebugger, +}>; + +export type CreateCustomMessageHandlerFn = ( + connection: CustomMessageHandlerConnection, +) => ?CustomMessageHandler; + +/** + * The device message middleware allows implementers to handle unsupported CDP messages. + * It is instantiated per device and may contain state that is specific to that device. + * The middleware can also mark messages from the device or debugger as handled, which stops propagating. + */ +export interface CustomMessageHandler { + /** + * Handle a CDP message coming from the device. + * This is invoked before the message is sent to the debugger. + * When returning true, the message is considered handled and will not be sent to the debugger. + */ + handleDeviceMessage(message: JSONSerializable): true | void; + + /** + * Handle a CDP message coming from the debugger. + * This is invoked before the message is sent to the device. + * When returning true, the message is considered handled and will not be sent to the device. + */ + handleDebuggerMessage(message: JSONSerializable): true | void; +} diff --git a/packages/dev-middleware/src/inspector-proxy/Device.js b/packages/dev-middleware/src/inspector-proxy/Device.js index 26befc0b1185c4..a7c4450c593da3 100644 --- a/packages/dev-middleware/src/inspector-proxy/Device.js +++ b/packages/dev-middleware/src/inspector-proxy/Device.js @@ -16,6 +16,10 @@ import type { CDPResponse, CDPServerMessage, } from './cdp-types/messages'; +import type { + CreateCustomMessageHandlerFn, + CustomMessageHandler, +} from './CustomMessageHandler'; import type { MessageFromDevice, MessageToDevice, @@ -51,6 +55,11 @@ type DebuggerInfo = { userAgent: string | null, }; +type DebuggerConnection = { + ...DebuggerInfo, + customHandler: ?CustomMessageHandler, +}; + const REACT_NATIVE_RELOADABLE_PAGE_ID = '-1'; /** @@ -74,7 +83,7 @@ export default class Device { #pages: $ReadOnlyMap; // Stores information about currently connected debugger (if any). - #debuggerConnection: ?DebuggerInfo = null; + #debuggerConnection: ?DebuggerConnection = null; // Last known Page ID of the React Native page. // This is used by debugger connections that don't have PageID specified @@ -97,6 +106,9 @@ export default class Device { #pagesPollingIntervalId: ReturnType; + // The device message middleware factory function allowing implementers to handle unsupported CDP messages. + #createCustomMessageHandler: ?CreateCustomMessageHandlerFn; + constructor( id: string, name: string, @@ -104,6 +116,7 @@ export default class Device { socket: WS, projectRoot: string, eventReporter: ?EventReporter, + createMessageMiddleware: ?CreateCustomMessageHandlerFn, ) { this.#id = id; this.#name = name; @@ -118,6 +131,7 @@ export default class Device { appId: app, }) : null; + this.#createCustomMessageHandler = createMessageMiddleware; // $FlowFixMe[incompatible-call] this.#deviceSocket.on('message', (message: string) => { @@ -205,6 +219,7 @@ export default class Device { prependedFilePrefix: false, pageId, userAgent: metadata.userAgent, + customHandler: null, }; // TODO(moti): Handle null case explicitly, e.g. refuse to connect to @@ -215,6 +230,50 @@ export default class Device { debug(`Got new debugger connection for page ${pageId} of ${this.#name}`); + if (page && this.#debuggerConnection && this.#createCustomMessageHandler) { + this.#debuggerConnection.customHandler = this.#createCustomMessageHandler( + { + page, + debugger: { + userAgent: debuggerInfo.userAgent, + sendMessage: message => { + try { + const payload = JSON.stringify(message); + debug('(Debugger) <- (Proxy) (Device): ' + payload); + socket.send(payload); + } catch {} + }, + }, + device: { + appId: this.#app, + id: this.#id, + name: this.#name, + sendMessage: message => { + try { + const payload = JSON.stringify({ + event: 'wrappedEvent', + payload: { + pageId: this.#mapToDevicePageId(pageId), + wrappedEvent: JSON.stringify(message), + }, + }); + debug('(Debugger) -> (Proxy) (Device): ' + payload); + this.#deviceSocket.send(payload); + } catch {} + }, + }, + }, + ); + + if (this.#debuggerConnection.customHandler) { + debug('Created new custom message handler for debugger connection'); + } else { + debug( + 'Skipping new custom message handler for debugger connection, factory function returned null', + ); + } + } + this.#sendMessageToDevice({ event: 'connect', payload: { @@ -231,6 +290,15 @@ export default class Device { frontendUserAgent: metadata.userAgent, }); let processedReq = debuggerRequest; + + if ( + this.#debuggerConnection?.customHandler?.handleDebuggerMessage( + debuggerRequest, + ) === true + ) { + return; + } + if (!page || !this.#pageHasCapability(page, 'nativeSourceCodeFetching')) { processedReq = this.#interceptClientMessageForSourceFetching( debuggerRequest, @@ -411,12 +479,21 @@ export default class Device { }); } - if (this.#debuggerConnection != null) { + const debuggerConnection = this.#debuggerConnection; + if (debuggerConnection != null) { + if ( + debuggerConnection.customHandler?.handleDeviceMessage( + parsedPayload, + ) === true + ) { + return; + } + // Wrapping just to make flow happy :) // $FlowFixMe[unused-promise] this.#processMessageFromDeviceLegacy( parsedPayload, - this.#debuggerConnection, + debuggerConnection, pageId, ).then(() => { const messageToSend = JSON.stringify(parsedPayload); @@ -499,7 +576,7 @@ export default class Device { // Allows to make changes in incoming message from device. async #processMessageFromDeviceLegacy( payload: CDPServerMessage, - debuggerInfo: DebuggerInfo, + debuggerInfo: DebuggerConnection, pageId: ?string, ) { // TODO(moti): Handle null case explicitly, or ideally associate a copy @@ -616,7 +693,7 @@ export default class Device { */ #interceptClientMessageForSourceFetching( req: CDPClientMessage, - debuggerInfo: DebuggerInfo, + debuggerInfo: DebuggerConnection, socket: WS, ): CDPClientMessage | null { switch (req.method) { @@ -633,7 +710,7 @@ export default class Device { #processDebuggerSetBreakpointByUrl( req: CDPRequest<'Debugger.setBreakpointByUrl'>, - debuggerInfo: DebuggerInfo, + debuggerInfo: DebuggerConnection, ): CDPRequest<'Debugger.setBreakpointByUrl'> { // If we replaced Android emulator's address to localhost we need to change it back. if (debuggerInfo.originalSourceURLAddress != null) { @@ -758,10 +835,6 @@ export default class Device { // Fetch text, raising an exception if the text could not be fetched, // or is too large. async #fetchText(url: URL): Promise { - if (!['localhost', '127.0.0.1'].includes(url.hostname)) { - throw new Error('remote fetches not permitted'); - } - // $FlowFixMe[incompatible-call] Suppress arvr node-fetch flow error const response = await fetch(url); if (!response.ok) { diff --git a/packages/dev-middleware/src/inspector-proxy/InspectorProxy.js b/packages/dev-middleware/src/inspector-proxy/InspectorProxy.js index 066fa44cc3d536..9b9916dc220d98 100644 --- a/packages/dev-middleware/src/inspector-proxy/InspectorProxy.js +++ b/packages/dev-middleware/src/inspector-proxy/InspectorProxy.js @@ -11,6 +11,7 @@ import type {EventReporter} from '../types/EventReporter'; import type {Experiments} from '../types/Experiments'; +import type {CreateCustomMessageHandlerFn} from './CustomMessageHandler'; import type { JsonPagesListResponse, JsonVersionResponse, @@ -58,17 +59,22 @@ export default class InspectorProxy implements InspectorProxyQueries { #experiments: Experiments; + // custom message handler factory allowing implementers to handle unsupported CDP messages. + #customMessageHandler: ?CreateCustomMessageHandlerFn; + constructor( projectRoot: string, serverBaseUrl: string, eventReporter: ?EventReporter, experiments: Experiments, + customMessageHandler: ?CreateCustomMessageHandlerFn, ) { this.#projectRoot = projectRoot; this.#serverBaseUrl = serverBaseUrl; this.#devices = new Map(); this.#eventReporter = eventReporter; this.#experiments = experiments; + this.#customMessageHandler = customMessageHandler; } getPageDescriptions(): Array { @@ -167,6 +173,7 @@ export default class InspectorProxy implements InspectorProxyQueries { response.writeHead(200, { 'Content-Type': 'application/json; charset=UTF-8', 'Cache-Control': 'no-cache', + 'Content-Length': Buffer.byteLength(data).toString(), Connection: 'close', }); response.end(data); @@ -203,6 +210,7 @@ export default class InspectorProxy implements InspectorProxyQueries { socket, this.#projectRoot, this.#eventReporter, + this.#customMessageHandler, ); if (oldDevice) { @@ -257,7 +265,7 @@ export default class InspectorProxy implements InspectorProxyQueries { } device.handleDebuggerConnection(socket, pageId, { - userAgent: req.headers['user-agent'] ?? null, + userAgent: req.headers['user-agent'] ?? query.userAgent ?? null, }); } catch (e) { console.error(e); diff --git a/packages/dev-middleware/src/inspector-proxy/types.js b/packages/dev-middleware/src/inspector-proxy/types.js index f4994a812c4830..a89bfc9a914d57 100644 --- a/packages/dev-middleware/src/inspector-proxy/types.js +++ b/packages/dev-middleware/src/inspector-proxy/types.js @@ -30,6 +30,13 @@ export type TargetCapabilityFlags = $ReadOnly<{ * In the proxy, this disables source fetching emulation and host rewrites. */ nativeSourceCodeFetching?: boolean, + + /** + * The target supports native network inspection. + * + * In the proxy, this disables intercepting and storing network requests. + */ + nativeNetworkInspection?: boolean, }>; // Page information received from the device. New page is created for diff --git a/packages/dev-middleware/src/middleware/openDebuggerMiddleware.js b/packages/dev-middleware/src/middleware/openDebuggerMiddleware.js index 1f3b4d74358521..6b571f7aa026cd 100644 --- a/packages/dev-middleware/src/middleware/openDebuggerMiddleware.js +++ b/packages/dev-middleware/src/middleware/openDebuggerMiddleware.js @@ -132,8 +132,8 @@ export default function openDebuggerMiddleware({ Location: getDevToolsFrontendUrl( experiments, target.webSocketDebuggerUrl, - // Use a relative URL. - '', + serverBaseUrl, + {relative: true}, ), }); res.end(); diff --git a/packages/dev-middleware/src/utils/getDevToolsFrontendUrl.js b/packages/dev-middleware/src/utils/getDevToolsFrontendUrl.js index 4623616292fea5..7dd33dfd9d08a3 100644 --- a/packages/dev-middleware/src/utils/getDevToolsFrontendUrl.js +++ b/packages/dev-middleware/src/utils/getDevToolsFrontendUrl.js @@ -18,16 +18,21 @@ export default function getDevToolsFrontendUrl( experiments: Experiments, webSocketDebuggerUrl: string, devServerUrl: string, + options?: $ReadOnly<{ + relative?: boolean, + }>, ): string { - const scheme = new URL(webSocketDebuggerUrl).protocol.slice(0, -1); - const webSocketUrlWithoutProtocol = webSocketDebuggerUrl.replace( - /^wss?:\/\//, - '', - ); - const appUrl = `${devServerUrl}/debugger-frontend/rn_inspector.html`; + const wsParam = getWsParam({ + webSocketDebuggerUrl, + devServerUrl, + }); + + const appUrl = + (options?.relative === true ? '' : devServerUrl) + + '/debugger-frontend/rn_inspector.html'; const searchParams = new URLSearchParams([ - [scheme, webSocketUrlWithoutProtocol], + [wsParam.key, wsParam.value], ['sources.hide_add_folder', 'true'], ]); if (experiments.enableNetworkInspector) { @@ -36,3 +41,28 @@ export default function getDevToolsFrontendUrl( return appUrl + '?' + searchParams.toString(); } + +function getWsParam({ + webSocketDebuggerUrl, + devServerUrl, +}: $ReadOnly<{ + webSocketDebuggerUrl: string, + devServerUrl: string, +}>): { + key: string, + value: string, +} { + const wsUrl = new URL(webSocketDebuggerUrl); + const serverHost = new URL(devServerUrl).host; + let value; + if (wsUrl.host === serverHost) { + // Use a path-absolute (host-relative) URL + // Depends on https://github.com/facebookexperimental/rn-chrome-devtools-frontend/pull/4 + value = wsUrl.pathname + wsUrl.search + wsUrl.hash; + } else { + // Standard URL format accepted by the DevTools frontend + value = wsUrl.host + wsUrl.pathname + wsUrl.search + wsUrl.hash; + } + const key = wsUrl.protocol.slice(0, -1); + return {key, value}; +} diff --git a/packages/eslint-config-react-native/package.json b/packages/eslint-config-react-native/package.json index 7edb68a00afbe1..d2fd202cfb6b67 100644 --- a/packages/eslint-config-react-native/package.json +++ b/packages/eslint-config-react-native/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/eslint-config", - "version": "0.74.0", + "version": "0.75.0-main", "description": "ESLint config for React Native", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/eslint-config-react-native" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/eslint-config-react-native#readme", @@ -22,13 +22,13 @@ "dependencies": { "@babel/core": "^7.20.0", "@babel/eslint-parser": "^7.20.0", - "@react-native/eslint-plugin": "0.74.0", - "@typescript-eslint/eslint-plugin": "^6.7.4", - "@typescript-eslint/parser": "^6.7.4", + "@react-native/eslint-plugin": "0.75.0-main", + "@typescript-eslint/eslint-plugin": "^7.1.1", + "@typescript-eslint/parser": "^7.1.1", "eslint-config-prettier": "^8.5.0", "eslint-plugin-eslint-comments": "^3.2.0", "eslint-plugin-ft-flow": "^2.0.1", - "eslint-plugin-jest": "^26.5.3", + "eslint-plugin-jest": "^27.9.0", "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-react": "^7.30.1", "eslint-plugin-react-hooks": "^4.6.0", @@ -39,7 +39,7 @@ "prettier": ">=2" }, "devDependencies": { - "eslint": "^8.23.1", + "eslint": "^8.57.0", "prettier": "2.8.8" } } diff --git a/packages/eslint-plugin-react-native/package.json b/packages/eslint-plugin-react-native/package.json index acb35918dd30e1..10618f6453d3b9 100644 --- a/packages/eslint-plugin-react-native/package.json +++ b/packages/eslint-plugin-react-native/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/eslint-plugin", - "version": "0.74.0", + "version": "0.75.0-main", "description": "ESLint rules for @react-native/eslint-config", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/eslint-plugin-react-native" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/eslint-plugin-react-native#readme", diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json index fa04efd48a5717..3429d1eb63d93f 100644 --- a/packages/eslint-plugin-specs/package.json +++ b/packages/eslint-plugin-specs/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/eslint-plugin-specs", - "version": "0.74.0", + "version": "0.75.0-main", "description": "ESLint rules to validate NativeModule and Component Specs", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/eslint-plugin-specs" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/eslint-plugin-specs#readme", @@ -31,7 +31,7 @@ "@babel/eslint-parser": "^7.20.0", "@babel/plugin-transform-flow-strip-types": "^7.20.0", "@babel/preset-flow": "^7.20.0", - "@react-native/codegen": "0.74.0", + "@react-native/codegen": "0.75.0-main", "make-dir": "^2.1.0", "pirates": "^4.0.1", "source-map-support": "0.5.0" diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index 0124f83b5419aa..e3bb2f97f39bc6 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -1,16 +1,16 @@ { "name": "@react-native/hermes-inspector-msggen", - "version": "0.72.0", + "version": "0.75.0-main", "private": true, "description": "Hermes Inspector Message Generator for React Native", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/hermes-inspector-msggen" }, "bin": { - "msggen": "./bin/index.js" + "msggen": "bin/index.js" }, "engines": { "node": ">=18" diff --git a/packages/hermes-inspector-msggen/src/Property.js b/packages/hermes-inspector-msggen/src/Property.js index a673916035755f..3874d83c58c733 100644 --- a/packages/hermes-inspector-msggen/src/Property.js +++ b/packages/hermes-inspector-msggen/src/Property.js @@ -194,8 +194,8 @@ class RefProperty extends Property { return this.cyclical ? `{nullptr, deleter<${fullCppType}>}` : this.optional - ? '' - : '{}'; + ? '' + : '{}'; } } diff --git a/packages/metro-config/package.json b/packages/metro-config/package.json index 410f04a50b8952..75ff711fba0f43 100644 --- a/packages/metro-config/package.json +++ b/packages/metro-config/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/metro-config", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Metro configuration for React Native.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/metro-config" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/metro-config#readme", @@ -26,8 +26,8 @@ "dist" ], "dependencies": { - "@react-native/js-polyfills": "0.74.0", - "@react-native/metro-babel-transformer": "0.74.0", + "@react-native/js-polyfills": "0.75.0-main", + "@react-native/metro-babel-transformer": "0.75.0-main", "metro-config": "^0.80.3", "metro-runtime": "^0.80.3" } diff --git a/packages/normalize-color/package.json b/packages/normalize-color/package.json index c489d39b87bc80..875c9ce1c51cc9 100644 --- a/packages/normalize-color/package.json +++ b/packages/normalize-color/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/normalize-colors", - "version": "0.74.1", + "version": "0.75.0-main", "description": "Color normalization for React Native.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/normalize-color" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/normalize-color#readme", diff --git a/packages/polyfills/console.js b/packages/polyfills/console.js index 338e1590cb3bc7..aac13350ccb6bc 100644 --- a/packages/polyfills/console.js +++ b/packages/polyfills/console.js @@ -554,6 +554,7 @@ if (global.nativeLoggingHook) { } global.console = { + ...(originalConsole ?? {}), error: getNativeLogFunction(LOG_LEVELS.error), info: getNativeLogFunction(LOG_LEVELS.info), log: getNativeLogFunction(LOG_LEVELS.info), @@ -578,7 +579,10 @@ if (global.nativeLoggingHook) { if (__DEV__ && originalConsole) { Object.keys(console).forEach(methodName => { const reactNativeMethod = console[methodName]; - if (originalConsole[methodName]) { + if ( + originalConsole[methodName] && + reactNativeMethod !== originalConsole[methodName] + ) { console[methodName] = function () { originalConsole[methodName](...arguments); reactNativeMethod.apply(console, arguments); diff --git a/packages/polyfills/package.json b/packages/polyfills/package.json index cadebf8191e007..6bd3b33f0b3f53 100644 --- a/packages/polyfills/package.json +++ b/packages/polyfills/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/js-polyfills", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Polyfills for React Native.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/polyfills" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/polyfills#readme", diff --git a/packages/react-native-babel-preset/package.json b/packages/react-native-babel-preset/package.json index 74a6f1df7c917d..8c5078b0cdba9b 100644 --- a/packages/react-native-babel-preset/package.json +++ b/packages/react-native-babel-preset/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/babel-preset", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Babel preset for React Native applications", "main": "src/index.js", "repository": { "type": "git", - "url": "git@github.com:facebook/react-native.git" + "url": "git+ssh://git@github.com/facebook/react-native.git" }, "keywords": [ "babel", @@ -54,7 +54,7 @@ "@babel/plugin-transform-typescript": "^7.5.0", "@babel/plugin-transform-unicode-regex": "^7.0.0", "@babel/template": "^7.0.0", - "@react-native/babel-plugin-codegen": "0.74.0", + "@react-native/babel-plugin-codegen": "0.75.0-main", "babel-plugin-transform-flow-enums": "^0.0.2", "react-refresh": "^0.14.0" }, diff --git a/packages/react-native-babel-transformer/package.json b/packages/react-native-babel-transformer/package.json index b78d79c643db84..24ba4d33cfc873 100644 --- a/packages/react-native-babel-transformer/package.json +++ b/packages/react-native-babel-transformer/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/metro-babel-transformer", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Babel transformer for React Native applications.", "main": "src/index.js", "repository": { "type": "git", - "url": "git@github.com:facebook/react-native.git", + "url": "git+ssh://git@github.com/facebook/react-native.git", "directory": "packages/react-native-babel-transformer" }, "keywords": [ @@ -16,8 +16,8 @@ "license": "MIT", "dependencies": { "@babel/core": "^7.20.0", - "@react-native/babel-preset": "0.74.0", - "hermes-parser": "0.19.1", + "@react-native/babel-preset": "0.75.0-main", + "hermes-parser": "0.20.1", "nullthrows": "^1.1.1" }, "peerDependencies": { diff --git a/packages/react-native-bots/package.json b/packages/react-native-bots/package.json index 961bdbd9d6bfab..6132001e214f9f 100644 --- a/packages/react-native-bots/package.json +++ b/packages/react-native-bots/package.json @@ -1,12 +1,12 @@ { "name": "@react-native/bots", "description": "React Native Bots", - "version": "0.0.0", + "version": "0.75.0-main", "private": true, "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/react-native-bots" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-bots#readme", diff --git a/packages/react-native-codegen-typescript-test/package.json b/packages/react-native-codegen-typescript-test/package.json index c170d4cedccc8e..d60e7369d5c81a 100644 --- a/packages/react-native-codegen-typescript-test/package.json +++ b/packages/react-native-codegen-typescript-test/package.json @@ -1,12 +1,12 @@ { "name": "@react-native/codegen-typescript-test", - "version": "0.0.1", + "version": "0.75.0-main", "private": true, "description": "TypeScript related unit test for @react-native/codegen", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/react-native-codegen-typescript-test" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-typescript-test", @@ -19,7 +19,7 @@ "prepare": "yarn run build" }, "dependencies": { - "@react-native/codegen": "0.74.0" + "@react-native/codegen": "0.75.0-main" }, "devDependencies": { "@babel/core": "^7.20.0", diff --git a/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleCpp-test.js.snap index 21946d6459940c..3130ea41984170 100644 --- a/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleCpp-test.js.snap +++ b/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleCpp-test.js.snap @@ -17,20 +17,20 @@ namespace facebook::react { static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getReadOnlyArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getReadOnlyArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getArrayWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArrayWithAlias( rt, - args[0].asObject(rt).asArray(rt), - args[1].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt) ); } @@ -43,13 +43,13 @@ NativeArrayTurboModuleCxxSpecJSI::NativeArrayTurboModuleCxxSpecJSI(std::shared_p static jsi::Value __hostFunction_NativeBooleanTurboModuleCxxSpecJSI_getBoolean(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBoolean( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeBooleanTurboModuleCxxSpecJSI_getBooleanWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBooleanWithAlias( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } @@ -61,14 +61,14 @@ NativeBooleanTurboModuleCxxSpecJSI::NativeBooleanTurboModuleCxxSpecJSI(std::shar static jsi::Value __hostFunction_NativeCallbackTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeCallbackTurboModuleCxxSpecJSI_getValueWithCallbackWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallbackWithAlias( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } @@ -81,40 +81,40 @@ NativeCallbackTurboModuleCxxSpecJSI::NativeCallbackTurboModuleCxxSpecJSI(std::sh static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusRegular(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusRegular( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusStr(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusStr( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusNum(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusNum( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusFraction(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusFraction( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStateType(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStateType( rt, - args[0].asString(rt), - args[1].asString(rt), - args[2].asNumber(), - args[3].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asNumber(), + count <= 3 ? throw jsi::JSError(rt, \\"Expected argument in position 3 to be passed\\") : args[3].asNumber() ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStateTypeWithEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStateTypeWithEnums( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } @@ -130,35 +130,35 @@ NativeEnumTurboModuleCxxSpecJSI::NativeEnumTurboModuleCxxSpecJSI(std::shared_ptr static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getBool( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getNumber( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getString( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getArray( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObject( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -181,13 +181,13 @@ NativeNullableTurboModuleCxxSpecJSI::NativeNullableTurboModuleCxxSpecJSI(std::sh static jsi::Value __hostFunction_NativeNumberTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeNumberTurboModuleCxxSpecJSI_getNumberWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumberWithAlias( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } @@ -199,25 +199,25 @@ NativeNumberTurboModuleCxxSpecJSI::NativeNumberTurboModuleCxxSpecJSI(std::shared static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObjectReadOnly(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObjectReadOnly( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObjectWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObjectWithAlias( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_difficultObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->difficultObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -257,14 +257,14 @@ static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_ge static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_getSomeObjFromPartialSomeObj(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getSomeObjFromPartialSomeObj( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_getPartialPartial(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getPartialPartial( rt, - args[0].asObject(rt), - args[1].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt) ); } @@ -278,13 +278,13 @@ NativePartialAnnotationTurboModuleCxxSpecJSI::NativePartialAnnotationTurboModule static jsi::Value __hostFunction_NativePromiseTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativePromiseTurboModuleCxxSpecJSI_getValueWithPromiseWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromiseWithAlias( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } @@ -307,70 +307,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi: static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - args[0].getNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asNumber(), - args[1].asString(rt), - args[2].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } @@ -404,70 +404,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_voidFun static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asObject(rt).asArray(rt), - args[1].asObject(rt).asArray(rt), - args[2].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } @@ -501,79 +501,79 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_voidF static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getBool( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getNumber( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getString( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getArray( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObject( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObjectShape( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getAlias( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getRootTag( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getValue( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), - args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), - args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), + count <= 1 || args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), + count <= 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getValueWithPromise( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -643,7 +643,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSp static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -656,7 +656,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSp static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getRootTag( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -714,70 +714,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_voidF static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), - count <= 1 || args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), - count <= 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), + count <= 1 || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), + count <= 2 || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asFunction(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asFunction(rt)) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); } @@ -800,13 +800,13 @@ NativeSampleTurboModuleOptionalCxxSpecJSI::NativeSampleTurboModuleOptionalCxxSpe static jsi::Value __hostFunction_NativeStringTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeStringTurboModuleCxxSpecJSI_getStringWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStringWithAlias( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } @@ -838,20 +838,20 @@ namespace facebook::react { static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getReadOnlyArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getReadOnlyArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeArrayTurboModuleCxxSpecJSI_getArrayWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArrayWithAlias( rt, - args[0].asObject(rt).asArray(rt), - args[1].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt) ); } @@ -864,13 +864,13 @@ NativeArrayTurboModuleCxxSpecJSI::NativeArrayTurboModuleCxxSpecJSI(std::shared_p static jsi::Value __hostFunction_NativeBooleanTurboModuleCxxSpecJSI_getBoolean(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBoolean( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeBooleanTurboModuleCxxSpecJSI_getBooleanWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBooleanWithAlias( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } @@ -882,14 +882,14 @@ NativeBooleanTurboModuleCxxSpecJSI::NativeBooleanTurboModuleCxxSpecJSI(std::shar static jsi::Value __hostFunction_NativeCallbackTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeCallbackTurboModuleCxxSpecJSI_getValueWithCallbackWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallbackWithAlias( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } @@ -902,40 +902,40 @@ NativeCallbackTurboModuleCxxSpecJSI::NativeCallbackTurboModuleCxxSpecJSI(std::sh static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusRegular(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusRegular( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusStr(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusStr( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusNum(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusNum( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStatusFraction(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStatusFraction( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStateType(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStateType( rt, - args[0].asString(rt), - args[1].asString(rt), - args[2].asNumber(), - args[3].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asNumber(), + count <= 3 ? throw jsi::JSError(rt, \\"Expected argument in position 3 to be passed\\") : args[3].asNumber() ); } static jsi::Value __hostFunction_NativeEnumTurboModuleCxxSpecJSI_getStateTypeWithEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStateTypeWithEnums( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } @@ -951,35 +951,35 @@ NativeEnumTurboModuleCxxSpecJSI::NativeEnumTurboModuleCxxSpecJSI(std::shared_ptr static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getBool( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getNumber( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getString( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getArray( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeNullableTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObject( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -1002,13 +1002,13 @@ NativeNullableTurboModuleCxxSpecJSI::NativeNullableTurboModuleCxxSpecJSI(std::sh static jsi::Value __hostFunction_NativeNumberTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeNumberTurboModuleCxxSpecJSI_getNumberWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumberWithAlias( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } @@ -1020,25 +1020,25 @@ NativeNumberTurboModuleCxxSpecJSI::NativeNumberTurboModuleCxxSpecJSI(std::shared static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObjectReadOnly(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObjectReadOnly( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getGenericObjectWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGenericObjectWithAlias( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_difficultObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->difficultObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeObjectTurboModuleCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -1078,14 +1078,14 @@ static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_ge static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_getSomeObjFromPartialSomeObj(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getSomeObjFromPartialSomeObj( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativePartialAnnotationTurboModuleCxxSpecJSI_getPartialPartial(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getPartialPartial( rt, - args[0].asObject(rt), - args[1].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt) ); } @@ -1099,13 +1099,13 @@ NativePartialAnnotationTurboModuleCxxSpecJSI::NativePartialAnnotationTurboModule static jsi::Value __hostFunction_NativePromiseTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativePromiseTurboModuleCxxSpecJSI_getValueWithPromiseWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromiseWithAlias( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } @@ -1128,70 +1128,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi: static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - args[0].getNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asNumber(), - args[1].asString(rt), - args[2].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } @@ -1225,70 +1225,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_voidFun static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asObject(rt).asArray(rt), - args[1].asObject(rt).asArray(rt), - args[2].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleArraysCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } @@ -1322,79 +1322,79 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_voidF static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getBool( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getNumber( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getString( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getArray( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObject( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getObjectShape( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getAlias( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getRootTag( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getValue( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), - args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), - args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), + count <= 1 || args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), + count <= 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getValueWithPromise( rt, - args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -1464,7 +1464,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSp static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -1477,7 +1477,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSp static jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getRootTag( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -1535,70 +1535,70 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_voidF static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asString(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asArray(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getObjectShape(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectShape( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getAlias( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].getNumber()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), - count <= 1 || args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), - count <= 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asNumber()), + count <= 1 || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)), + count <= 2 || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asFunction(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).asFunction(rt)) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleOptionalCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); } @@ -1621,13 +1621,13 @@ NativeSampleTurboModuleOptionalCxxSpecJSI::NativeSampleTurboModuleOptionalCxxSpe static jsi::Value __hostFunction_NativeStringTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeStringTurboModuleCxxSpecJSI_getStringWithAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStringWithAlias( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 2e8200e957f0a7..451723e26e5372 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/codegen", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Code generation tools for React Native", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/react-native-codegen" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen#readme", @@ -31,7 +31,7 @@ "dependencies": { "@babel/parser": "^7.20.0", "glob": "^7.1.1", - "hermes-parser": "0.19.1", + "hermes-parser": "0.20.1", "invariant": "^2.2.4", "jscodeshift": "^0.14.0", "mkdirp": "^0.5.1", @@ -49,7 +49,7 @@ "@babel/plugin-transform-flow-strip-types": "^7.20.0", "@babel/preset-env": "^7.20.0", "chalk": "^4.0.0", - "hermes-estree": "0.19.1", + "hermes-estree": "0.20.1", "micromatch": "^4.0.4", "prettier": "2.8.8", "rimraf": "^3.0.2", diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js index e435945e5c7f0d..8928c0e8566062 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js @@ -122,7 +122,6 @@ function serializeArg( const {typeAnnotation: nullableTypeAnnotation, optional} = arg; const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const isRequired = !optional && !nullable; let realTypeAnnotation = typeAnnotation; if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { @@ -132,22 +131,28 @@ function serializeArg( function wrap(callback: (val: string) => string) { const val = `args[${index}]`; const expression = callback(val); - if (isRequired) { - return expression; - } else { - let condition = `${val}.isNull() || ${val}.isUndefined()`; - if (optional) { - condition = `count <= ${index} || ${condition}`; - } - return `${condition} ? std::nullopt : std::make_optional(${expression})`; + + // param?: T + if (optional && !nullable) { + // throw new Error('are we hitting this case? ' + moduleName); + return `count <= ${index} || ${val}.isUndefined() ? std::nullopt : std::make_optional(${expression})`; + } + + // param: ?T + // param?: ?T + if (nullable || optional) { + return `count <= ${index} || ${val}.isNull() || ${val}.isUndefined() ? std::nullopt : std::make_optional(${expression})`; } + + // param: T + return `count <= ${index} ? throw jsi::JSError(rt, "Expected argument in position ${index} to be passed") : ${expression}`; } switch (realTypeAnnotation.type) { case 'ReservedTypeAnnotation': switch (realTypeAnnotation.name) { case 'RootTag': - return wrap(val => `${val}.getNumber()`); + return wrap(val => `${val}.asNumber()`); default: (realTypeAnnotation.name: empty); throw new Error( diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js index 2dc407f303476f..8335f705ae6eb6 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js @@ -462,7 +462,7 @@ module.exports = { 'com.facebook.react.bridge.ReactApplicationContext', 'com.facebook.react.bridge.ReactContextBaseJavaModule', 'com.facebook.react.bridge.ReactMethod', - 'com.facebook.react.internal.turbomodule.core.interfaces.TurboModule', + 'com.facebook.react.turbomodule.core.interfaces.TurboModule', 'com.facebook.proguard.annotations.DoNotStrip', 'javax.annotation.Nonnull', ]); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap index cef33f44c2ef3f..dcfbcaa3e16023 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap @@ -46,29 +46,29 @@ namespace facebook::react { static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_difficult(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->difficult( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionals(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->optionals( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionalMethod(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->optionalMethod( rt, - args[0].asObject(rt), - args[1].asObject(rt).asFunction(rt), - count <= 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt).asArray(rt)) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asFunction(rt), + count <= 2 || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt).asArray(rt)) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArrays(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getArrays( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); return jsi::Value::undefined(); } @@ -126,13 +126,13 @@ namespace facebook::react { static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -143,7 +143,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getConstants( static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getCustomEnum(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getCustomEnum( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getCustomHostObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -154,96 +154,96 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getCustomHost static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_consumeCustomHostObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->consumeCustomHostObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBinaryTreeNode(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBinaryTreeNode( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getGraphNode(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getGraphNode( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumEnum(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumEnum( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getStrEnum(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getStrEnum( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getMap(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getMap( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getSet(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getSet( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getUnion(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getUnion( rt, - args[0].asNumber(), - args[1].asString(rt), - args[2].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asNumber(), - args[1].asString(rt), - args[2].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getWithWithOptionalArgs(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { auto result = static_cast(&turboModule)->getWithWithOptionalArgs( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asBool()) ); return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); } @@ -256,14 +256,14 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi: static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_setMenu(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->setMenu( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_emitCustomDeviceEvent(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->emitCustomDeviceEvent( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); return jsi::Value::undefined(); } @@ -276,7 +276,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFuncThrow static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObjectThrows(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectThrows( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFuncAssert(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -288,7 +288,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFuncAsser static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObjectAssert(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObjectAssert( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } @@ -380,7 +380,7 @@ static jsi::Value __hostFunction_AliasTurboModuleCxxSpecJSI_getConstants(jsi::Ru static jsi::Value __hostFunction_AliasTurboModuleCxxSpecJSI_cropImage(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->cropImage( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); return jsi::Value::undefined(); } @@ -420,20 +420,20 @@ static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_getConstants( static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_getPhotos(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getPhotos( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_saveToCameraRoll(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->saveToCameraRoll( rt, - args[0].asString(rt), - args[1].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt) ); } static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_deletePhotos(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->deletePhotos( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } @@ -447,34 +447,34 @@ NativeCameraRollManagerCxxSpecJSI::NativeCameraRollManagerCxxSpecJSI(std::shared static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportFatalException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->reportFatalException( rt, - args[0].asString(rt), - args[1].asObject(rt).asArray(rt), - args[2].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asNumber() ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportSoftException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->reportSoftException( rt, - args[0].asString(rt), - args[1].asObject(rt).asArray(rt), - args[2].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asNumber() ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->reportException( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_updateExceptionMessage(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->updateExceptionMessage( rt, - args[0].asString(rt), - args[1].asObject(rt).asArray(rt), - args[2].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asObject(rt).asArray(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asNumber() ); return jsi::Value::undefined(); } @@ -529,45 +529,45 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi: static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getBool( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getNumber( rt, - args[0].asNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getString( rt, - args[0].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asString(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getArray( rt, - args[0].asObject(rt).asArray(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asArray(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getObject( rt, - args[0].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getRootTag( rt, - args[0].getNumber() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValue( rt, - args[0].asNumber(), - args[1].asString(rt), - args[2].asObject(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asString(rt), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asObject(rt) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnumReturn(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -578,28 +578,28 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnumReturn static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->getValueWithCallback( rt, - args[0].asObject(rt).asFunction(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asObject(rt).asFunction(rt) ); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise( rt, - args[0].asBool() + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asBool() ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithOptionalArg(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithOptionalArg( rt, - count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) + count <= 0 || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt)) ); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getEnums( rt, - args[0].asNumber(), - args[1].asNumber(), - args[2].asString(rt) + count <= 0 ? throw jsi::JSError(rt, \\"Expected argument in position 0 to be passed\\") : args[0].asNumber(), + count <= 1 ? throw jsi::JSError(rt, \\"Expected argument in position 1 to be passed\\") : args[1].asNumber(), + count <= 2 ? throw jsi::JSError(rt, \\"Expected argument in position 2 to be passed\\") : args[2].asString(rt) ); } diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap index a03ec04f54d55d..875476d45acaae 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap @@ -20,7 +20,7 @@ import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -66,7 +66,7 @@ import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -136,7 +136,7 @@ import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -178,7 +178,7 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class AliasTurboModuleSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -224,7 +224,7 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeCameraRollManagerSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -272,7 +272,7 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeExceptionsManagerSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -338,7 +338,7 @@ import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.Arrays; import java.util.HashSet; import java.util.Map; @@ -462,7 +462,7 @@ import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements TurboModule { @@ -500,7 +500,7 @@ import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; public abstract class NativeSampleTurboModule2Spec extends ReactContextBaseJavaModule implements TurboModule { diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 33b450a9e9166c..c9c794d1bc5432 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/gradle-plugin", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Gradle Plugin for React Native", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/react-native-gradle-plugin" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin#readme", diff --git a/packages/react-native-popup-menu-android/android/build.gradle.kts b/packages/react-native-popup-menu-android/android/build.gradle.kts new file mode 100644 index 00000000000000..d861b977491ea5 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/build.gradle.kts @@ -0,0 +1,35 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +plugins { + id("com.facebook.react") + alias(libs.plugins.android.library) + alias(libs.plugins.kotlin.android) +} + +android { + compileSdk = libs.versions.compileSdk.get().toInt() + buildToolsVersion = libs.versions.buildTools.get() + namespace = "com.facebook.react.popupmenu" + + defaultConfig { + minSdk = libs.versions.minSdk.get().toInt() + targetSdk = libs.versions.targetSdk.get().toInt() + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { jvmTarget = "17" } +} + +dependencies { + // Build React Native from source + implementation(project(":packages:react-native:ReactAndroid")) +} diff --git a/packages/react-native-popup-menu-android/android/gradle.properties b/packages/react-native-popup-menu-android/android/gradle.properties new file mode 100644 index 00000000000000..f436a7474fed62 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/gradle.properties @@ -0,0 +1,3 @@ +# We want to have more fine grained control on the Java version for +# ReactAndroid, therefore we disable RGNP Java version alignment mechanism +react.internal.disableJavaVersionAlignment=true diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h new file mode 100644 index 00000000000000..af069cd67fc885 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h @@ -0,0 +1,20 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateComponentDescriptorH.js + */ + +#pragma once + +#include "ShadowNodes.h" +#include + +namespace facebook::react { + +using AndroidPopupMenuComponentDescriptor = ConcreteComponentDescriptor; + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.cpp b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.cpp new file mode 100644 index 00000000000000..0c18d59e3a63db --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.cpp @@ -0,0 +1,24 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateEventEmitterCpp.js + */ + +#include "EventEmitters.h" + + +namespace facebook::react { + +void AndroidPopupMenuEventEmitter::onSelectionChange(OnSelectionChange $event) const { + dispatchEvent("selectionChange", [$event=std::move($event)](jsi::Runtime &runtime) { + auto $payload = jsi::Object(runtime); + $payload.setProperty(runtime, "item", $event.item); + return $payload; + }); +} + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h new file mode 100644 index 00000000000000..a0387907710fe0 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h @@ -0,0 +1,25 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateEventEmitterH.js + */ +#pragma once + +#include + + +namespace facebook::react { +class AndroidPopupMenuEventEmitter : public ViewEventEmitter { + public: + using ViewEventEmitter::ViewEventEmitter; + + struct OnSelectionChange { + int item; + }; + void onSelectionChange(OnSelectionChange value) const; +}; +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.cpp b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.cpp new file mode 100644 index 00000000000000..ddcdcff88ebfef --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.cpp @@ -0,0 +1,25 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GeneratePropsCpp.js + */ + +#include "Props.h" +#include +#include + +namespace facebook::react { + +AndroidPopupMenuProps::AndroidPopupMenuProps( + const PropsParserContext &context, + const AndroidPopupMenuProps &sourceProps, + const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), + + menuItems(convertRawProp(context, rawProps, "menuItems", sourceProps.menuItems, {})) + {} + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h new file mode 100644 index 00000000000000..191f0b15776bc5 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h @@ -0,0 +1,28 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GeneratePropsH.js + */ +#pragma once + +#include +#include +#include + +namespace facebook::react { + +class AndroidPopupMenuProps final : public ViewProps { + public: + AndroidPopupMenuProps() = default; + AndroidPopupMenuProps(const PropsParserContext& context, const AndroidPopupMenuProps &sourceProps, const RawProps &rawProps); + +#pragma mark - Props + + std::vector menuItems{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.cpp b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.cpp new file mode 100644 index 00000000000000..5fd96dbbadaacf --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.cpp @@ -0,0 +1,17 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateShadowNodeCpp.js + */ + +#include "ShadowNodes.h" + +namespace facebook::react { + +extern const char AndroidPopupMenuComponentName[] = "AndroidPopupMenu"; + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h new file mode 100644 index 00000000000000..0fd9852b1bca57 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h @@ -0,0 +1,32 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateShadowNodeH.js + */ + +#pragma once + +#include "EventEmitters.h" +#include "Props.h" +#include "States.h" +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char AndroidPopupMenuComponentName[]; + +/* + * `ShadowNode` for component. + */ +using AndroidPopupMenuShadowNode = ConcreteViewShadowNode< + AndroidPopupMenuComponentName, + AndroidPopupMenuProps, + AndroidPopupMenuEventEmitter, + AndroidPopupMenuState>; + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.cpp b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.cpp new file mode 100644 index 00000000000000..1dbb184cbddb62 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.cpp @@ -0,0 +1,16 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateStateCpp.js + */ +#include "States.h" + +namespace facebook::react { + + + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h new file mode 100644 index 00000000000000..62c048033b7021 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h @@ -0,0 +1,34 @@ +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateStateH.js + */ +#pragma once + +#ifdef ANDROID +#include +#include +#include +#endif + +namespace facebook::react { + +class AndroidPopupMenuState { +public: + AndroidPopupMenuState() = default; + +#ifdef ANDROID + AndroidPopupMenuState(AndroidPopupMenuState const &previousState, folly::dynamic data){}; + folly::dynamic getDynamic() const { + return {}; + }; + MapBuffer getMapBuffer() const { + return MapBufferBuilder::EMPTY(); + }; +#endif +}; + +} // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuPackage.kt b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuPackage.kt new file mode 100644 index 00000000000000..0a351d28643ee0 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuPackage.kt @@ -0,0 +1,56 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.popupmenu + +import com.facebook.react.BaseReactPackage +import com.facebook.react.ViewManagerOnDemandReactPackage +import com.facebook.react.bridge.ModuleSpec +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.module.annotations.ReactModuleList +import com.facebook.react.module.model.ReactModuleInfoProvider +import com.facebook.react.uimanager.ViewManager + +@ReactModuleList(nativeModules = arrayOf()) +class PopupMenuPackage() : BaseReactPackage(), ViewManagerOnDemandReactPackage { + private var viewManagersMap: Map? = null + + override fun getModule(name: String, context: ReactApplicationContext): NativeModule? { + return null + } + + private fun getViewManagersMap(): Map { + val viewManagers = + viewManagersMap + ?: mapOf( + ReactPopupMenuManager.REACT_CLASS to + ModuleSpec.viewManagerSpec({ ReactPopupMenuManager() })) + viewManagersMap = viewManagers + return viewManagers + } + + protected override fun getViewManagers(context: ReactApplicationContext): List { + return ArrayList(getViewManagersMap().values) + } + + override fun getViewManagerNames(context: ReactApplicationContext): Collection { + return getViewManagersMap().keys + } + + override fun createViewManager( + reactContext: ReactApplicationContext, + viewManagerName: String + ): ViewManager<*, *>? { + val spec: ModuleSpec? = getViewManagersMap().get(viewManagerName) + return if (spec != null) (spec.getProvider().get() as ViewManager<*, *>) else null + } + + override fun getReactModuleInfoProvider(): ReactModuleInfoProvider { + return ReactModuleInfoProvider { emptyMap() } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/PopupMenuSelectionEvent.kt b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuSelectionEvent.kt similarity index 89% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/PopupMenuSelectionEvent.kt rename to packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuSelectionEvent.kt index f0195e6d29ff4d..289b70d566c870 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/PopupMenuSelectionEvent.kt +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/PopupMenuSelectionEvent.kt @@ -5,9 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -@file:Suppress("DEPRECATION") // We want to use RCTEventEmitter for interop purposes - -package com.facebook.react.views.popupmenu +package com.facebook.react.popupmenu import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuContainer.kt b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuContainer.kt similarity index 97% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuContainer.kt rename to packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuContainer.kt index 57574290bacbe3..6be3bfc916d059 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuContainer.kt +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuContainer.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.popupmenu +package com.facebook.react.popupmenu import android.content.Context import android.os.Build diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuManager.kt b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuManager.kt similarity index 97% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuManager.kt rename to packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuManager.kt index 99dd6b72aa3c92..3758f154c8741e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/popupmenu/ReactPopupMenuManager.kt +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/popupmenu/ReactPopupMenuManager.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.popupmenu +package com.facebook.react.popupmenu import com.facebook.react.bridge.ReadableArray import com.facebook.react.module.annotations.ReactModule diff --git a/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerDelegate.java b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerDelegate.java new file mode 100644 index 00000000000000..736b778e5948f5 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerDelegate.java @@ -0,0 +1,41 @@ +/** +* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). +* +* Do not edit this file as changes may cause incorrect behavior and will be lost +* once the code is regenerated. +* +* @generated by codegen project: GeneratePropsJavaDelegate.js +*/ + +package com.facebook.react.viewmanagers; + +import android.view.View; +import androidx.annotation.Nullable; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.uimanager.BaseViewManagerDelegate; +import com.facebook.react.uimanager.BaseViewManagerInterface; + +public class AndroidPopupMenuManagerDelegate & AndroidPopupMenuManagerInterface> extends BaseViewManagerDelegate { + public AndroidPopupMenuManagerDelegate(U viewManager) { + super(viewManager); + } + @Override + public void setProperty(T view, String propName, @Nullable Object value) { + switch (propName) { + case "menuItems": + mViewManager.setMenuItems(view, (ReadableArray) value); + break; + default: + super.setProperty(view, propName, value); + } + } + + @Override + public void receiveCommand(T view, String commandName, ReadableArray args) { + switch (commandName) { + case "show": + mViewManager.show(view); + break; + } + } +} diff --git a/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerInterface.java b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerInterface.java new file mode 100644 index 00000000000000..83e94ab5e295a2 --- /dev/null +++ b/packages/react-native-popup-menu-android/android/src/main/java/com/facebook/react/viewmanagers/AndroidPopupMenuManagerInterface.java @@ -0,0 +1,19 @@ +/** +* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). +* +* Do not edit this file as changes may cause incorrect behavior and will be lost +* once the code is regenerated. +* +* @generated by codegen project: GeneratePropsJavaInterface.js +*/ + +package com.facebook.react.viewmanagers; + +import android.view.View; +import androidx.annotation.Nullable; +import com.facebook.react.bridge.ReadableArray; + +public interface AndroidPopupMenuManagerInterface { + void setMenuItems(T view, @Nullable ReadableArray value); + void show(T view); +} diff --git a/packages/react-native-popup-menu-android/index.d.ts b/packages/react-native-popup-menu-android/index.d.ts new file mode 100644 index 00000000000000..9caa4c385a77e4 --- /dev/null +++ b/packages/react-native-popup-menu-android/index.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +export type {default} from './PopupMenuAndroid'; +export type {PopupMenuAndroidInstance} from './PopupMenuAndroid'; diff --git a/packages/react-native-popup-menu-android/index.js b/packages/react-native-popup-menu-android/index.js new file mode 100644 index 00000000000000..f433cc1331389f --- /dev/null +++ b/packages/react-native-popup-menu-android/index.js @@ -0,0 +1,12 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +export {default} from './js/PopupMenuAndroid'; +export type {PopupMenuAndroidInstance} from './js/PopupMenuAndroid'; diff --git a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.android.js b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.android.js similarity index 89% rename from packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.android.js rename to packages/react-native-popup-menu-android/js/PopupMenuAndroid.android.js index 035a1da5b150d6..b97d45cb5a476d 100644 --- a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.android.js +++ b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.android.js @@ -8,13 +8,13 @@ * @flow strict-local */ -import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; -import type {SyntheticEvent} from '../../Types/CoreEventTypes'; import type {RefObject} from 'react'; +import type {HostComponent} from 'react-native'; +import type {SyntheticEvent} from 'react-native/Libraries/Types/CoreEventTypes'; import PopupMenuAndroidNativeComponent, { Commands, -} from './PopupMenuAndroidNativeComponent'; +} from './PopupMenuAndroidNativeComponent.android'; import nullthrows from 'nullthrows'; import * as React from 'react'; import {useCallback, useImperativeHandle, useRef} from 'react'; diff --git a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.d.ts b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.d.ts similarity index 89% rename from packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.d.ts rename to packages/react-native-popup-menu-android/js/PopupMenuAndroid.d.ts index 435df11d487fe7..8eab4875f38347 100644 --- a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.d.ts +++ b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.d.ts @@ -8,7 +8,7 @@ */ import type * as React from 'react'; -import {HostComponent} from '../../../types/public/ReactNativeTypes'; +import {HostComponent} from 'react-native'; type PopupMenuAndroidInstance = { show: () => void; diff --git a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.js b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.js similarity index 50% rename from packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.js rename to packages/react-native-popup-menu-android/js/PopupMenuAndroid.js index 94677cd6b8d23d..1331d32bd29722 100644 --- a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.js +++ b/packages/react-native-popup-menu-android/js/PopupMenuAndroid.js @@ -12,8 +12,29 @@ import type {RefObject} from 'react'; import type {Node} from 'react'; import * as React from 'react'; +import {StyleSheet, View} from 'react-native'; -const UnimplementedView = require('../UnimplementedViews/UnimplementedView'); +/** + * Common implementation for a simple stubbed view. Simply applies the view's styles to the inner + * View component and renders its children. + */ +class UnimplementedView extends React.Component<{children: Node}> { + render(): React.Node { + return ( + {this.props.children} + ); + } +} + +const styles = StyleSheet.create({ + unimplementedView: __DEV__ + ? { + alignSelf: 'flex-start', + borderColor: 'red', + borderWidth: 1, + } + : {}, +}); export type PopupMenuAndroidInstance = { +show: () => void, @@ -27,7 +48,7 @@ type Props = { }; function PopupMenuAndroid(props: Props): Node { - return ; + return {props.children}; } export default PopupMenuAndroid; diff --git a/packages/react-native/src/private/specs/components/PopupMenuAndroidNativeComponent.js b/packages/react-native-popup-menu-android/js/PopupMenuAndroidNativeComponent.android.js similarity index 68% rename from packages/react-native/src/private/specs/components/PopupMenuAndroidNativeComponent.js rename to packages/react-native-popup-menu-android/js/PopupMenuAndroidNativeComponent.android.js index 81801f65f4d0dd..7558d75415bfb0 100644 --- a/packages/react-native/src/private/specs/components/PopupMenuAndroidNativeComponent.js +++ b/packages/react-native-popup-menu-android/js/PopupMenuAndroidNativeComponent.android.js @@ -8,16 +8,16 @@ * @format */ -import type {ViewProps} from '../../../../Libraries/Components/View/ViewPropTypes'; -import type {HostComponent} from '../../../../Libraries/Renderer/shims/ReactNativeTypes'; +import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes'; +import type {HostComponent} from 'react-native/Libraries/Renderer/shims/ReactNativeTypes'; import type { DirectEventHandler, Int32, -} from '../../../../Libraries/Types/CodegenTypes'; +} from 'react-native/Libraries/Types/CodegenTypes'; -import codegenNativeCommands from '../../../../Libraries/Utilities/codegenNativeCommands'; -import codegenNativeComponent from '../../../../Libraries/Utilities/codegenNativeComponent'; import * as React from 'react'; +import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands'; +import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent'; type PopupMenuSelectionEvent = $ReadOnly<{ item: Int32, diff --git a/packages/react-native-popup-menu-android/package.json b/packages/react-native-popup-menu-android/package.json new file mode 100644 index 00000000000000..99f52be3071303 --- /dev/null +++ b/packages/react-native-popup-menu-android/package.json @@ -0,0 +1,42 @@ +{ + "name": "@react-native/popup-menu-android", + "version": "0.75.0-main", + "description": "PopupMenu for the Android platform", + "react-native": "js/PopupMenuAndroid", + "source": "js/PopupMenuAndroid", + "files": [ + "js", + "android", + "!android/build", + "!**/__tests__", + "!**/__fixtures__", + "!**/__mocks__" + ], + "keywords": [ + "react-native", + "android" + ], + "license": "MIT", + "devDependencies": { + "@react-native/codegen": "0.75.0-main" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + }, + "dependencies": { + "nullthrows": "^1.1.1" + }, + "codegenConfig": { + "name": "ReactPopupMenuAndroidSpecs", + "type": "components", + "jsSrcsDir": "js", + "outputDir": { + "android": "android" + }, + "includesGeneratedCode": true, + "android": { + "javaPackageName": "com.facebook.react.viewmanagers" + } + } +} diff --git a/packages/react-native-test-renderer/package.json b/packages/react-native-test-renderer/package.json index 4b90093f6fc2cb..3c0da0cc18c6c5 100644 --- a/packages/react-native-test-renderer/package.json +++ b/packages/react-native-test-renderer/package.json @@ -1,16 +1,18 @@ { - "name": "@react-native/test-renderer", - "private": true, - "version": "0.0.0", - "description": "A Test rendering library for React Native", - "license": "MIT", - "devDependencies": { - "@babel/core": "^7.20.0", - "@babel/plugin-transform-react-jsx": "^7.0.0", - "@babel/preset-env": "^7.20.0", - "@babel/preset-flow": "^7.20.0" - }, - "dependencies": {}, - "main": "src/index.js", - "peerDependencies": { "jest": "^29.7.0" } + "name": "@react-native/test-renderer", + "private": true, + "version": "0.75.0-main", + "description": "A Test rendering library for React Native", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.20.0", + "@babel/plugin-transform-react-jsx": "^7.0.0", + "@babel/preset-env": "^7.20.0", + "@babel/preset-flow": "^7.20.0" + }, + "dependencies": {}, + "main": "src/index.js", + "peerDependencies": { + "jest": "^29.7.0" } +} diff --git a/packages/react-native/Libraries/Animated/__tests__/AnimatedNative-test.js b/packages/react-native/Libraries/Animated/__tests__/AnimatedNative-test.js index d331d283029c51..67d1cf29113655 100644 --- a/packages/react-native/Libraries/Animated/__tests__/AnimatedNative-test.js +++ b/packages/react-native/Libraries/Animated/__tests__/AnimatedNative-test.js @@ -23,6 +23,7 @@ jest // findNodeHandle is imported from RendererProxy so mock that whole module. .setMock('../../ReactNative/RendererProxy', {findNodeHandle: () => 1}); +import {format} from 'node:util'; import * as React from 'react'; import TestRenderer from 'react-test-renderer'; @@ -295,11 +296,13 @@ describe('Native Animated', () => { useNativeDriver: true, }); + const consoleError = console.error; jest.spyOn(console, 'error').mockImplementationOnce((...args) => { - if (args[0].startsWith('The above error occurred in the')) { + const message = format(args); + if (message.includes('The above error occurred in the')) { return; } - console.errorDebug(...args); + consoleError(...args); }); expect(() => { diff --git a/packages/react-native/Libraries/Animated/createAnimatedComponent.js b/packages/react-native/Libraries/Animated/createAnimatedComponent.js index 78b66e094812d2..90878ca81bd6db 100644 --- a/packages/react-native/Libraries/Animated/createAnimatedComponent.js +++ b/packages/react-native/Libraries/Animated/createAnimatedComponent.js @@ -8,19 +8,12 @@ * @format */ -import View from '../Components/View/View'; import useMergeRefs from '../Utilities/useMergeRefs'; import useAnimatedProps from './useAnimatedProps'; import * as React from 'react'; // $FlowFixMe[deprecated-type] -export type AnimatedProps = $ObjMap< - Props & - $ReadOnly<{ - passthroughAnimatedPropExplicitValues?: React.ElementConfig, - }>, - () => any, ->; +export type AnimatedProps = $ObjMap any>; export type AnimatedComponentType< Props: {...}, @@ -43,19 +36,9 @@ export default function createAnimatedComponent( // transformed and Pressable, onPress will not work after transform // without these passthrough values. // $FlowFixMe[prop-missing] - const {passthroughAnimatedPropExplicitValues, style} = reducedProps; - const {style: passthroughStyle, ...passthroughProps} = - passthroughAnimatedPropExplicitValues ?? {}; - const mergedStyle = {...style, ...passthroughStyle}; + const {style} = reducedProps; - return ( - - ); + return ; }, ); diff --git a/packages/react-native/Libraries/Animated/useAnimatedProps.js b/packages/react-native/Libraries/Animated/useAnimatedProps.js index 6be9fac9cd86cf..7350b0951e7bb8 100644 --- a/packages/react-native/Libraries/Animated/useAnimatedProps.js +++ b/packages/react-native/Libraries/Animated/useAnimatedProps.js @@ -74,40 +74,67 @@ export default function useAnimatedProps( // every animation frame. When using the native driver, this callback is // called when the animation completes. onUpdateRef.current = () => { + if (process.env.NODE_ENV === 'test') { + // Check 1: this is a test. + // call `scheduleUpdate` to bypass use of setNativeProps. + return scheduleUpdate(); + } + + const isFabricNode = isFabricInstance(instance); + if (node.__isNative) { + // Check 2: this is an animation driven by native. + // In native driven animations, this callback is only called once the animation completes. + if (isFabricNode) { + // Call `scheduleUpdate` to synchronise Fiber and Shadow tree. + // Must not be called in Paper. + scheduleUpdate(); + } + return; + } + if ( - process.env.NODE_ENV === 'test' || typeof instance !== 'object' || - typeof instance?.setNativeProps !== 'function' || - (isFabricInstance(instance) && !useNativePropsInFabric) + typeof instance?.setNativeProps !== 'function' ) { - // Schedule an update for this component to update `reducedProps`, - // but do not compute it immediately. If a parent also updated, we - // need to merge those new props in before updating. - scheduleUpdate(); - } else if (!node.__isNative) { + // Check 3: the instance does not support setNativeProps. Call `scheduleUpdate`. + return scheduleUpdate(); + } + + if (!isFabricNode) { + // Check 4: this is a paper instance, call setNativeProps. // $FlowIgnore[not-a-function] - Assume it's still a function. // $FlowFixMe[incompatible-use] - instance.setNativeProps(node.__getAnimatedValue()); - if (isFabricInstance(instance)) { - // Keeping state of Fiber tree and Shadow tree in sync. - // - // This is done by calling `scheduleUpdate` which will trigger a commit. - // However, React commit is not fast enough to drive animations. - // This is where setNativeProps comes in handy but the state between - // Fiber tree and Shadow tree needs to be kept in sync. - // The goal is to call `scheduleUpdate` as little as possible to maintain - // performance but frequently enough to keep state in sync. - // Debounce is set to 48ms, which is 3 * the duration of a frame. - // 3 frames was the highest value where flickering state was not observed. - if (timerRef.current != null) { - clearTimeout(timerRef.current); - } - timerRef.current = setTimeout(() => { - timerRef.current = null; - scheduleUpdate(); - }, 48); - } + return instance.setNativeProps(node.__getAnimatedValue()); + } + + if (!useNativePropsInFabric) { + // Check 5: setNativeProps are disabled. + return scheduleUpdate(); } + + // This is a Fabric instance and setNativeProps is supported. + + // $FlowIgnore[not-a-function] - Assume it's still a function. + // $FlowFixMe[incompatible-use] + instance.setNativeProps(node.__getAnimatedValue()); + + // Keeping state of Fiber tree and Shadow tree in sync. + // + // This is done by calling `scheduleUpdate` which will trigger a commit. + // However, React commit is not fast enough to drive animations. + // This is where setNativeProps comes in handy but the state between + // Fiber tree and Shadow tree needs to be kept in sync. + // The goal is to call `scheduleUpdate` as little as possible to maintain + // performance but frequently enough to keep state in sync. + // Debounce is set to 48ms, which is 3 * the duration of a frame. + // 3 frames was the highest value where flickering state was not observed. + if (timerRef.current != null) { + clearTimeout(timerRef.current); + } + timerRef.current = setTimeout(() => { + timerRef.current = null; + scheduleUpdate(); + }, 48); }; const target = getEventTarget(instance); diff --git a/packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.cpp b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate+Protected.h similarity index 50% rename from packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.cpp rename to packages/react-native/Libraries/AppDelegate/RCTAppDelegate+Protected.h index 604122a6ce41e7..2321b43c4da971 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.cpp +++ b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate+Protected.h @@ -5,13 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -#include "UnbatchedEventQueue.h" +#if defined(__cplusplus) -namespace facebook::react { +#import +#import "RCTAppDelegate.h" -void UnbatchedEventQueue::onEnqueue() const { - eventBeat_->request(); - eventBeat_->induce(); -} +@interface RCTAppDelegate () +@end -} // namespace facebook::react +#endif diff --git a/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.h b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.h index dd234fb7b1616d..741dfa92f7fcdc 100644 --- a/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.h +++ b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.h @@ -6,7 +6,9 @@ */ #import +#import #import +#import "RCTRootViewFactory.h" @class RCTBridge; @protocol RCTBridgeDelegate; @@ -57,9 +59,12 @@ NS_ASSUME_NONNULL_BEGIN /// The window object, used to render the UViewControllers @property (nonatomic, strong, nonnull) UIWindow *window; -@property (nonatomic, strong, nullable) RCTBridge *bridge; +@property (nonatomic, nullable) RCTBridge *bridge; @property (nonatomic, strong, nullable) NSString *moduleName; @property (nonatomic, strong, nullable) NSDictionary *initialProps; +@property (nonatomic, strong, nonnull) RCTRootViewFactory *rootViewFactory; + +@property (nonatomic, nullable) RCTSurfacePresenterBridgeAdapter *bridgeAdapter; /** * It creates a `RCTBridge` using a delegate and some launch options. @@ -126,12 +131,10 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)setRootView:(UIView *)rootView toRootViewController:(UIViewController *)rootViewController; -/// This method controls whether the App will use RuntimeScheduler. Only applicable in the legacy architecture. -/// -/// @return: `YES` to use RuntimeScheduler, `NO` to use JavaScript scheduler. The default value is `YES`. -- (BOOL)runtimeSchedulerEnabled; - -@property (nonatomic, strong) RCTSurfacePresenterBridgeAdapter *bridgeAdapter; +/** + * The default `RCTColorSpace` for the app. It defaults to `RCTColorSpaceSRGB`. + */ +@property (nonatomic, readonly) RCTColorSpace defaultColorSpace; /// This method returns a map of Component Descriptors and Components classes that needs to be registered in the /// new renderer. The Component Descriptor is a string which represent the name used in JS to refer to the native diff --git a/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.mm b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.mm index a53a42303d7d40..4e3fa2f8bdbca5 100644 --- a/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.mm +++ b/packages/react-native/Libraries/AppDelegate/RCTAppDelegate.mm @@ -6,12 +6,16 @@ */ #import "RCTAppDelegate.h" -#import +#import #import #import #import #import -#import +#import +#import +#import +#import +#import "RCTAppDelegate+Protected.h" #import "RCTAppSetupUtils.h" #if RN_DISABLE_OSS_PLUGIN_HEADER @@ -19,104 +23,41 @@ #else #import #endif -#import #import #import -#import -#import -#import -#import #if USE_HERMES #import #else #import #endif -#import -#import -#import -#import -#import -#import -#import - -@interface RCTAppDelegate () < - RCTTurboModuleManagerDelegate, - RCTComponentViewFactoryComponentProvider, - RCTContextContainerHandling> { - std::shared_ptr _reactNativeConfig; - facebook::react::ContextContainer::Shared _contextContainer; -} -@end - -static NSDictionary *updateInitialProps(NSDictionary *initialProps, BOOL isFabricEnabled) -{ - NSMutableDictionary *mutableProps = [initialProps mutableCopy] ?: [NSMutableDictionary new]; - return mutableProps; -} +#import +#import -@interface RCTAppDelegate () { - std::shared_ptr _runtimeScheduler; -} +@interface RCTAppDelegate () @end -@implementation RCTAppDelegate { - RCTHost *_reactHost; -} - -- (instancetype)init -{ - if (self = [super init]) { - _contextContainer = std::make_shared(); - _reactNativeConfig = std::make_shared(); - _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); - } - return self; -} +@implementation RCTAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - RCTSetNewArchEnabled([self newArchEnabled]); - BOOL enableTM = self.turboModuleEnabled; - BOOL fabricEnabled = self.fabricEnabled; - BOOL enableBridgeless = self.bridgelessEnabled; - - NSDictionary *initProps = updateInitialProps([self prepareInitialProps], fabricEnabled); + [self _setUpFeatureFlags]; - RCTAppSetupPrepareApp(application, enableTM); + RCTSetNewArchEnabled([self newArchEnabled]); + [RCTColorSpaceUtils applyDefaultColorSpace:self.defaultColorSpace]; + RCTAppSetupPrepareApp(application, self.turboModuleEnabled); - UIView *rootView; - if (enableBridgeless) { - // Enable native view config interop only if both bridgeless mode and Fabric is enabled. - RCTSetUseNativeViewConfigsInBridgelessMode(fabricEnabled); + self.rootViewFactory = [self createRCTRootViewFactory]; - // Enable TurboModule interop by default in Bridgeless mode - RCTEnableTurboModuleInterop(YES); - RCTEnableTurboModuleInteropBridgeProxy(YES); + UIView *rootView = [self.rootViewFactory viewWithModuleName:self.moduleName + initialProperties:self.initialProps + launchOptions:launchOptions]; - [self createReactHost]; + if (self.newArchEnabled || self.fabricEnabled) { [RCTComponentViewFactory currentComponentViewFactory].thirdPartyFabricComponentsProvider = self; - RCTFabricSurface *surface = [_reactHost createSurfaceWithModuleName:self.moduleName initialProperties:initProps]; - - RCTSurfaceHostingProxyRootView *surfaceHostingProxyRootView = [[RCTSurfaceHostingProxyRootView alloc] - initWithSurface:surface - sizeMeasureMode:RCTSurfaceSizeMeasureModeWidthExact | RCTSurfaceSizeMeasureModeHeightExact]; - - rootView = (RCTRootView *)surfaceHostingProxyRootView; - rootView.backgroundColor = [UIColor systemBackgroundColor]; - } else { - if (!self.bridge) { - self.bridge = [self createBridgeWithDelegate:self launchOptions:launchOptions]; - } - if ([self newArchEnabled]) { - self.bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:self.bridge - contextContainer:_contextContainer]; - self.bridge.surfacePresenter = self.bridgeAdapter.surfacePresenter; - - [RCTComponentViewFactory currentComponentViewFactory].thirdPartyFabricComponentsProvider = self; - } - rootView = [self createRootViewWithBridge:self.bridge moduleName:self.moduleName initProps:initProps]; } + [self _logWarnIfCreateRootViewWithBridgeIsOverridden]; [self customizeRootView:(RCTRootView *)rootView]; + self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [self createRootViewController]; [self setRootView:rootView toRootViewController:rootViewController]; @@ -139,26 +80,15 @@ - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge return nil; } -- (NSDictionary *)prepareInitialProps -{ - return self.initialProps; -} - - (RCTBridge *)createBridgeWithDelegate:(id)delegate launchOptions:(NSDictionary *)launchOptions { return [[RCTBridge alloc] initWithDelegate:delegate launchOptions:launchOptions]; } -- (void)customizeRootView:(RCTRootView *)rootView -{ - // Override point for customization after application launch. -} - - (UIView *)createRootViewWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName initProps:(NSDictionary *)initProps { - [self _logWarnIfCreateRootViewWithBridgeIsOverridden]; BOOL enableFabric = self.fabricEnabled; UIView *rootView = RCTAppSetupDefaultRootView(bridge, moduleName, initProps, enableFabric); @@ -192,9 +122,9 @@ - (void)setRootView:(UIView *)rootView toRootViewController:(UIViewController *) rootViewController.view = rootView; } -- (BOOL)runtimeSchedulerEnabled +- (void)customizeRootView:(RCTRootView *)rootView { - return YES; + // Override point for customization after application launch. } #pragma mark - UISceneDelegate @@ -207,23 +137,9 @@ - (void)windowScene:(UIWindowScene *)windowScene [[NSNotificationCenter defaultCenter] postNotificationName:RCTWindowFrameDidChangeNotification object:self]; } -#pragma mark - RCTCxxBridgeDelegate - -- (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge +- (RCTColorSpace)defaultColorSpace { - _runtimeScheduler = std::make_shared(RCTRuntimeExecutorFromBridge(bridge)); - if ([self newArchEnabled]) { - std::shared_ptr callInvoker = - std::make_shared(_runtimeScheduler); - RCTTurboModuleManager *turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge - delegate:self - jsInvoker:callInvoker]; - _contextContainer->erase("RuntimeScheduler"); - _contextContainer->insert("RuntimeScheduler", _runtimeScheduler); - return RCTAppSetupDefaultJsExecutorFactory(bridge, turboModuleManager, _runtimeScheduler); - } else { - return RCTAppSetupJsExecutorFactoryForOldArch(bridge, _runtimeScheduler); - } + return RCTColorSpaceSRGB; } #pragma mark - New Arch Enabled settings @@ -252,11 +168,33 @@ - (BOOL)bridgelessEnabled return [self newArchEnabled]; } -#pragma mark - RCTComponentViewFactoryComponentProvider +- (NSURL *)bundleURL +{ + [NSException raise:@"RCTAppDelegate::bundleURL not implemented" + format:@"Subclasses must implement a valid getBundleURL method"]; + return nullptr; +} -- (NSDictionary> *)thirdPartyFabricComponents +#pragma mark - Bridge and Bridge Adapter properties + +- (RCTBridge *)bridge { - return @{}; + return self.rootViewFactory.bridge; +} + +- (RCTSurfacePresenterBridgeAdapter *)bridgeAdapter +{ + return self.rootViewFactory.bridgeAdapter; +} + +- (void)setBridge:(RCTBridge *)bridge +{ + self.rootViewFactory.bridge = bridge; +} + +- (void)setBridgeAdapter:(RCTSurfacePresenterBridgeAdapter *)bridgeAdapter +{ + self.rootViewFactory.bridgeAdapter = bridgeAdapter; } #pragma mark - RCTTurboModuleManagerDelegate @@ -273,6 +211,14 @@ - (Class)getModuleClassFromName:(const char *)name - (std::shared_ptr)getTurboModule:(const std::string &)name jsInvoker:(std::shared_ptr)jsInvoker { + if (name == facebook::react::NativeReactNativeFeatureFlags::kModuleName) { + return std::make_shared(jsInvoker); + } + + if (name == facebook::react::NativeMicrotasks::kModuleName) { + return std::make_shared(jsInvoker); + } + return nullptr; } @@ -288,43 +234,58 @@ - (Class)getModuleClassFromName:(const char *)name return RCTAppSetupDefaultModuleFromClass(moduleClass); } -#pragma mark - New Arch Utilities +#pragma mark - RCTComponentViewFactoryComponentProvider -- (void)createReactHost +- (NSDictionary> *)thirdPartyFabricComponents { - __weak __typeof(self) weakSelf = self; - _reactHost = [[RCTHost alloc] initWithBundleURL:[self bundleURL] - hostDelegate:nil - turboModuleManagerDelegate:self - jsEngineProvider:^std::shared_ptr() { - return [weakSelf createJSRuntimeFactory]; - }]; - [_reactHost setBundleURLProvider:^NSURL *() { - return [weakSelf bundleURL]; - }]; - [_reactHost setContextContainerHandler:self]; - [_reactHost start]; + return @{}; } -- (std::shared_ptr)createJSRuntimeFactory +- (RCTRootViewFactory *)createRCTRootViewFactory { -#if USE_HERMES - return std::make_shared(_reactNativeConfig, nullptr); -#else - return std::make_shared(); -#endif -} + RCTRootViewFactoryConfiguration *configuration = + [[RCTRootViewFactoryConfiguration alloc] initWithBundleURL:self.bundleURL + newArchEnabled:self.fabricEnabled + turboModuleEnabled:self.turboModuleEnabled + bridgelessEnabled:self.bridgelessEnabled]; -- (void)didCreateContextContainer:(std::shared_ptr)contextContainer -{ - contextContainer->insert("ReactNativeConfig", _reactNativeConfig); + __weak __typeof(self) weakSelf = self; + configuration.createRootViewWithBridge = ^UIView *(RCTBridge *bridge, NSString *moduleName, NSDictionary *initProps) + { + return [weakSelf createRootViewWithBridge:bridge moduleName:moduleName initProps:initProps]; + }; + + configuration.createBridgeWithDelegate = ^RCTBridge *(id delegate, NSDictionary *launchOptions) + { + return [weakSelf createBridgeWithDelegate:delegate launchOptions:launchOptions]; + }; + + return [[RCTRootViewFactory alloc] initWithConfiguration:configuration andTurboModuleManagerDelegate:self]; } -- (NSURL *)bundleURL +#pragma mark - Feature Flags + +class RCTAppDelegateBridgelessFeatureFlags : public facebook::react::ReactNativeFeatureFlagsDefaults { + public: + bool useModernRuntimeScheduler() override + { + return true; + } + bool enableMicrotasks() override + { + return true; + } + bool batchRenderingUpdatesInEventLoop() override + { + return true; + } +}; + +- (void)_setUpFeatureFlags { - [NSException raise:@"RCTAppDelegate::bundleURL not implemented" - format:@"Subclasses must implement a valid getBundleURL method"]; - return nullptr; + if ([self bridgelessEnabled]) { + facebook::react::ReactNativeFeatureFlags::override(std::make_unique()); + } } @end diff --git a/packages/react-native/Libraries/AppDelegate/RCTAppSetupUtils.mm b/packages/react-native/Libraries/AppDelegate/RCTAppSetupUtils.mm index 6c5f7a4a13bde5..9cc4e2c63a5031 100644 --- a/packages/react-native/Libraries/AppDelegate/RCTAppSetupUtils.mm +++ b/packages/react-native/Libraries/AppDelegate/RCTAppSetupUtils.mm @@ -27,12 +27,9 @@ // jsinspector-modern #import -#if __has_include() +#if __has_include() #define USE_OSS_CODEGEN 1 -#import -#elif __has_include() -#define USE_OSS_CODEGEN 1 -#import +#import #else // Meta internal system do not generate the RCTModulesConformingToProtocolsProvider.h file #define USE_OSS_CODEGEN 0 diff --git a/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.h b/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.h new file mode 100644 index 00000000000000..5047802ebc5eda --- /dev/null +++ b/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import +#import +#import + +@protocol RCTCxxBridgeDelegate; +@protocol RCTComponentViewFactoryComponentProvider; +@protocol RCTTurboModuleManagerDelegate; +@class RCTBridge; +@class RCTRootView; +@class RCTSurfacePresenterBridgeAdapter; + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Blocks' definitions +typedef UIView *_Nonnull ( + ^RCTCreateRootViewWithBridgeBlock)(RCTBridge *bridge, NSString *moduleName, NSDictionary *initProps); +typedef RCTBridge *_Nonnull ( + ^RCTCreateBridgeWithDelegateBlock)(id delegate, NSDictionary *launchOptions); + +#pragma mark - RCTRootViewFactory Configuration +@interface RCTRootViewFactoryConfiguration : NSObject + +/// This property controls whether the App will use the Fabric renderer of the New Architecture or not. +@property (nonatomic, assign, readonly) BOOL fabricEnabled; + +/// This property controls whether React Native's new initialization layer is enabled. +@property (nonatomic, assign, readonly) BOOL bridgelessEnabled; + +/// This method controls whether the `turboModules` feature of the New Architecture is turned on or off +@property (nonatomic, assign, readonly) BOOL turboModuleEnabled; + +/// Return the bundle URL for the main bundle. +@property (nonatomic) NSURL *bundleURL; + +/** + * Use this method to initialize a new instance of `RCTRootViewFactoryConfiguration` by passing a `bundleURL` + * + * Which is the location of the JavaScript source file. When running from the packager + * this should be an absolute URL, e.g. `http://localhost:8081/index.ios.bundle`. + * When running from a locally bundled JS file, this should be a `file://` url + * pointing to a path inside the app resources, e.g. `file://.../main.jsbundle`. + * + */ +- (instancetype)initWithBundleURL:(NSURL *)bundleURL + newArchEnabled:(BOOL)newArchEnabled + turboModuleEnabled:(BOOL)turboModuleEnabled + bridgelessEnabled:(BOOL)bridgelessEnabled; + +/** + * Block that allows to override logic of creating root view instance. + * It creates a `UIView` starting from a bridge, a module name and a set of initial properties. + * By default, it is invoked using the bridge created by `RCTCreateBridgeWithDelegateBlock` (or the default + * implementation) and the `moduleName` variable comes from `viewWithModuleName:initialProperties:launchOptions` of + * `RCTRootViewFactory`. + * + * @parameter: bridge - an instance of the `RCTBridge` object. + * @parameter: moduleName - the name of the app, used by Metro to resolve the module. + * @parameter: initProps - a set of initial properties. + * + * @returns: a UIView properly configured with a bridge for React Native. + */ +@property (nonatomic, nullable) RCTCreateRootViewWithBridgeBlock createRootViewWithBridge; + +/** + * Block that allows to override default behavior of creating bridge. + * It should return `RCTBridge` using a delegate and some launch options. + * + * By default, it is invoked passing `self` as a delegate. + * + * @parameter: delegate - an object that implements the `RCTBridgeDelegate` protocol. + * @parameter: launchOptions - a dictionary with a set of options. + * + * @returns: a newly created instance of RCTBridge. + */ +@property (nonatomic, nullable) RCTCreateBridgeWithDelegateBlock createBridgeWithDelegate; + +@end + +#pragma mark - RCTRootViewFactory +/** + * The RCTRootViewFactory is an utility class that encapsulates the logic of creating a new RCTRootView based on the + * current state of the environment. It allows you to initialize your app root view for old architecture, new + * architecture and bridgless mode. + * + * This class is used to initalize rootView in RCTAppDelegate, but you can also use it separately. + * + * Create a new instance of this class (make sure to retain it) and call the + * `viewWithModuleName:initialProperties:launchOptions` method to create new RCTRootView. + */ +@interface RCTRootViewFactory : NSObject + +@property (nonatomic, strong, nullable) RCTBridge *bridge; +@property (nonatomic, strong, nullable) RCTSurfacePresenterBridgeAdapter *bridgeAdapter; + +- (instancetype)initWithConfiguration:(RCTRootViewFactoryConfiguration *)configuration + andTurboModuleManagerDelegate:(id)turboModuleManagerDelegate; + +/** + * This method can be used to create new RCTRootViews on demand. + * + * @parameter: moduleName - the name of the app, used by Metro to resolve the module. + * @parameter: initialProperties - a set of initial properties. + * @parameter: moduleName - a dictionary with a set of options. + */ +- (UIView *_Nonnull)viewWithModuleName:(NSString *)moduleName + initialProperties:(NSDictionary *__nullable)initialProperties + launchOptions:(NSDictionary *__nullable)launchOptions; + +- (UIView *_Nonnull)viewWithModuleName:(NSString *)moduleName + initialProperties:(NSDictionary *__nullable)initialProperties; + +- (UIView *_Nonnull)viewWithModuleName:(NSString *)moduleName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.mm b/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.mm new file mode 100644 index 00000000000000..c71ea624423433 --- /dev/null +++ b/packages/react-native/Libraries/AppDelegate/RCTRootViewFactory.mm @@ -0,0 +1,254 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RCTRootViewFactory.h" +#import +#import +#import +#import +#import +#import +#import "RCTAppDelegate.h" +#import "RCTAppSetupUtils.h" + +#if RN_DISABLE_OSS_PLUGIN_HEADER +#import +#else +#import +#endif +#import +#import +#import +#import +#import +#import +#import +#if USE_HERMES +#import +#else +#import +#endif +#import +#import +#import +#import +#import +#import +#import + +static NSString *const kRNConcurrentRoot = @"concurrentRoot"; + +static NSDictionary *updateInitialProps(NSDictionary *initialProps, BOOL isFabricEnabled) +{ + NSMutableDictionary *mutableProps = initialProps != NULL ? [initialProps mutableCopy] : [NSMutableDictionary new]; + // Hardcoding the Concurrent Root as it it not recommended to + // have the concurrentRoot turned off when Fabric is enabled. + mutableProps[kRNConcurrentRoot] = @(isFabricEnabled); + return mutableProps; +} + +@implementation RCTRootViewFactoryConfiguration + +- (instancetype)initWithBundleURL:(NSURL *)bundleURL + newArchEnabled:(BOOL)newArchEnabled + turboModuleEnabled:(BOOL)turboModuleEnabled + bridgelessEnabled:(BOOL)bridgelessEnabled +{ + if (self = [super init]) { + _bundleURL = bundleURL; + _fabricEnabled = newArchEnabled; + _turboModuleEnabled = turboModuleEnabled; + _bridgelessEnabled = bridgelessEnabled; + } + return self; +} + +@end + +@interface RCTRootViewFactory () { + std::shared_ptr _reactNativeConfig; + facebook::react::ContextContainer::Shared _contextContainer; +} +@end + +@interface RCTRootViewFactory () { + std::shared_ptr _runtimeScheduler; +} +@end + +@implementation RCTRootViewFactory { + RCTHost *_reactHost; + RCTRootViewFactoryConfiguration *_configuration; + __weak id _turboModuleManagerDelegate; +} + +- (instancetype)initWithConfiguration:(RCTRootViewFactoryConfiguration *)configuration + andTurboModuleManagerDelegate:(id)turboModuleManagerDelegate +{ + if (self = [super init]) { + _configuration = configuration; + _contextContainer = std::make_shared(); + _reactNativeConfig = std::make_shared(); + _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); + _turboModuleManagerDelegate = turboModuleManagerDelegate; + } + return self; +} + +- (UIView *)viewWithModuleName:(NSString *)moduleName initialProperties:(NSDictionary *)initialProperties +{ + return [self viewWithModuleName:moduleName initialProperties:initialProperties launchOptions:nil]; +} + +- (UIView *)viewWithModuleName:(NSString *)moduleName +{ + return [self viewWithModuleName:moduleName initialProperties:nil launchOptions:nil]; +} + +- (UIView *)viewWithModuleName:(NSString *)moduleName + initialProperties:(NSDictionary *)initialProperties + launchOptions:(NSDictionary *)launchOptions +{ + NSDictionary *initProps = updateInitialProps(initialProperties, self->_configuration.fabricEnabled); + + if (self->_configuration.bridgelessEnabled) { + // Enable native view config interop only if both bridgeless mode and Fabric is enabled. + RCTSetUseNativeViewConfigsInBridgelessMode(self->_configuration.fabricEnabled); + + // Enable TurboModule interop by default in Bridgeless mode + RCTEnableTurboModuleInterop(YES); + RCTEnableTurboModuleInteropBridgeProxy(YES); + + [self createReactHostIfNeeded]; + + RCTFabricSurface *surface = [_reactHost createSurfaceWithModuleName:moduleName initialProperties:initProps]; + + RCTSurfaceHostingProxyRootView *surfaceHostingProxyRootView = [[RCTSurfaceHostingProxyRootView alloc] + initWithSurface:surface + sizeMeasureMode:RCTSurfaceSizeMeasureModeWidthExact | RCTSurfaceSizeMeasureModeHeightExact]; + + surfaceHostingProxyRootView.backgroundColor = [UIColor systemBackgroundColor]; + return surfaceHostingProxyRootView; + } + + [self createBridgeIfNeeded:launchOptions]; + [self createBridgeAdapterIfNeeded]; + + if (self->_configuration.createRootViewWithBridge != nil) { + return self->_configuration.createRootViewWithBridge(self.bridge, moduleName, initProps); + } + + return [self createRootViewWithBridge:self.bridge moduleName:moduleName initProps:initProps]; +} + +- (RCTBridge *)createBridgeWithDelegate:(id)delegate launchOptions:(NSDictionary *)launchOptions +{ + return [[RCTBridge alloc] initWithDelegate:delegate launchOptions:launchOptions]; +} + +- (UIView *)createRootViewWithBridge:(RCTBridge *)bridge + moduleName:(NSString *)moduleName + initProps:(NSDictionary *)initProps +{ + BOOL enableFabric = self->_configuration.fabricEnabled; + UIView *rootView = RCTAppSetupDefaultRootView(bridge, moduleName, initProps, enableFabric); + + rootView.backgroundColor = [UIColor systemBackgroundColor]; + + return rootView; +} + +#pragma mark - RCTCxxBridgeDelegate +- (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge +{ + _runtimeScheduler = std::make_shared(RCTRuntimeExecutorFromBridge(bridge)); + if (RCTIsNewArchEnabled()) { + std::shared_ptr callInvoker = + std::make_shared(_runtimeScheduler); + RCTTurboModuleManager *turboModuleManager = + [[RCTTurboModuleManager alloc] initWithBridge:bridge + delegate:_turboModuleManagerDelegate + jsInvoker:callInvoker]; + _contextContainer->erase("RuntimeScheduler"); + _contextContainer->insert("RuntimeScheduler", _runtimeScheduler); + return RCTAppSetupDefaultJsExecutorFactory(bridge, turboModuleManager, _runtimeScheduler); + } else { + return RCTAppSetupJsExecutorFactoryForOldArch(bridge, _runtimeScheduler); + } +} + +- (void)createBridgeIfNeeded:(NSDictionary *)launchOptions +{ + if (self.bridge != nil) { + return; + } + + if (self->_configuration.createBridgeWithDelegate != nil) { + self.bridge = self->_configuration.createBridgeWithDelegate(self, launchOptions); + } else { + self.bridge = [self createBridgeWithDelegate:self launchOptions:launchOptions]; + } +} + +- (void)createBridgeAdapterIfNeeded +{ + if (!self->_configuration.fabricEnabled || self.bridgeAdapter) { + return; + } + + self.bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:self.bridge + contextContainer:_contextContainer]; + self.bridge.surfacePresenter = self.bridgeAdapter.surfacePresenter; +} + +#pragma mark - New Arch Utilities + +- (void)createReactHostIfNeeded +{ + if (_reactHost) { + return; + } + + __weak __typeof(self) weakSelf = self; + _reactHost = [[RCTHost alloc] initWithBundleURL:[self bundleURL] + hostDelegate:nil + turboModuleManagerDelegate:_turboModuleManagerDelegate + jsEngineProvider:^std::shared_ptr() { + return [weakSelf createJSRuntimeFactory]; + }]; + [_reactHost setBundleURLProvider:^NSURL *() { + return [weakSelf bundleURL]; + }]; + [_reactHost setContextContainerHandler:self]; + [_reactHost start]; +} + +- (std::shared_ptr)createJSRuntimeFactory +{ +#if USE_HERMES + return std::make_shared(_reactNativeConfig, nullptr); +#else + return std::make_shared(); +#endif +} + +- (void)didCreateContextContainer:(std::shared_ptr)contextContainer +{ + contextContainer->insert("ReactNativeConfig", _reactNativeConfig); +} + +- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge +{ + return [self bundleURL]; +} + +- (NSURL *)bundleURL +{ + return self->_configuration.bundleURL; +} + +@end diff --git a/packages/react-native/Libraries/AppDelegate/React-RCTAppDelegate.podspec b/packages/react-native/Libraries/AppDelegate/React-RCTAppDelegate.podspec index 146ff1ea5ccf83..cbc952669aeecc 100644 --- a/packages/react-native/Libraries/AppDelegate/React-RCTAppDelegate.podspec +++ b/packages/react-native/Libraries/AppDelegate/React-RCTAppDelegate.podspec @@ -76,7 +76,9 @@ Pod::Spec.new do |s| s.dependency "React-RCTImage" s.dependency "React-CoreModules" s.dependency "React-nativeconfig" - s.dependency "React-Codegen" + s.dependency "ReactCodegen" + s.dependency "React-featureflagsnativemodule" + s.dependency "React-microtasksnativemodule" add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") @@ -89,6 +91,7 @@ Pod::Spec.new do |s| add_dependency(s, "React-utils") add_dependency(s, "React-debug") add_dependency(s, "React-rendererdebug") + add_dependency(s, "React-featureflags") if use_hermes s.dependency "React-hermes" diff --git a/packages/react-native/Libraries/Blob/React-RCTBlob.podspec b/packages/react-native/Libraries/Blob/React-RCTBlob.podspec index 8b48d45e7f4067..ee72d65b6378af 100644 --- a/packages/react-native/Libraries/Blob/React-RCTBlob.podspec +++ b/packages/react-native/Libraries/Blob/React-RCTBlob.podspec @@ -25,7 +25,7 @@ header_search_paths = [ "\"$(PODS_ROOT)/boost\"", "\"$(PODS_ROOT)/DoubleConversion\"", "\"$(PODS_ROOT)/fmt/include\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -55,7 +55,7 @@ Pod::Spec.new do |s| s.dependency "React-Core/RCTWebSocket" s.dependency "React-RCTNetwork" - add_dependency(s, "React-Codegen") + add_dependency(s, "ReactCodegen") add_dependency(s, "React-NativeModulesApple") add_dependency(s, "React-jsinspector", :framework_name => 'jsinspector_modern') add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) diff --git a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroidNativeComponent.js b/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroidNativeComponent.js deleted file mode 100644 index 05bbd5693155c5..00000000000000 --- a/packages/react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroidNativeComponent.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - * @flow strict-local - */ - -export * from '../../../src/private/specs/components/PopupMenuAndroidNativeComponent'; -import PopupMenuAndroidNativeComponent from '../../../src/private/specs/components/PopupMenuAndroidNativeComponent'; -export default PopupMenuAndroidNativeComponent; diff --git a/packages/react-native/Libraries/Components/ScrollView/ScrollView.js b/packages/react-native/Libraries/Components/ScrollView/ScrollView.js index 8d73e00a609496..d8814ccefc4846 100644 --- a/packages/react-native/Libraries/Components/ScrollView/ScrollView.js +++ b/packages/react-native/Libraries/Components/ScrollView/ScrollView.js @@ -266,33 +266,6 @@ type IOSProps = $ReadOnly<{| * @platform ios */ canCancelContentTouches?: ?boolean, - /** - * When set, the scroll view will adjust the scroll position so that the first child that is - * currently visible and at or beyond `minIndexForVisible` will not change position. This is - * useful for lists that are loading content in both directions, e.g. a chat thread, where new - * messages coming in might otherwise cause the scroll position to jump. A value of 0 is common, - * but other values such as 1 can be used to skip loading spinners or other content that should - * not maintain position. - * - * The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll - * to the top after making the adjustment if the user was within the threshold of the top before - * the adjustment was made. This is also useful for chat-like applications where you want to see - * new messages scroll into place, but not if the user has scrolled up a ways and it would be - * disruptive to scroll a bunch. - * - * Caveat 1: Reordering elements in the scrollview with this enabled will probably cause - * jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now, - * don't re-order the content of any ScrollViews or Lists that use this feature. - * - * Caveat 2: This simply uses `contentOffset` and `frame.origin` in native code to compute - * visibility. Occlusion, transforms, and other complexity won't be taken into account as to - * whether content is "visible" or not. - * - */ - maintainVisibleContentPosition?: ?$ReadOnly<{| - minIndexForVisible: number, - autoscrollToTopThreshold?: ?number, - |}>, /** * The maximum allowed zoom scale. The default value is 1.0. * @platform ios @@ -465,6 +438,20 @@ export type Props = $ReadOnly<{| * - `'fast'`: 0.99 on iOS, 0.9 on Android */ decelerationRate?: ?DecelerationRateType, + + /** + * *Experimental, iOS Only*. The API is experimental and will change in future releases. + * + * Controls how much distance is travelled after user stops scrolling. + * Value greater than 1 will increase the distance travelled. + * Value less than 1 will decrease the distance travelled. + * + * @deprecated + * + * The default value is 1. + */ + experimental_endDraggingSensitivityMultiplier?: ?number, + /** * When true, the scroll view's children are arranged horizontally in a row * instead of vertically in a column. The default value is false. @@ -505,6 +492,33 @@ export type Props = $ReadOnly<{| * - `true`, deprecated, use 'always' instead */ keyboardShouldPersistTaps?: ?('always' | 'never' | 'handled' | true | false), + /** + * When set, the scroll view will adjust the scroll position so that the first child that is + * partially or fully visible and at or beyond `minIndexForVisible` will not change position. + * This is useful for lists that are loading content in both directions, e.g. a chat thread, + * where new messages coming in might otherwise cause the scroll position to jump. A value of 0 + * is common, but other values such as 1 can be used to skip loading spinners or other content + * that should not maintain position. + * + * The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll + * to the top after making the adjustment if the user was within the threshold of the top before + * the adjustment was made. This is also useful for chat-like applications where you want to see + * new messages scroll into place, but not if the user has scrolled up a ways and it would be + * disruptive to scroll a bunch. + * + * Caveat 1: Reordering elements in the scrollview with this enabled will probably cause + * jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now, + * don't re-order the content of any ScrollViews or Lists that use this feature. + * + * Caveat 2: This simply uses `contentOffset` and `frame.origin` in native code to compute + * visibility. Occlusion, transforms, and other complexity won't be taken into account as to + * whether content is "visible" or not. + * + */ + maintainVisibleContentPosition?: ?$ReadOnly<{| + minIndexForVisible: number, + autoscrollToTopThreshold?: ?number, + |}>, /** * Called when the momentum scroll starts (scroll which occurs as the ScrollView glides to a stop). */ @@ -1733,8 +1747,11 @@ class ScrollView extends React.Component { this.props.horizontal === true ? styles.baseHorizontal : styles.baseVertical; + + const {experimental_endDraggingSensitivityMultiplier, ...otherProps} = + this.props; const props = { - ...this.props, + ...otherProps, alwaysBounceHorizontal, alwaysBounceVertical, style: StyleSheet.compose(baseStyle, this.props.style), @@ -1759,6 +1776,8 @@ class ScrollView extends React.Component { onTouchStart: this._handleTouchStart, onTouchCancel: this._handleTouchCancel, onScroll: this._handleScroll, + endDraggingSensitivityMultiplier: + experimental_endDraggingSensitivityMultiplier, scrollEventThrottle: hasStickyHeaders ? 1 : this.props.scrollEventThrottle, diff --git a/packages/react-native/Libraries/Components/ScrollView/ScrollViewNativeComponent.js b/packages/react-native/Libraries/Components/ScrollView/ScrollViewNativeComponent.js index 69ebcef0d56971..8c1126849022d2 100644 --- a/packages/react-native/Libraries/Components/ScrollView/ScrollViewNativeComponent.js +++ b/packages/react-native/Libraries/Components/ScrollView/ScrollViewNativeComponent.js @@ -46,6 +46,7 @@ export const __INTERNAL_VIEW_CONFIG: PartialViewConfig = }, decelerationRate: true, disableIntervalMomentum: true, + maintainVisibleContentPosition: true, pagingEnabled: true, scrollEnabled: true, showsVerticalScrollIndicator: true, @@ -59,6 +60,7 @@ export const __INTERNAL_VIEW_CONFIG: PartialViewConfig = sendMomentumEvents: true, borderRadius: true, nestedScrollEnabled: true, + scrollEventThrottle: true, borderStyle: true, borderRightColor: { process: require('../../StyleSheet/processColor').default, @@ -130,6 +132,7 @@ export const __INTERNAL_VIEW_CONFIG: PartialViewConfig = }, contentInsetAdjustmentBehavior: true, decelerationRate: true, + endDraggingSensitivityMultiplier: true, directionalLockEnabled: true, disableIntervalMomentum: true, indicatorStyle: true, diff --git a/packages/react-native/Libraries/Components/TextInput/RCTTextInputViewConfig.js b/packages/react-native/Libraries/Components/TextInput/RCTTextInputViewConfig.js index f91026796ce9cb..2875ebb776d4c5 100644 --- a/packages/react-native/Libraries/Components/TextInput/RCTTextInputViewConfig.js +++ b/packages/react-native/Libraries/Components/TextInput/RCTTextInputViewConfig.js @@ -79,18 +79,12 @@ const RCTTextInputViewConfig = { topTextInput: { registrationName: 'onTextInput', }, - topKeyPressSync: { - registrationName: 'onKeyPressSync', - }, topScroll: { registrationName: 'onScroll', }, topSelectionChange: { registrationName: 'onSelectionChange', }, - topChangeSync: { - registrationName: 'onChangeSync', - }, topContentSizeChange: { registrationName: 'onContentSizeChange', }, @@ -159,8 +153,6 @@ const RCTTextInputViewConfig = { onSelectionChange: true, onContentSizeChange: true, onScroll: true, - onChangeSync: true, - onKeyPressSync: true, onTextInput: true, }), }, diff --git a/packages/react-native/Libraries/Components/TextInput/TextInput.js b/packages/react-native/Libraries/Components/TextInput/TextInput.js index 7b522fe5dcb026..7034e6b6320f4b 100644 --- a/packages/react-native/Libraries/Components/TextInput/TextInput.js +++ b/packages/react-native/Libraries/Components/TextInput/TextInput.js @@ -741,33 +741,12 @@ export type Props = $ReadOnly<{| */ onChange?: ?(e: ChangeEvent) => mixed, - /** - * DANGER: this API is not stable and will change in the future. - * - * Callback will be called on the main thread and may result in dropped frames. - * Callback that is called when the text input's text changes. - * - * @platform ios - */ - unstable_onChangeSync?: ?(e: ChangeEvent) => mixed, - /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText?: ?(text: string) => mixed, - /** - * DANGER: this API is not stable and will change in the future. - * - * Callback will be called on the main thread and may result in dropped frames. - * Callback that is called when the text input's text changes. - * Changed text is passed as an argument to the callback handler. - * - * @platform ios - */ - unstable_onChangeTextSync?: ?(text: string) => mixed, - /** * Callback that is called when the text input's content size changes. * This will be called with @@ -796,21 +775,6 @@ export type Props = $ReadOnly<{| */ onKeyPress?: ?(e: KeyPressEvent) => mixed, - /** - * DANGER: this API is not stable and will change in the future. - * - * Callback will be called on the main thread and may result in dropped frames. - * - * Callback that is called when a key is pressed. - * This will be called with `{ nativeEvent: { key: keyValue } }` - * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and - * the typed-in character otherwise including `' '` for space. - * Fires before `onChange` callbacks. - * - * @platform ios - */ - unstable_onKeyPressSync?: ?(e: KeyPressEvent) => mixed, - /** * Called when a single tap gesture is detected. */ @@ -1158,8 +1122,8 @@ function InternalTextInput(props: Props): React.Node { typeof props.value === 'string' ? props.value : typeof props.defaultValue === 'string' - ? props.defaultValue - : ''; + ? props.defaultValue + : ''; // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value @@ -1308,26 +1272,6 @@ function InternalTextInput(props: Props): React.Node { setMostRecentEventCount(event.nativeEvent.eventCount); }; - const _onChangeSync = (event: ChangeEvent) => { - const currentText = event.nativeEvent.text; - props.unstable_onChangeSync && props.unstable_onChangeSync(event); - props.unstable_onChangeTextSync && - props.unstable_onChangeTextSync(currentText); - - if (inputRef.current == null) { - // calling `props.onChange` or `props.onChangeText` - // may clean up the input itself. Exits here. - return; - } - - setLastNativeText(currentText); - // This must happen last, after we call setLastNativeText. - // Different ordering can cause bugs when editing AndroidTextInputs - // with multiple Fragments. - // We must update this so that controlled input updates work. - setMostRecentEventCount(event.nativeEvent.eventCount); - }; - const _onSelectionChange = (event: SelectionChangeEvent) => { props.onSelectionChange && props.onSelectionChange(event); @@ -1470,10 +1414,6 @@ function InternalTextInput(props: Props): React.Node { style.paddingVertical == null && style.paddingTop == null)); - const useOnChangeSync = - (props.unstable_onChangeSync || props.unstable_onChangeTextSync) && - !(props.onChange || props.onChangeText); - textInput = ( { input = renderTree.root.findByType(TextInput); }); it('has expected instance functions', () => { - expect(inputRef.current.isFocused).toBeInstanceOf(Function); // Would have prevented S168585 + expect(inputRef.current.isFocused).toBeInstanceOf(Function); // Would have prevented S168585 expect(inputRef.current.clear).toBeInstanceOf(Function); expect(inputRef.current.focus).toBeInstanceOf(jest.fn().constructor); expect(inputRef.current.blur).toBeInstanceOf(jest.fn().constructor); @@ -89,7 +78,6 @@ describe('TextInput tests', () => { it('focus() should not do anything if the TextInput is not editable', () => { const textInputRef = createTextInput({editable: false}); - // currentProps is the property actually containing props at runtime textInputRef.current.currentProps = textInputRef.current.props; expect(textInputRef.current.isFocused()).toBe(false); @@ -183,7 +171,6 @@ describe('TextInput tests', () => { mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} @@ -229,7 +216,6 @@ describe('TextInput', () => { mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} @@ -275,7 +261,6 @@ describe('TextInput compat with web', () => { nativeID="id" onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} @@ -407,7 +392,6 @@ describe('TextInput compat with web', () => { mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} @@ -450,7 +434,6 @@ describe('TextInput compat with web', () => { mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} diff --git a/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap b/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap index ac93dc2e644c7c..4c9b1e93b71ad5 100644 --- a/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap +++ b/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap @@ -9,7 +9,6 @@ exports[`TextInput tests should render as expected: should deep render when mock mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} @@ -38,7 +37,6 @@ exports[`TextInput tests should render as expected: should deep render when not mostRecentEventCount={0} onBlur={[Function]} onChange={[Function]} - onChangeSync={null} onClick={[Function]} onFocus={[Function]} onResponderGrant={[Function]} diff --git a/packages/react-native/Libraries/Components/Touchable/Touchable.js b/packages/react-native/Libraries/Components/Touchable/Touchable.js index c34ca4f8b85ec6..899385a995a89d 100644 --- a/packages/react-native/Libraries/Components/Touchable/Touchable.js +++ b/packages/react-native/Libraries/Components/Touchable/Touchable.js @@ -40,8 +40,8 @@ const extractSingleTouch = (nativeEvent: { return !hasTouches && hasChangedTouches ? changedTouches[0] : hasTouches - ? touches[0] - : nativeEvent; + ? touches[0] + : nativeEvent; }; /** diff --git a/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js b/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js index e870c99355d1e0..e0c82a319f3756 100644 --- a/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js +++ b/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js @@ -144,6 +144,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { borderTopLeftRadius: true, borderTopRightRadius: true, borderTopStartRadius: true, + cursor: true, opacity: true, pointerEvents: true, diff --git a/packages/react-native/Libraries/Core/Devtools/parseErrorStack.js b/packages/react-native/Libraries/Core/Devtools/parseErrorStack.js index 9b84537c3d9863..d52ae1faffade8 100644 --- a/packages/react-native/Libraries/Core/Devtools/parseErrorStack.js +++ b/packages/react-native/Libraries/Core/Devtools/parseErrorStack.js @@ -47,11 +47,11 @@ function parseErrorStack(errorStack?: string): Array { const parsedStack = Array.isArray(errorStack) ? errorStack : global.HermesInternal - ? convertHermesStack(parseHermesStack(errorStack)) - : stacktraceParser.parse(errorStack).map((frame): StackFrame => ({ - ...frame, - column: frame.column != null ? frame.column - 1 : null, - })); + ? convertHermesStack(parseHermesStack(errorStack)) + : stacktraceParser.parse(errorStack).map((frame): StackFrame => ({ + ...frame, + column: frame.column != null ? frame.column - 1 : null, + })); return parsedStack; } diff --git a/packages/react-native/Libraries/Core/Devtools/parseHermesStack.js b/packages/react-native/Libraries/Core/Devtools/parseHermesStack.js index 1193afd88f9507..d39a69c9637ae3 100644 --- a/packages/react-native/Libraries/Core/Devtools/parseHermesStack.js +++ b/packages/react-native/Libraries/Core/Devtools/parseHermesStack.js @@ -72,6 +72,7 @@ const RE_FRAME = // Capturing groups: // 1. count of skipped frames const RE_SKIPPED = /^ {4}... skipping (\d+) frames$/; +const RE_COMPONENT_NO_STACK = /^ {4}at .*$/; function isInternalBytecodeSourceUrl(sourceUrl: string): boolean { // See https://github.com/facebook/hermes/blob/3332fa020cae0bab751f648db7c94e1d687eeec7/lib/VM/Runtime.cpp#L1100 @@ -88,25 +89,25 @@ function parseLine(line: string): ?HermesStackEntry { asFrame[2] === 'native' ? {type: 'NATIVE'} : asFrame[3] === 'address at ' - ? isInternalBytecodeSourceUrl(asFrame[4]) - ? { - type: 'INTERNAL_BYTECODE', - sourceUrl: asFrame[4], - line1Based: Number.parseInt(asFrame[5], 10), - virtualOffset0Based: Number.parseInt(asFrame[6], 10), - } + ? isInternalBytecodeSourceUrl(asFrame[4]) + ? { + type: 'INTERNAL_BYTECODE', + sourceUrl: asFrame[4], + line1Based: Number.parseInt(asFrame[5], 10), + virtualOffset0Based: Number.parseInt(asFrame[6], 10), + } + : { + type: 'BYTECODE', + sourceUrl: asFrame[4], + line1Based: Number.parseInt(asFrame[5], 10), + virtualOffset0Based: Number.parseInt(asFrame[6], 10), + } : { - type: 'BYTECODE', + type: 'SOURCE', sourceUrl: asFrame[4], line1Based: Number.parseInt(asFrame[5], 10), - virtualOffset0Based: Number.parseInt(asFrame[6], 10), - } - : { - type: 'SOURCE', - sourceUrl: asFrame[4], - line1Based: Number.parseInt(asFrame[5], 10), - column1Based: Number.parseInt(asFrame[6], 10), - }, + column1Based: Number.parseInt(asFrame[6], 10), + }, }; } const asSkipped = line.match(RE_SKIPPED); @@ -132,6 +133,11 @@ module.exports = function parseHermesStack(stack: string): HermesParsedStack { entries.push(entry); continue; } + if (RE_COMPONENT_NO_STACK.test(line)) { + // Skip component stacks without source location. + // TODO: This will not be displayed, not sure how to handle it. + continue; + } // No match - we're still in the message lastMessageLine = i; entries = []; diff --git a/packages/react-native/Libraries/Core/registerCallableModule.d.ts b/packages/react-native/Libraries/Core/registerCallableModule.d.ts new file mode 100644 index 00000000000000..05d9e92da7c717 --- /dev/null +++ b/packages/react-native/Libraries/Core/registerCallableModule.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +type Module = Object; +type RegisterCallableModule = ( + name: string, + moduleOrFactory: Module | (() => Module), +) => void; + +export const registerCallableModule: RegisterCallableModule; diff --git a/packages/react-native/Libraries/Core/setUpPerformance.js b/packages/react-native/Libraries/Core/setUpPerformance.js index a33afb30cae53d..acd41a7398c4e7 100644 --- a/packages/react-native/Libraries/Core/setUpPerformance.js +++ b/packages/react-native/Libraries/Core/setUpPerformance.js @@ -8,8 +8,8 @@ * @format */ -import NativePerformance from '../../src/private/webapis/performance/NativePerformance'; import Performance from '../../src/private/webapis/performance/Performance'; +import NativePerformance from '../../src/private/webapis/performance/specs/NativePerformance'; // In case if the native implementation of the Performance API is available, use it, // otherwise fall back to the legacy/default one, which only defines 'Performance.now()' diff --git a/packages/react-native/Libraries/Core/setUpTimers.js b/packages/react-native/Libraries/Core/setUpTimers.js index 86d73869f5ef9c..db0ac5dc1e7cf3 100644 --- a/packages/react-native/Libraries/Core/setUpTimers.js +++ b/packages/react-native/Libraries/Core/setUpTimers.js @@ -10,7 +10,9 @@ 'use strict'; -const {isNativeFunction} = require('../Utilities/FeatureDetection'); +const ReactNativeFeatureFlags = require('../../src/private/featureflags/ReactNativeFeatureFlags'); +const NativeReactNativeFeatureFlags = + require('../../src/private/featureflags/specs/NativeReactNativeFeatureFlags').default; const {polyfillGlobal} = require('../Utilities/PolyfillFunctions'); if (__DEV__) { @@ -19,14 +21,6 @@ if (__DEV__) { } } -// Currently, Hermes `Promise` is implemented via Internal Bytecode. -const hasHermesPromiseQueuedToJSVM = - global.HermesInternal?.hasPromise?.() === true && - global.HermesInternal?.useEngineQueue?.() === true; - -const hasNativePromise = isNativeFunction(Promise); -const hasPromiseQueuedToJSVM = hasNativePromise || hasHermesPromiseQueuedToJSVM; - // In bridgeless mode, timers are host functions installed from cpp. if (global.RN$Bridgeless !== true) { /** @@ -56,13 +50,33 @@ if (global.RN$Bridgeless !== true) { defineLazyTimer('cancelIdleCallback'); } -/** - * Set up immediate APIs, which is required to use the same microtask queue - * as the Promise. - */ -if (hasPromiseQueuedToJSVM) { - // When promise queues to the JSVM microtasks queue, we shim the immediate - // APIs via `queueMicrotask` to maintain the backward compatibility. +// We need to check if the native module is available before accessing the +// feature flag, because otherwise the API would throw an error in the legacy +// architecture in OSS, where the native module isn't available. +if ( + NativeReactNativeFeatureFlags != null && + ReactNativeFeatureFlags.enableMicrotasks() +) { + // This is the flag that tells React to use `queueMicrotask` to batch state + // updates, instead of using the scheduler to schedule a regular task. + // We use a global variable because we don't currently have any other + // mechanism to pass feature flags from RN to React in OSS. + global.RN$enableMicrotasksInReact = true; + + polyfillGlobal('queueMicrotask', () => { + const nativeQueueMicrotask = + require('../../src/private/webapis/microtasks/specs/NativeMicrotasks') + .default?.queueMicrotask; + if (nativeQueueMicrotask) { + return nativeQueueMicrotask; + } else { + // For backwards-compatibility + return global.HermesInternal?.enqueueJob; + } + }); + + // We shim the immediate APIs via `queueMicrotask` to maintain the backward + // compatibility. polyfillGlobal( 'setImmediate', () => require('./Timers/immediateShim').setImmediate, @@ -72,6 +86,12 @@ if (hasPromiseQueuedToJSVM) { () => require('./Timers/immediateShim').clearImmediate, ); } else { + // Polyfill it with promise (regardless it's polyfilled or native) otherwise. + polyfillGlobal( + 'queueMicrotask', + () => require('./Timers/queueMicrotask.js').default, + ); + // When promise was polyfilled hence is queued to the RN microtask queue, // we polyfill the immediate APIs as aliases to the ReactNativeMicrotask APIs. // Note that in bridgeless mode, immediate APIs are installed from cpp. @@ -86,18 +106,3 @@ if (hasPromiseQueuedToJSVM) { ); } } - -/** - * Set up the microtask queueing API, which is required to use the same - * microtask queue as the Promise. - */ -if (hasHermesPromiseQueuedToJSVM) { - // Fast path for Hermes. - polyfillGlobal('queueMicrotask', () => global.HermesInternal?.enqueueJob); -} else { - // Polyfill it with promise (regardless it's polyfilled or native) otherwise. - polyfillGlobal( - 'queueMicrotask', - () => require('./Timers/queueMicrotask.js').default, - ); -} diff --git a/packages/react-native/Libraries/Image/Image.android.js b/packages/react-native/Libraries/Image/Image.android.js index ac8660e968e63f..111abb665acd94 100644 --- a/packages/react-native/Libraries/Image/Image.android.js +++ b/packages/react-native/Libraries/Image/Image.android.js @@ -23,7 +23,9 @@ import { import {getImageSourcesFromImageProps} from './ImageSourceUtils'; import {convertObjectFitToResizeMode} from './ImageUtils'; import ImageViewNativeComponent from './ImageViewNativeComponent'; -import NativeImageLoaderAndroid from './NativeImageLoaderAndroid'; +import NativeImageLoaderAndroid, { + type ImageSize, +} from './NativeImageLoaderAndroid'; import resolveAssetSource from './resolveAssetSource'; import TextInlineImageNativeComponent from './TextInlineImageNativeComponent'; import * as React from 'react'; @@ -40,13 +42,15 @@ function generateRequestId() { */ function getSize( url: string, - success: (width: number, height: number) => void, + success?: (width: number, height: number) => void, failure?: (error: mixed) => void, -): void { - NativeImageLoaderAndroid.getSize(url) - .then(function (sizes) { - success(sizes.width, sizes.height); - }) +): void | Promise { + const promise = NativeImageLoaderAndroid.getSize(url); + if (typeof success !== 'function') { + return promise; + } + promise + .then(sizes => success(sizes.width, sizes.height)) .catch( failure || function () { @@ -64,13 +68,15 @@ function getSize( function getSizeWithHeaders( url: string, headers: {[string]: string, ...}, - success: (width: number, height: number) => void, + success?: (width: number, height: number) => void, failure?: (error: mixed) => void, -): void { - NativeImageLoaderAndroid.getSizeWithHeaders(url, headers) - .then(function (sizes) { - success(sizes.width, sizes.height); - }) +): void | Promise { + const promise = NativeImageLoaderAndroid.getSizeWithHeaders(url, headers); + if (typeof success !== 'function') { + return promise; + } + promise + .then(sizes => success(sizes.width, sizes.height)) .catch( failure || function () { @@ -171,7 +177,11 @@ let BaseImage: AbstractImageAndroid = React.forwardRef( ...restProps, style, shouldNotifyLoadEvents: !!(onLoadStart || onLoad || onLoadEnd || onError), + // Both iOS and C++ sides expect to have "source" prop, whereas on Android it's "src" + // (for historical reasons). So in the latter case we populate both "src" and "source", + // in order to have a better alignment between platforms in the future. src: sources, + source: sources, /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found * when making Flow check .android.js files. */ headers: (source?.[0]?.headers || source?.headers: ?{[string]: string}), diff --git a/packages/react-native/Libraries/Image/Image.d.ts b/packages/react-native/Libraries/Image/Image.d.ts index c9e0195ba9604c..9eeb0cbd12fc98 100644 --- a/packages/react-native/Libraries/Image/Image.d.ts +++ b/packages/react-native/Libraries/Image/Image.d.ts @@ -325,20 +325,31 @@ export interface ImageProps extends ImagePropsBase { style?: StyleProp | undefined; } +export interface ImageSize { + width: number; + height: number; +} + declare class ImageComponent extends React.Component {} declare const ImageBase: Constructor & typeof ImageComponent; export class Image extends ImageBase { + static getSize(uri: string): Promise; static getSize( uri: string, success: (width: number, height: number) => void, failure?: (error: any) => void, - ): any; + ): void; + + static getSizeWithHeaders( + uri: string, + headers: {[index: string]: string}, + ): Promise; static getSizeWithHeaders( uri: string, headers: {[index: string]: string}, success: (width: number, height: number) => void, failure?: (error: any) => void, - ): any; + ): void; static prefetch(url: string): Promise; static prefetchWithMetadata( url: string, @@ -368,16 +379,4 @@ export interface ImageBackgroundProps extends ImagePropsBase { declare class ImageBackgroundComponent extends React.Component {} declare const ImageBackgroundBase: Constructor & typeof ImageBackgroundComponent; -export class ImageBackground extends ImageBackgroundBase { - resizeMode: ImageResizeMode; - getSize( - uri: string, - success: (width: number, height: number) => void, - failure: (error: any) => void, - ): any; - prefetch(url: string): any; - abortPrefetch?(requestId: number): void; - queryCache?( - urls: string[], - ): Promise<{[url: string]: 'memory' | 'disk' | 'disk/memory'}>; -} +export class ImageBackground extends ImageBackgroundBase {} diff --git a/packages/react-native/Libraries/Image/Image.ios.js b/packages/react-native/Libraries/Image/Image.ios.js index 9ba060e16a9c6a..4b7353e2547f91 100644 --- a/packages/react-native/Libraries/Image/Image.ios.js +++ b/packages/react-native/Libraries/Image/Image.ios.js @@ -11,6 +11,7 @@ import type {ImageStyle, ImageStyleProp} from '../StyleSheet/StyleSheet'; import type {RootTag} from '../Types/RootTagTypes'; import type {AbstractImageIOS, ImageIOS} from './ImageTypes.flow'; +import type {ImageSize} from './NativeImageLoaderAndroid'; import {createRootTag} from '../ReactNative/RootTag'; import flattenStyle from '../StyleSheet/flattenStyle'; @@ -29,15 +30,22 @@ import * as React from 'react'; function getSize( uri: string, - success: (width: number, height: number) => void, + success?: (width: number, height: number) => void, failure?: (error: mixed) => void, -): void { - NativeImageLoaderIOS.getSize(uri) - .then(([width, height]) => success(width, height)) +): void | Promise { + const promise = NativeImageLoaderIOS.getSize(uri).then(([width, height]) => ({ + width, + height, + })); + if (typeof success !== 'function') { + return promise; + } + promise + .then(sizes => success(sizes.width, sizes.height)) .catch( failure || function () { - console.warn('Failed to get size for image ' + uri); + console.warn('Failed to get size for image: ' + uri); }, ); } @@ -45,13 +53,15 @@ function getSize( function getSizeWithHeaders( uri: string, headers: {[string]: string, ...}, - success: (width: number, height: number) => void, + success?: (width: number, height: number) => void, failure?: (error: mixed) => void, -): void { - NativeImageLoaderIOS.getSizeWithHeaders(uri, headers) - .then(function (sizes) { - success(sizes.width, sizes.height); - }) +): void | Promise { + const promise = NativeImageLoaderIOS.getSizeWithHeaders(uri, headers); + if (typeof success !== 'function') { + return promise; + } + promise + .then(sizes => success(sizes.width, sizes.height)) .catch( failure || function () { diff --git a/packages/react-native/Libraries/Image/ImageTypes.flow.js b/packages/react-native/Libraries/Image/ImageTypes.flow.js index 4200a776987f52..7ea0f71a5707ef 100644 --- a/packages/react-native/Libraries/Image/ImageTypes.flow.js +++ b/packages/react-native/Libraries/Image/ImageTypes.flow.js @@ -18,12 +18,17 @@ import typeof TextInlineImageNativeComponent from './TextInlineImageNativeCompon import * as React from 'react'; type ImageComponentStaticsIOS = $ReadOnly<{ - getSize: ( + getSize(uri: string): Promise<{width: number, height: number}>, + getSize( uri: string, success: (width: number, height: number) => void, failure?: (error: mixed) => void, - ) => void, + ): void, + getSizeWithHeaders( + uri: string, + headers: {[string]: string, ...}, + ): Promise<{width: number, height: number}>, getSizeWithHeaders( uri: string, headers: {[string]: string, ...}, diff --git a/packages/react-native/Libraries/Image/RCTImageLoaderLoggable.h b/packages/react-native/Libraries/Image/RCTImageLoaderLoggable.h index 08507e7f6422db..9b7da2e60a0e08 100644 --- a/packages/react-native/Libraries/Image/RCTImageLoaderLoggable.h +++ b/packages/react-native/Libraries/Image/RCTImageLoaderLoggable.h @@ -5,10 +5,12 @@ * LICENSE file in the root directory of this source tree. */ +#import + /** * The image loader (i.e. RCTImageLoader) implement this to declare whether image performance should be logged. */ -@protocol RCTImageLoaderLoggableProtocol +@protocol RCTImageLoaderLoggableProtocol /** * Image instrumentation - declares whether its caller should log images diff --git a/packages/react-native/Libraries/Image/React-RCTImage.podspec b/packages/react-native/Libraries/Image/React-RCTImage.podspec index 8fb9cca15e2aad..5aacf0d7999c32 100644 --- a/packages/react-native/Libraries/Image/React-RCTImage.podspec +++ b/packages/react-native/Libraries/Image/React-RCTImage.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] @@ -53,7 +53,7 @@ Pod::Spec.new do |s| s.dependency "React-Core/RCTImageHeaders" s.dependency "React-RCTNetwork" - add_dependency(s, "React-Codegen") + add_dependency(s, "ReactCodegen") add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") diff --git a/packages/react-native/Libraries/Image/__tests__/Image-test.js b/packages/react-native/Libraries/Image/__tests__/Image-test.js index 46124adc88ef2a..6cdedf05178f27 100644 --- a/packages/react-native/Libraries/Image/__tests__/Image-test.js +++ b/packages/react-native/Libraries/Image/__tests__/Image-test.js @@ -13,6 +13,8 @@ import type {ElementRef} from 'react'; +import NativeImageLoaderAndroid from '../NativeImageLoaderAndroid'; +import NativeImageLoaderIOS from '../NativeImageLoaderIOS'; import {act, create} from 'react-test-renderer'; const render = require('../../../jest/renderer'); @@ -291,4 +293,62 @@ describe('', () => { expect(secondInstance).toBe(null); expect(imageInstancesFromCallback.size).toBe(0); }); + + it('should resolve asset source even when Image module is mocked', async () => { + jest.mock('../Image'); + const resolvedSource = Image.resolveAssetSource({uri: 'foo-bar.jpg'}); + expect(resolvedSource).toEqual({uri: 'foo-bar.jpg'}); + }); + + it('should compute image size even when Image module is mocked', async () => { + jest.mock('../Image'); + const mockOnGetSizeSuccess = jest.fn((width, height) => undefined); + const mockSuccessCallback = (width: number, height: number) => + mockOnGetSizeSuccess(width, height); + + await Image.getSize('foo-bar.jpg', mockSuccessCallback); + await jest.runAllTicks(); + + expect(mockOnGetSizeSuccess).toHaveBeenCalledWith(320, 240); + + await Image.getSizeWithHeaders( + 'foo-bar.jpg', + {header: 'foo'}, + mockSuccessCallback, + ); + + expect(mockOnGetSizeSuccess).toHaveBeenCalledWith(333, 222); + }); + + it('should call native prefetch methods when calling JS prefetch methods', async () => { + jest.mock('../Image'); + await Image.prefetch('foo-bar.jpg'); + expect(NativeImageLoaderIOS.prefetchImage).toHaveBeenCalledWith( + 'foo-bar.jpg', + ); + expect(NativeImageLoaderAndroid.prefetchImage).toHaveBeenCalledWith( + 'foo-bar.jpg', + ); + + await Image.prefetchWithMetadata('foo-bar.jpg', 'foo-queryRootName'); + expect(NativeImageLoaderIOS.prefetchImageWithMetadata).toHaveBeenCalledWith( + 'foo-bar.jpg', + 'foo-queryRootName', + 0, + ); + expect(NativeImageLoaderAndroid.prefetchImage).toHaveBeenCalledWith( + 'foo-bar.jpg', + ); + }); + + it('should call native queryCache method when JS queryCache method is called', async () => { + jest.mock('../Image'); + await Image.queryCache(['foo-bar.jpg']); + expect(NativeImageLoaderIOS.queryCache).toHaveBeenCalledWith([ + 'foo-bar.jpg', + ]); + expect(NativeImageLoaderIOS.queryCache).toHaveBeenCalledWith([ + 'foo-bar.jpg', + ]); + }); }); diff --git a/packages/react-native/Libraries/Interaction/TouchHistoryMath.js b/packages/react-native/Libraries/Interaction/TouchHistoryMath.js index cbcbe2606de9ad..aec0d66913137b 100644 --- a/packages/react-native/Libraries/Interaction/TouchHistoryMath.js +++ b/packages/react-native/Libraries/Interaction/TouchHistoryMath.js @@ -48,10 +48,10 @@ const TouchHistoryMath = { ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis - ? oneTouchData.currentPageY - : !ofCurrent && isXAxis - ? oneTouchData.previousPageX - : oneTouchData.previousPageY; + ? oneTouchData.currentPageY + : !ofCurrent && isXAxis + ? oneTouchData.previousPageX + : oneTouchData.previousPageY; count = 1; } } else { diff --git a/packages/react-native/Libraries/IntersectionObserver/NativeIntersectionObserver.h b/packages/react-native/Libraries/IntersectionObserver/NativeIntersectionObserver.h index 1281f60db29fe1..f35ce7cd758420 100644 --- a/packages/react-native/Libraries/IntersectionObserver/NativeIntersectionObserver.h +++ b/packages/react-native/Libraries/IntersectionObserver/NativeIntersectionObserver.h @@ -56,8 +56,7 @@ struct Bridging NativeIntersectionObserverEntry> {}; class NativeIntersectionObserver - : public NativeIntersectionObserverCxxSpec, - std::enable_shared_from_this { + : public NativeIntersectionObserverCxxSpec { public: NativeIntersectionObserver(std::shared_ptr jsInvoker); diff --git a/packages/react-native/Libraries/LinkingIOS/React-RCTLinking.podspec b/packages/react-native/Libraries/LinkingIOS/React-RCTLinking.podspec index 54745755443098..eff125c9615056 100644 --- a/packages/react-native/Libraries/LinkingIOS/React-RCTLinking.podspec +++ b/packages/react-native/Libraries/LinkingIOS/React-RCTLinking.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -49,7 +49,7 @@ Pod::Spec.new do |s| s.dependency "ReactCommon/turbomodule/core", version s.dependency "React-jsi", version - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple", :additional_framework_paths => ["build/generated/ios"]) end diff --git a/packages/react-native/Libraries/Lists/FlatList.js b/packages/react-native/Libraries/Lists/FlatList.js index 3d267cb95988ed..f34fe50f8721ee 100644 --- a/packages/react-native/Libraries/Lists/FlatList.js +++ b/packages/react-native/Libraries/Lists/FlatList.js @@ -308,7 +308,6 @@ export type Props = { * Also inherits [ScrollView Props](docs/scrollview.html#props), unless it is nested in another FlatList of same orientation. */ class FlatList extends React.PureComponent, void> { - props: Props; /** * Scrolls to the end of the content. May be janky without `getItemLayout` prop. */ diff --git a/packages/react-native/Libraries/Lists/__tests__/__snapshots__/SectionList-test.js.snap b/packages/react-native/Libraries/Lists/__tests__/__snapshots__/SectionList-test.js.snap index dd3dcacc32ef8c..dcb40ffe0ae809 100644 --- a/packages/react-native/Libraries/Lists/__tests__/__snapshots__/SectionList-test.js.snap +++ b/packages/react-native/Libraries/Lists/__tests__/__snapshots__/SectionList-test.js.snap @@ -264,31 +264,27 @@ exports[`SectionList renders all the bells and whistles 1`] = ` onLayout={[Function]} style={null} > - - - - - + + + - - - - + + - - - - - + + + - - - - + + - - - - - + + + - - - - + + ({ + column: frame?.location?.column, + file: frame.fileName, + lineNumber: frame?.location?.row, + methodName: frame.content, + collapse: false, + })); +} + +function convertStackToComponentStack(stack: Stack): ComponentStack { + const componentStack = []; + for (let i = 0; i < stack.length; i++) { + const frame = stack[i]; + // NOTE: Skip stack frames missing location. + if (frame.lineNumber != null && frame.column != null) { + componentStack.push({ + fileName: frame?.file || '', + location: { + row: frame.lineNumber, + column: frame.column, + }, + content: frame.methodName, + collapse: false, + }); + } + } + return componentStack; +} + export type LogBoxLogData = $ReadOnly<{| level: LogLevel, type?: ?string, message: Message, stack: Stack, category: string, + componentStackType?: ComponentStackType, componentStack: ComponentStack, codeFrame?: ?CodeFrame, isComponentError: boolean, @@ -39,6 +73,7 @@ class LogBoxLog { type: ?string; category: Category; componentStack: ComponentStack; + componentStackType: ComponentStackType; stack: Stack; count: number; level: LogLevel; @@ -54,6 +89,19 @@ class LogBoxLog { stack: null, status: 'NONE', }; + symbolicatedComponentStack: + | $ReadOnly<{|error: null, componentStack: null, status: 'NONE'|}> + | $ReadOnly<{|error: null, componentStack: null, status: 'PENDING'|}> + | $ReadOnly<{| + error: null, + componentStack: ComponentStack, + status: 'COMPLETE', + |}> + | $ReadOnly<{|error: Error, componentStack: null, status: 'FAILED'|}> = { + error: null, + componentStack: null, + status: 'NONE', + }; constructor(data: LogBoxLogData) { this.level = data.level; @@ -62,6 +110,7 @@ class LogBoxLog { this.stack = data.stack; this.category = data.category; this.componentStack = data.componentStack; + this.componentStackType = data.componentStackType || 'legacy'; this.codeFrame = data.codeFrame; this.isComponentError = data.isComponentError; this.extraData = data.extraData; @@ -78,6 +127,15 @@ class LogBoxLog { : this.stack; } + getAvailableComponentStack(): ComponentStack { + if (this.componentStackType === 'legacy') { + return this.componentStack; + } + return this.symbolicatedComponentStack.status === 'COMPLETE' + ? this.symbolicatedComponentStack.componentStack + : this.componentStack; + } + retrySymbolicate(callback?: (status: SymbolicationStatus) => void): void { if (this.symbolicated.status !== 'COMPLETE') { LogBoxSymbolication.deleteStack(this.stack); @@ -102,6 +160,25 @@ class LogBoxLog { this.updateStatus(error, null, null, callback); }, ); + if (this.componentStack != null && this.componentStackType === 'stack') { + this.updateComponentStackStatus(null, null, null, callback); + const componentStackFrames = convertComponentStateToStack( + this.componentStack, + ); + LogBoxSymbolication.symbolicate(componentStackFrames, []).then( + data => { + this.updateComponentStackStatus( + null, + convertStackToComponentStack(data.stack), + null, + callback, + ); + }, + error => { + this.updateComponentStackStatus(error, null, null, callback); + }, + ); + } } } @@ -140,6 +217,38 @@ class LogBoxLog { callback(this.symbolicated.status); } } + + updateComponentStackStatus( + error: ?Error, + componentStack: ?ComponentStack, + codeFrame: ?CodeFrame, + callback?: (status: SymbolicationStatus) => void, + ): void { + const lastStatus = this.symbolicatedComponentStack.status; + if (error != null) { + this.symbolicatedComponentStack = { + error, + componentStack: null, + status: 'FAILED', + }; + } else if (componentStack != null) { + this.symbolicatedComponentStack = { + error: null, + componentStack, + status: 'COMPLETE', + }; + } else { + this.symbolicatedComponentStack = { + error: null, + componentStack: null, + status: 'PENDING', + }; + } + + if (callback && lastStatus !== this.symbolicatedComponentStack.status) { + callback(this.symbolicatedComponentStack.status); + } + } } export default LogBoxLog; diff --git a/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js b/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js index 42a2a9e6950daa..895ccf57ec50f4 100644 --- a/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js +++ b/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js @@ -18,6 +18,7 @@ const {parseLogBoxException, parseLogBoxLog} = require('../parseLogBoxLog'); describe('parseLogBoxLog', () => { it('parses strings', () => { expect(parseLogBoxLog(['A'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: 'A', message: { @@ -29,6 +30,7 @@ describe('parseLogBoxLog', () => { it('parses strings with arguments', () => { expect(parseLogBoxLog(['A', 'B', 'C'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: 'A B C', message: { @@ -40,6 +42,7 @@ describe('parseLogBoxLog', () => { it('parses formatted strings', () => { expect(parseLogBoxLog(['%s', 'A'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: '\ufeff%s', message: { @@ -56,6 +59,7 @@ describe('parseLogBoxLog', () => { it('parses formatted strings with insufficient arguments', () => { expect(parseLogBoxLog(['%s %s', 'A'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: '\ufeff%s %s', message: { @@ -76,6 +80,7 @@ describe('parseLogBoxLog', () => { it('parses formatted strings with excess arguments', () => { expect(parseLogBoxLog(['%s', 'A', 'B'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: '\ufeff%s B', message: { @@ -92,6 +97,7 @@ describe('parseLogBoxLog', () => { it('treats "%s" in arguments as literals', () => { expect(parseLogBoxLog(['%s', '%s', 'A'])).toEqual({ + componentStackType: 'legacy', componentStack: [], category: '\ufeff%s A', message: { @@ -114,6 +120,7 @@ describe('parseLogBoxLog', () => { '\n in MyComponent (at filename.js:1)\n in MyOtherComponent (at filename2.js:1)', ]), ).toEqual({ + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -147,6 +154,7 @@ describe('parseLogBoxLog', () => { 'Some kind of message\n in MyComponent (at filename.js:1)\n in MyOtherComponent (at filename2.js:1)', ]), ).toEqual({ + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -174,6 +182,7 @@ describe('parseLogBoxLog', () => { '\n in MyComponent (at filename.js:1)\n in MyOtherComponent (at filename2.js:1)', ]), ).toEqual({ + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -203,6 +212,7 @@ describe('parseLogBoxLog', () => { 'Some third kind of message', ]), ).toEqual({ + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -231,6 +241,7 @@ describe('parseLogBoxLog', () => { originalMessage: 'TransformError failed to transform file.', name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -245,6 +256,7 @@ describe('parseLogBoxLog', () => { substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: 'TransformError failed to transform file.', }); @@ -268,6 +280,7 @@ describe('parseLogBoxLog', () => { 200 |`, name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -291,6 +304,7 @@ describe('parseLogBoxLog', () => { substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: '/path/to/RKJSModules/Apps/CrashReact/CrashReactApp.js-199-0', }); @@ -328,6 +342,7 @@ If you are sure the module exists, try these steps: \u001b[0m \u001b[90m 15 | \u001b[39m\u001b[36mimport\u001b[39m fbRemoteAsset from \u001b[32m'fbRemoteAsset'\u001b[39m\u001b[33m;\u001b[39m\u001b[0m`, name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -359,6 +374,7 @@ If you are sure the module exists, try these steps: substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: '/path/to/file.js-1-1', }); @@ -382,6 +398,7 @@ If you are sure the module exists, try these steps: 200 |`, name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -405,6 +422,7 @@ If you are sure the module exists, try these steps: substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: '/path/to/RKJSModules/Apps/CrashReact/CrashReactApp.js-199-0', }); @@ -430,6 +448,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets 200 |`, name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -455,6 +474,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: '/path/to/RKJSModules/Apps/CrashReact/CrashReactApp.js-1-1', }); @@ -476,6 +496,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets \u001b[0m \u001b[90m 46 | \u001b[39m headline\u001b[33m=\u001b[39m\u001b[32m"CrashReact Error Boundary"\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 47 | \u001b[39m body\u001b[33m=\u001b[39m{\u001b[32m\`\${this.state.errorMessage}\`\u001b[39m}\u001b[0m\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 48 | \u001b[39m icon\u001b[33m=\u001b[39m{fbRemoteAsset(\u001b[32m'null_state_glyphs'\u001b[39m\u001b[33m,\u001b[39m {\u001b[0m\n\u001b[0m \u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 49 | \u001b[39m name\u001b[33m:\u001b[39m \u001b[32m'codexxx'\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 50 | \u001b[39m size\u001b[33m:\u001b[39m \u001b[32m'112'\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 51 | \u001b[39m })}\u001b[0m`, name: '', isComponentError: false, + componentStackType: 'legacy', componentStack: '', stack: ([]: Array), id: 0, @@ -498,6 +519,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, substitutions: [], }, stack: [], + componentStackType: 'legacy', componentStack: [], category: '/path/to/RKJSModules/Apps/CrashReact/CrashReactApp.js-1-1', }); @@ -511,6 +533,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, message: '### Error', originalMessage: '### Error', name: '', + componentStackType: 'legacy', componentStack: '\n in MyComponent (at filename.js:1)\n in MyOtherComponent (at filename2.js:1)', stack: [ @@ -532,6 +555,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, content: '### Error', substitutions: [], }, + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -566,6 +590,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, originalMessage: 'Some kind of message\n in MyComponent (at filename.js:1)\n in MyOtherComponent (at filename2.js:1)', name: '', + componentStackType: 'legacy', componentStack: null, stack: [ { @@ -589,6 +614,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, methodName: 'bar', }, ], + componentStackType: 'legacy', componentStack: [ { content: 'MyComponent', @@ -616,6 +642,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, isComponentError: false, message: '### Fatal', originalMessage: '### Fatal', + componentStackType: 'legacy', componentStack: null, name: '', stack: [ @@ -637,6 +664,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, content: '### Fatal', substitutions: [], }, + componentStackType: 'legacy', componentStack: [], stack: [ { @@ -678,6 +706,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, content: '### Fatal', substitutions: [], }, + componentStackType: 'legacy', componentStack: [], stack: [ { @@ -724,6 +753,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, substitutions: [], }, isComponentError: false, + componentStackType: 'legacy', componentStack: [], stack: [ { @@ -737,16 +767,291 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); }); - describe('Handles component stack frames formatted as call stacks', () => { + describe('Handles component stack frames without debug source', () => { + it('detects a component stack in an interpolated warning', () => { + expect( + parseLogBoxLog([ + 'Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s%s', + '\n\nCheck the render method of `MyComponent`.', + '\n in MyComponent (created by MyOtherComponent)\n in MyOtherComponent (created by MyComponent)\n in MyAppComponent (created by MyOtherComponent)', + ]), + ).toEqual({ + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + { + content: 'MyOtherComponent', + fileName: '', + location: null, + }, + { + content: 'MyAppComponent', + fileName: '', + location: null, + }, + ], + category: + 'Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s', + message: { + content: + 'Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?\n\nCheck the render method of `MyComponent`.', + substitutions: [ + { + length: 43, + offset: 129, + }, + ], + }, + }); + }); + + it('detects a component stack in the first argument', () => { + expect( + parseLogBoxLog([ + 'Some kind of message\n in MyComponent (created by MyOtherComponent)\n in MyOtherComponent (created by MyComponent)\n in MyAppComponent (created by MyOtherComponent)', + ]), + ).toEqual({ + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + { + content: 'MyOtherComponent', + fileName: '', + location: null, + }, + { + content: 'MyAppComponent', + fileName: '', + location: null, + }, + ], + category: 'Some kind of message', + message: { + content: 'Some kind of message', + substitutions: [], + }, + }); + }); + + it('detects a component stack in the second argument', () => { + expect( + parseLogBoxLog([ + 'Some kind of message', + '\n in MyComponent (created by MyOtherComponent)\n in MyOtherComponent (created by MyComponent)\n in MyAppComponent (created by MyOtherComponent)', + ]), + ).toEqual({ + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + { + content: 'MyOtherComponent', + fileName: '', + location: null, + }, + { + content: 'MyAppComponent', + fileName: '', + location: null, + }, + ], + category: 'Some kind of message', + message: { + content: 'Some kind of message', + substitutions: [], + }, + }); + }); + + it('detects a component stack in the nth argument', () => { + expect( + parseLogBoxLog([ + 'Warning: Each child in a list should have a unique "key" prop.%s%s See https://fb.me/react-warning-keys for more information.%s', + '\n\nCheck the render method of `MyOtherComponent`.', + '', + '\n in MyComponent (created by MyOtherComponent)\n in MyOtherComponent (created by MyComponent)\n in MyAppComponent (created by MyOtherComponent)', + ]), + ).toEqual({ + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + { + content: 'MyOtherComponent', + fileName: '', + location: null, + }, + { + content: 'MyAppComponent', + fileName: '', + location: null, + }, + ], + category: + 'Warning: Each child in a list should have a unique "key" prop.%s%s See https://fb.me/react-warning-keys for more information.', + message: { + content: + 'Warning: Each child in a list should have a unique "key" prop.\n\nCheck the render method of `MyOtherComponent`. See https://fb.me/react-warning-keys for more information.', + substitutions: [ + { + length: 48, + offset: 62, + }, + { + length: 0, + offset: 110, + }, + ], + }, + }); + }); + + it('detects a single component in a component stack', () => { + const error = { + id: 0, + isFatal: true, + isComponentError: true, + message: + 'Error: Some kind of message\n\nThis error is located at:\n in MyComponent (created by MyOtherComponent)\n', + originalMessage: 'Some kind of message', + name: '', + componentStackType: 'legacy', + componentStack: '\n in MyComponent (created by MyOtherComponent)\n', + stack: [ + { + column: 1, + file: 'foo.js', + lineNumber: 1, + methodName: 'bar', + collapse: false, + }, + ], + }; + + expect(parseLogBoxException(error)).toEqual({ + level: 'fatal', + isComponentError: true, + stack: [ + { + collapse: false, + column: 1, + file: 'foo.js', + lineNumber: 1, + methodName: 'bar', + }, + ], + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + ], + category: 'Some kind of message', + message: { + content: 'Some kind of message', + substitutions: [], + }, + }); + }); + + it('parses an error log with `error.componentStack`', () => { + const error = { + id: 0, + isFatal: false, + isComponentError: false, + message: '### Error', + originalMessage: '### Error', + name: '', + componentStack: + '\n in MyComponent (created by MyOtherComponent)\n in MyOtherComponent (created by MyComponent)\n in MyAppComponent (created by MyOtherComponent)', + stack: [ + { + column: 1, + file: 'foo.js', + lineNumber: 1, + methodName: 'bar', + collapse: false, + }, + ], + }; + + expect(parseLogBoxException(error)).toEqual({ + level: 'error', + category: '### Error', + isComponentError: false, + message: { + content: '### Error', + substitutions: [], + }, + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyComponent', + fileName: '', + location: null, + }, + { + content: 'MyOtherComponent', + fileName: '', + location: null, + }, + { + content: 'MyAppComponent', + fileName: '', + location: null, + }, + ], + stack: [ + { + column: 1, + file: 'foo.js', + lineNumber: 1, + methodName: 'bar', + collapse: false, + }, + ], + }); + }); + }); + + describe('Handles component stack frames formatted as call stacks in Hermes', () => { + let originalHermesInternal; + beforeEach(() => { + originalHermesInternal = global.HermesInternal; + // $FlowFixMe[cannot-write] - Jest + global.HermesInternal = true; + }); + afterEach(() => { + // $FlowFixMe[cannot-write] - Jest + global.HermesInternal = originalHermesInternal; + }); + // In new versions of React, the component stack frame format changed to match call stacks. it('detects a component stack in an interpolated warning', () => { expect( parseLogBoxLog([ 'Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s%s', '\n\nCheck the render method of `MyComponent`.', - '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', + '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -781,9 +1086,10 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, it('detects a component stack in the first argument', () => { expect( parseLogBoxLog([ - 'Some kind of message\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', + 'Some kind of message\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -812,9 +1118,10 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, expect( parseLogBoxLog([ 'Some kind of message', - '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', + '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -845,9 +1152,10 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, 'Warning: Each child in a list should have a unique "key" prop.%s%s See https://fb.me/react-warning-keys for more information.%s', '\n\nCheck the render method of `MyOtherComponent`.', '', - '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', + '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -892,7 +1200,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, originalMessage: '### Error', name: '', componentStack: - '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', + '\n at MyComponent (/path/to/filename.js:1:2)\n at MyOtherComponent\n at MyAppComponent (/path/to/app.js:100:20)', stack: [ { column: 1, @@ -912,6 +1220,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, content: '### Error', substitutions: [], }, + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -951,6 +1260,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, '\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -992,6 +1302,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, 'Some kind of message\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -1020,12 +1331,62 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); }); + it('detects a component stack for ts, tsx, jsx, and js files', () => { + expect( + parseLogBoxLog([ + 'Some kind of message\n in MyTSComponent (at MyTSXComponent.ts:1)\n in MyTSXComponent (at MyTSCComponent.tsx:1)\n in MyJSXComponent (at MyJSXComponent.jsx:1)\n in MyJSComponent (at MyJSComponent.js:1)', + ]), + ).toEqual({ + componentStackType: 'legacy', + componentStack: [ + { + content: 'MyTSComponent', + fileName: 'MyTSXComponent.ts', + location: { + column: -1, + row: 1, + }, + }, + { + content: 'MyTSXComponent', + fileName: 'MyTSCComponent.tsx', + location: { + column: -1, + row: 1, + }, + }, + { + content: 'MyJSXComponent', + fileName: 'MyJSXComponent.jsx', + location: { + column: -1, + row: 1, + }, + }, + { + content: 'MyJSComponent', + fileName: 'MyJSComponent.js', + location: { + column: -1, + row: 1, + }, + }, + ], + category: 'Some kind of message', + message: { + content: 'Some kind of message', + substitutions: [], + }, + }); + }); + it('detects a component stack in the first argument (JSC)', () => { expect( parseLogBoxLog([ 'Some kind of message\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -1061,6 +1422,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, '\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -1098,6 +1460,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, '\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', ]), ).toEqual({ + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -1166,6 +1529,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, content: '### Error', substitutions: [], }, + componentStackType: 'stack', componentStack: [ { collapse: false, @@ -1208,6 +1572,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, originalMessage: 'Some kind of message\nMyComponent@/path/to/filename.js:1:2\nforEach@[native code]\nMyAppComponent@/path/to/app.js:100:20', name: '', + componentStackType: 'stack', componentStack: null, stack: [ { @@ -1231,6 +1596,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, methodName: 'bar', }, ], + componentStackType: 'stack', componentStack: [ { collapse: false, diff --git a/packages/react-native/Libraries/LogBox/Data/parseLogBoxLog.js b/packages/react-native/Libraries/LogBox/Data/parseLogBoxLog.js index 744fa5e4e367ef..f4519b3eb574ea 100644 --- a/packages/react-native/Libraries/LogBox/Data/parseLogBoxLog.js +++ b/packages/react-native/Libraries/LogBox/Data/parseLogBoxLog.js @@ -18,11 +18,62 @@ import ansiRegex from 'ansi-regex'; const ANSI_REGEX = ansiRegex().source; -const BABEL_TRANSFORM_ERROR_FORMAT = +const RE_TRANSFORM_ERROR = /^TransformError /; +const RE_COMPONENT_STACK_LINE = /\n {4}(in|at) /; +const RE_COMPONENT_STACK_LINE_GLOBAL = /\n {4}(in|at) /g; +const RE_COMPONENT_STACK_LINE_OLD = / {4}in/; +const RE_COMPONENT_STACK_LINE_NEW = / {4}at/; +const RE_COMPONENT_STACK_LINE_STACK_FRAME = /@.*\n/; + +// "TransformError " (Optional) and either "SyntaxError: " or "ReferenceError: " +// Capturing groups: +// 1: error message +// 2: file path +// 3: line number +// 4: column number +// \n\n +// 5: code frame +const RE_BABEL_TRANSFORM_ERROR_FORMAT = /^(?:TransformError )?(?:SyntaxError: |ReferenceError: )(.*): (.*) \((\d+):(\d+)\)\n\n([\s\S]+)/; +// Capturing groups: +// 1: component name +// "at" +// 2: file path including extension +// 3: line number +const RE_COMPONENT_STACK_WITH_SOURCE = + /(.*) \(at (.*\.(?:js|jsx|ts|tsx)):([\d]+)\)/; + +// Capturing groups: +// 1: component name +// "at" +// 2: parent component name +const RE_COMPONENT_STACK_NO_SOURCE = /(.*) \(created by .*\)/; + +// Capturing groups: +// - non-capturing "TransformError " (optional) +// - non-capturing Error message +// 1: file path +// 2: file name +// 3: error message +// 4: code frame, which includes code snippet indicators or terminal escape sequences for formatting. +const RE_BABEL_CODE_FRAME_ERROR_FORMAT = + // eslint-disable-next-line no-control-regex + /^(?:TransformError )?(?:.*):? (?:.*?)(\/.*): ([\s\S]+?)\n([ >]{2}[\d\s]+ \|[\s\S]+|\u{001b}[\s\S]+)/u; + +// Capturing groups: +// - non-capturing "InternalError Metro has encountered an error:" +// 1: error title +// 2: error message +// 3: file path +// 4: line number +// 5: column number +// 6: code frame, which includes code snippet indicators or terminal escape sequences for formatting. +const RE_METRO_ERROR_FORMAT = + /^(?:InternalError Metro has encountered an error:) (.*): (.*) \((\d+):(\d+)\)\n\n([\s\S]+)/u; + // https://github.com/babel/babel/blob/33dbb85e9e9fe36915273080ecc42aee62ed0ade/packages/babel-code-frame/src/index.ts#L183-L184 -const BABEL_CODE_FRAME_MARKER_PATTERN = new RegExp( +const RE_BABEL_CODE_FRAME_MARKER_PATTERN = new RegExp( [ // Beginning of a line (per 'm' flag) '^', @@ -42,13 +93,6 @@ const BABEL_CODE_FRAME_MARKER_PATTERN = new RegExp( 'm', ); -const BABEL_CODE_FRAME_ERROR_FORMAT = - // eslint-disable-next-line no-control-regex - /^(?:TransformError )?(?:.*):? (?:.*?)(\/.*): ([\s\S]+?)\n([ >]{2}[\d\s]+ \|[\s\S]+|\u{001b}[\s\S]+)/u; - -const METRO_ERROR_FORMAT = - /^(?:InternalError Metro has encountered an error:) (.*): (.*) \((\d+):(\d+)\)\n\n([\s\S]+)/u; - export type ExtendedExceptionData = ExceptionData & { isComponentError: boolean, ... @@ -79,6 +123,7 @@ export type Message = $ReadOnly<{| |}>; export type ComponentStack = $ReadOnlyArray; +export type ComponentStackType = 'legacy' | 'stack'; const SUBSTITUTION = UTFSequence.BOM + '%s'; @@ -158,9 +203,12 @@ export function parseInterpolation(args: $ReadOnlyArray): $ReadOnly<{| } function isComponentStack(consoleArgument: string) { - const isOldComponentStackFormat = / {4}in/.test(consoleArgument); - const isNewComponentStackFormat = / {4}at/.test(consoleArgument); - const isNewJSCComponentStackFormat = /@.*\n/.test(consoleArgument); + const isOldComponentStackFormat = + RE_COMPONENT_STACK_LINE_OLD.test(consoleArgument); + const isNewComponentStackFormat = + RE_COMPONENT_STACK_LINE_NEW.test(consoleArgument); + const isNewJSCComponentStackFormat = + RE_COMPONENT_STACK_LINE_STACK_FRAME.test(consoleArgument); return ( isOldComponentStackFormat || @@ -169,42 +217,62 @@ function isComponentStack(consoleArgument: string) { ); } -export function parseComponentStack(message: string): ComponentStack { +export function parseComponentStack(message: string): { + type: ComponentStackType, + stack: ComponentStack, +} { // In newer versions of React, the component stack is formatted as a call stack frame. // First try to parse the component stack as a call stack frame, and if that doesn't // work then we'll fallback to the old custom component stack format parsing. const stack = parseErrorStack(message); if (stack && stack.length > 0) { - return stack.map(frame => ({ - content: frame.methodName, - collapse: frame.collapse || false, - fileName: frame.file == null ? 'unknown' : frame.file, - location: { - column: frame.column == null ? -1 : frame.column, - row: frame.lineNumber == null ? -1 : frame.lineNumber, - }, - })); + return { + type: 'stack', + stack: stack.map(frame => ({ + content: frame.methodName, + collapse: frame.collapse || false, + fileName: frame.file == null ? 'unknown' : frame.file, + location: { + column: frame.column == null ? -1 : frame.column, + row: frame.lineNumber == null ? -1 : frame.lineNumber, + }, + })), + }; } - - return message - .split(/\n {4}in /g) + const legacyStack = message + .split(RE_COMPONENT_STACK_LINE_GLOBAL) .map(s => { if (!s) { return null; } - const match = s.match(/(.*) \(at (.*\.js):([\d]+)\)/); - if (!match) { - return null; + const match = s.match(RE_COMPONENT_STACK_WITH_SOURCE); + if (match) { + let [content, fileName, row] = match.slice(1); + return { + content, + fileName, + location: {column: -1, row: parseInt(row, 10)}, + }; } - let [content, fileName, row] = match.slice(1); - return { - content, - fileName, - location: {column: -1, row: parseInt(row, 10)}, - }; + // In some cases, the component stack doesn't have a source. + const matchWithoutSource = s.match(RE_COMPONENT_STACK_NO_SOURCE); + if (matchWithoutSource) { + return { + content: matchWithoutSource[1], + fileName: '', + location: null, + }; + } + + return null; }) .filter(Boolean); + + return { + type: 'legacy', + stack: legacyStack, + }; } export function parseLogBoxException( @@ -213,7 +281,7 @@ export function parseLogBoxException( const message = error.originalMessage != null ? error.originalMessage : 'Unknown'; - const metroInternalError = message.match(METRO_ERROR_FORMAT); + const metroInternalError = message.match(RE_METRO_ERROR_FORMAT); if (metroInternalError) { const [content, fileName, row, column, codeFrame] = metroInternalError.slice(1); @@ -223,6 +291,7 @@ export function parseLogBoxException( type: 'Metro Error', stack: [], isComponentError: false, + componentStackType: 'legacy', componentStack: [], codeFrame: { fileName, @@ -241,7 +310,7 @@ export function parseLogBoxException( }; } - const babelTransformError = message.match(BABEL_TRANSFORM_ERROR_FORMAT); + const babelTransformError = message.match(RE_BABEL_TRANSFORM_ERROR_FORMAT); if (babelTransformError) { // Transform errors are thrown from inside the Babel transformer. const [fileName, content, row, column, codeFrame] = @@ -251,6 +320,7 @@ export function parseLogBoxException( level: 'syntax', stack: [], isComponentError: false, + componentStackType: 'legacy', componentStack: [], codeFrame: { fileName, @@ -271,8 +341,8 @@ export function parseLogBoxException( // Perform a cheap match first before trying to parse the full message, which // can get expensive for arbitrary input. - if (BABEL_CODE_FRAME_MARKER_PATTERN.test(message)) { - const babelCodeFrameError = message.match(BABEL_CODE_FRAME_ERROR_FORMAT); + if (RE_BABEL_CODE_FRAME_MARKER_PATTERN.test(message)) { + const babelCodeFrameError = message.match(RE_BABEL_CODE_FRAME_ERROR_FORMAT); if (babelCodeFrameError) { // Codeframe errors are thrown from any use of buildCodeFrameError. @@ -281,6 +351,7 @@ export function parseLogBoxException( level: 'syntax', stack: [], isComponentError: false, + componentStackType: 'legacy', componentStack: [], codeFrame: { fileName, @@ -297,11 +368,12 @@ export function parseLogBoxException( } } - if (message.match(/^TransformError /)) { + if (message.match(RE_TRANSFORM_ERROR)) { return { level: 'syntax', stack: error.stack, isComponentError: error.isComponentError, + componentStackType: 'legacy', componentStack: [], message: { content: message, @@ -314,24 +386,39 @@ export function parseLogBoxException( const componentStack = error.componentStack; if (error.isFatal || error.isComponentError) { - return { - level: 'fatal', - stack: error.stack, - isComponentError: error.isComponentError, - componentStack: - componentStack != null ? parseComponentStack(componentStack) : [], - extraData: error.extraData, - ...parseInterpolation([message]), - }; + if (componentStack != null) { + const {type, stack} = parseComponentStack(componentStack); + return { + level: 'fatal', + stack: error.stack, + isComponentError: error.isComponentError, + componentStackType: type, + componentStack: stack, + extraData: error.extraData, + ...parseInterpolation([message]), + }; + } else { + return { + level: 'fatal', + stack: error.stack, + isComponentError: error.isComponentError, + componentStackType: 'legacy', + componentStack: [], + extraData: error.extraData, + ...parseInterpolation([message]), + }; + } } if (componentStack != null) { // It is possible that console errors have a componentStack. + const {type, stack} = parseComponentStack(componentStack); return { level: 'error', stack: error.stack, isComponentError: error.isComponentError, - componentStack: parseComponentStack(componentStack), + componentStackType: type, + componentStack: stack, extraData: error.extraData, ...parseInterpolation([message]), }; @@ -350,12 +437,14 @@ export function parseLogBoxException( export function parseLogBoxLog(args: $ReadOnlyArray): {| componentStack: ComponentStack, + componentStackType: ComponentStackType, category: Category, message: Message, |} { const message = args[0]; let argsWithoutComponentStack: Array = []; let componentStack: ComponentStack = []; + let componentStackType = 'legacy'; // Extract component stack from warnings like "Some warning%s". if ( @@ -367,7 +456,9 @@ export function parseLogBoxLog(args: $ReadOnlyArray): {| if (typeof lastArg === 'string' && isComponentStack(lastArg)) { argsWithoutComponentStack = args.slice(0, -1); argsWithoutComponentStack[0] = message.slice(0, -2); - componentStack = parseComponentStack(lastArg); + const {type, stack} = parseComponentStack(lastArg); + componentStack = stack; + componentStackType = type; } } @@ -376,7 +467,7 @@ export function parseLogBoxLog(args: $ReadOnlyArray): {| for (const arg of args) { if (typeof arg === 'string' && isComponentStack(arg)) { // Strip out any messages before the component stack. - let messageEndIndex = arg.search(/\n {4}(in|at) /); + let messageEndIndex = arg.search(RE_COMPONENT_STACK_LINE); if (messageEndIndex < 0) { // Handle JSC component stacks. messageEndIndex = arg.search(/\n/); @@ -385,7 +476,9 @@ export function parseLogBoxLog(args: $ReadOnlyArray): {| argsWithoutComponentStack.push(arg.slice(0, messageEndIndex)); } - componentStack = parseComponentStack(arg); + const {type, stack} = parseComponentStack(arg); + componentStack = stack; + componentStackType = type; } else { argsWithoutComponentStack.push(arg); } @@ -395,5 +488,6 @@ export function parseLogBoxLog(args: $ReadOnlyArray): {| return { ...parseInterpolation(argsWithoutComponentStack), componentStack, + componentStackType, }; } diff --git a/packages/react-native/Libraries/LogBox/UI/LogBoxInspectorReactFrames.js b/packages/react-native/Libraries/LogBox/UI/LogBoxInspectorReactFrames.js index 4c1cf9b3c1c482..428dc83a5ce85e 100644 --- a/packages/react-native/Libraries/LogBox/UI/LogBoxInspectorReactFrames.js +++ b/packages/react-native/Libraries/LogBox/UI/LogBoxInspectorReactFrames.js @@ -50,24 +50,27 @@ function getPrettyFileName(path: string) { } function LogBoxInspectorReactFrames(props: Props): React.Node { const [collapsed, setCollapsed] = React.useState(true); - if (props.log.componentStack == null || props.log.componentStack.length < 1) { + if ( + props.log.getAvailableComponentStack() == null || + props.log.getAvailableComponentStack().length < 1 + ) { return null; } function getStackList() { if (collapsed) { - return props.log.componentStack.slice(0, 3); + return props.log.getAvailableComponentStack().slice(0, 3); } else { - return props.log.componentStack; + return props.log.getAvailableComponentStack(); } } function getCollapseMessage() { - if (props.log.componentStack.length <= 3) { + if (props.log.getAvailableComponentStack().length <= 3) { return; } - const count = props.log.componentStack.length - 3; + const count = props.log.getAvailableComponentStack().length - 3; if (collapsed) { return `See ${count} more components`; } else { diff --git a/packages/react-native/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspector-test.js.snap b/packages/react-native/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspector-test.js.snap index 0574a088ddf244..307cc240878b4b 100644 --- a/packages/react-native/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspector-test.js.snap +++ b/packages/react-native/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspector-test.js.snap @@ -21,6 +21,7 @@ exports[`LogBoxContainer should render fatal with selectedIndex 2 1`] = ` "category": "Some kind of message (third)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -35,6 +36,11 @@ exports[`LogBoxContainer should render fatal with selectedIndex 2 1`] = ` "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } @@ -71,6 +77,7 @@ exports[`LogBoxContainer should render warning with selectedIndex 0 1`] = ` "category": "Some kind of message (first)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -85,6 +92,11 @@ exports[`LogBoxContainer should render warning with selectedIndex 0 1`] = ` "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } diff --git a/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxInspectorContainer-test.js.snap b/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxInspectorContainer-test.js.snap index 591971a62af560..445cfb2365bb2d 100644 --- a/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxInspectorContainer-test.js.snap +++ b/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxInspectorContainer-test.js.snap @@ -27,6 +27,7 @@ exports[`LogBoxNotificationContainer should render both an error and warning not "category": "Some kind of message", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -41,6 +42,11 @@ exports[`LogBoxNotificationContainer should render both an error and warning not "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } @@ -65,6 +71,7 @@ exports[`LogBoxNotificationContainer should render both an error and warning not "category": "Some kind of message (latest)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -79,6 +86,11 @@ exports[`LogBoxNotificationContainer should render both an error and warning not "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } @@ -125,6 +137,7 @@ exports[`LogBoxNotificationContainer should render the latest error notification "category": "Some kind of message (latest)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -139,6 +152,11 @@ exports[`LogBoxNotificationContainer should render the latest error notification "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } @@ -177,6 +195,7 @@ exports[`LogBoxNotificationContainer should render the latest warning notificati "category": "Some kind of message (latest)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -191,6 +210,11 @@ exports[`LogBoxNotificationContainer should render the latest warning notificati "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, } } diff --git a/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxNotificationContainer-test.js.snap b/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxNotificationContainer-test.js.snap index 5402cb1504e05e..05c2778c4f6b91 100644 --- a/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxNotificationContainer-test.js.snap +++ b/packages/react-native/Libraries/LogBox/__tests__/__snapshots__/LogBoxNotificationContainer-test.js.snap @@ -19,6 +19,7 @@ exports[`LogBoxNotificationContainer should render inspector with logs, even whe "category": "Some kind of message", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -33,12 +34,18 @@ exports[`LogBoxNotificationContainer should render inspector with logs, even whe "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, }, LogBoxLog { "category": "Some kind of message (latest)", "codeFrame": undefined, "componentStack": Array [], + "componentStackType": "legacy", "count": 1, "extraData": undefined, "isComponentError": false, @@ -53,6 +60,11 @@ exports[`LogBoxNotificationContainer should render inspector with logs, even whe "stack": null, "status": "NONE", }, + "symbolicatedComponentStack": Object { + "componentStack": null, + "error": null, + "status": "NONE", + }, "type": undefined, }, ] diff --git a/packages/react-native/Libraries/MutationObserver/NativeMutationObserver.h b/packages/react-native/Libraries/MutationObserver/NativeMutationObserver.h index b7c2eab986d930..9d01507b4103fd 100644 --- a/packages/react-native/Libraries/MutationObserver/NativeMutationObserver.h +++ b/packages/react-native/Libraries/MutationObserver/NativeMutationObserver.h @@ -46,8 +46,7 @@ struct Bridging NativeMutationRecord> {}; class NativeMutationObserver - : public NativeMutationObserverCxxSpec, - std::enable_shared_from_this { + : public NativeMutationObserverCxxSpec { public: NativeMutationObserver(std::shared_ptr jsInvoker); diff --git a/packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.h b/packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.h index 77152f4a5773de..562913126e9442 100644 --- a/packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.h +++ b/packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.h @@ -7,6 +7,7 @@ #import #import +#import #import diff --git a/packages/react-native/Libraries/NativeAnimation/React-RCTAnimation.podspec b/packages/react-native/Libraries/NativeAnimation/React-RCTAnimation.podspec index fe5a5786da607a..c9f32c9eea7e36 100644 --- a/packages/react-native/Libraries/NativeAnimation/React-RCTAnimation.podspec +++ b/packages/react-native/Libraries/NativeAnimation/React-RCTAnimation.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -49,7 +49,7 @@ Pod::Spec.new do |s| s.dependency "React-jsi" s.dependency "React-Core/RCTAnimationHeaders" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") end diff --git a/packages/react-native/Libraries/Network/React-RCTNetwork.podspec b/packages/react-native/Libraries/Network/React-RCTNetwork.podspec index 179f0da985a1f1..d88cbe7574aaa9 100644 --- a/packages/react-native/Libraries/Network/React-RCTNetwork.podspec +++ b/packages/react-native/Libraries/Network/React-RCTNetwork.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -50,7 +50,7 @@ Pod::Spec.new do |s| s.dependency "React-jsi" s.dependency "React-Core/RCTNetworkHeaders" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple", :additional_framework_paths => ["build/generated/ios"]) end diff --git a/packages/react-native/Libraries/Network/XMLHttpRequest.js b/packages/react-native/Libraries/Network/XMLHttpRequest.js index e6191b10f7b560..6445ae25f0bc1e 100644 --- a/packages/react-native/Libraries/Network/XMLHttpRequest.js +++ b/packages/react-native/Libraries/Network/XMLHttpRequest.js @@ -248,7 +248,10 @@ class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) { } else if (this._response === '') { this._cachedResponse = BlobManager.createFromParts([]); } else { - throw new Error(`Invalid response for blob: ${this._response}`); + throw new Error( + 'Invalid response for blob - expecting object, was ' + + `${typeof this._response}: ${this._response.trim()}`, + ); } break; diff --git a/packages/react-native/Libraries/NewAppScreen/components/LearnMoreLinks.js b/packages/react-native/Libraries/NewAppScreen/components/LearnMoreLinks.js index cff854bcca7949..27195e3c4a2007 100644 --- a/packages/react-native/Libraries/NewAppScreen/components/LearnMoreLinks.js +++ b/packages/react-native/Libraries/NewAppScreen/components/LearnMoreLinks.js @@ -74,10 +74,10 @@ const links = [ }, { id: 9, - title: 'Follow us on Twitter', - link: 'https://twitter.com/reactnative', + title: 'Follow us', + link: 'https://x.com/reactnative', description: - 'Stay in touch with the community, join in on Q&As and more by following React Native on Twitter.', + 'Stay in touch with the community, join in on Q&As and more by following React Native on X.', }, ]; diff --git a/packages/react-native/Libraries/Pressability/Pressability.js b/packages/react-native/Libraries/Pressability/Pressability.js index 940249af9a8df4..1bd6853b4202e4 100644 --- a/packages/react-native/Libraries/Pressability/Pressability.js +++ b/packages/react-native/Libraries/Pressability/Pressability.js @@ -136,33 +136,6 @@ export type PressabilityConfig = $ReadOnly<{| * while this pressable is responder. */ blockNativeResponder?: ?boolean, - - /** - * Returns whether a long press gesture should cancel the press gesture. - * Defaults to true. - * - * @deprecated - */ - onLongPressShouldCancelPress_DEPRECATED?: ?() => boolean, - - /** - * If `cancelable` is set, this will be ignored. - * - * Returns whether to yield to a lock termination request (e.g. if a native - * scroll gesture attempts to steal the responder lock). - * - * @deprecated - */ - onResponderTerminationRequest_DEPRECATED?: ?() => boolean, - - /** - * If `disabled` is set, this will be ignored. - * - * Returns whether to start a press gesture. - * - * @deprecated - */ - onStartShouldSetResponder_DEPRECATED?: ?() => boolean, |}>; export type EventHandlers = $ReadOnly<{| @@ -475,13 +448,7 @@ export default class Pressability { const responderEventHandlers = { onStartShouldSetResponder: (): boolean => { const {disabled} = this._config; - if (disabled == null) { - const {onStartShouldSetResponder_DEPRECATED} = this._config; - return onStartShouldSetResponder_DEPRECATED == null - ? true - : onStartShouldSetResponder_DEPRECATED(); - } - return !disabled; + return !disabled ?? true; }, onResponderGrant: (event: PressEvent): void | boolean => { @@ -559,13 +526,7 @@ export default class Pressability { onResponderTerminationRequest: (): boolean => { const {cancelable} = this._config; - if (cancelable == null) { - const {onResponderTerminationRequest_DEPRECATED} = this._config; - return onResponderTerminationRequest_DEPRECATED == null - ? true - : onResponderTerminationRequest_DEPRECATED(); - } - return cancelable; + return cancelable ?? true; }, onClick: (event: PressEvent): void => { @@ -789,9 +750,7 @@ export default class Pressability { const {onLongPress, onPress, android_disableSound} = this._config; if (onPress != null) { const isPressCanceledByLongPress = - onLongPress != null && - prevState === 'RESPONDER_ACTIVE_LONG_PRESS_IN' && - this._shouldLongPressCancelPress(); + onLongPress != null && prevState === 'RESPONDER_ACTIVE_LONG_PRESS_IN'; if (!isPressCanceledByLongPress) { if (Platform.OS === 'android' && android_disableSound !== true) { SoundManager.playTouchSound(); @@ -925,13 +884,6 @@ export default class Pressability { } } - _shouldLongPressCancelPress(): boolean { - return ( - this._config.onLongPressShouldCancelPress_DEPRECATED == null || - this._config.onLongPressShouldCancelPress_DEPRECATED() - ); - } - _cancelHoverInDelayTimeout(): void { if (this._hoverInDelayTimeout != null) { clearTimeout(this._hoverInDelayTimeout); diff --git a/packages/react-native/Libraries/Pressability/__tests__/Pressability-test.js b/packages/react-native/Libraries/Pressability/__tests__/Pressability-test.js index 5581db9787fa5c..08d770d0f70f4d 100644 --- a/packages/react-native/Libraries/Pressability/__tests__/Pressability-test.js +++ b/packages/react-native/Libraries/Pressability/__tests__/Pressability-test.js @@ -13,13 +13,13 @@ jest.useFakeTimers({legacyFakeTimers: true}); import type {PressEvent} from '../../Types/CoreEventTypes'; +import type {PressabilityConfig} from '../Pressability'; const UIManager = require('../../ReactNative/UIManager'); const Platform = require('../../Utilities/Platform'); const HoverState = require('../HoverState'); const Pressability = require('../Pressability').default; const invariant = require('invariant'); -const nullthrows = require('nullthrows'); const isWindows = process.platform === 'win32'; const itif = (condition: boolean) => { @@ -36,9 +36,7 @@ function getMock, TReturn>( return (fn: $FlowFixMe); } -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -const createMockPressability = overrides => { +const createMockPressability = (overrides: ?Partial) => { const config = { cancelable: null, disabled: null, @@ -57,9 +55,6 @@ const createMockPressability = overrides => { onPress: jest.fn(), onPressIn: jest.fn(), onPressOut: jest.fn(), - onLongPressShouldCancelPress_DEPRECATED: jest.fn(), - onResponderTerminationRequest_DEPRECATED: jest.fn(() => true), - onStartShouldSetResponder_DEPRECATED: jest.fn(() => true), ...overrides, }; const touchable = new Pressability(config); @@ -514,7 +509,11 @@ describe('Pressability', () => { describe('onPress', () => { it('is called even when `measure` does not finish', () => { - const {config, handlers} = createMockPressability(); + // Disable onLongPress. Since we run all timers, we otherwise end up + // interpreting these events as a long press. + const {config, handlers} = createMockPressability({ + onLongPress: undefined, + }); handlers.onStartShouldSetResponder(); handlers.onResponderGrant(createMockPressEvent('onResponderGrant')); @@ -877,29 +876,4 @@ describe('Pressability', () => { }); }); }); - - describe('onStartShouldSetResponder', () => { - it('if omitted the responder is set by default', () => { - const {handlers} = createMockPressability({ - onStartShouldSetResponder_DEPRECATED: null, - }); - - expect(handlers.onStartShouldSetResponder()).toBe(true); - }); - - it('if supplied it is called', () => { - const {config, handlers} = createMockPressability(); - const onStartShouldSetResponder_DEPRECATED = nullthrows( - config.onStartShouldSetResponder_DEPRECATED, - ); - - // $FlowFixMe[prop-missing] - onStartShouldSetResponder_DEPRECATED.mockReturnValue(false); - expect(handlers.onStartShouldSetResponder()).toBe(false); - - // $FlowFixMe[prop-missing] - onStartShouldSetResponder_DEPRECATED.mockReturnValue(true); - expect(handlers.onStartShouldSetResponder()).toBe(true); - }); - }); }); diff --git a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.h b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.h index 214e0c81fc678c..3f72180dfa7880 100644 --- a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.h +++ b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.h @@ -45,9 +45,4 @@ typedef void (^RCTRemoteNotificationCallback)(UIBackgroundFetchResult result); */ + (void)setInitialNotification:(UNNotification *)notification; -/** DEPRECATED. Use didReceiveNotification instead. */ -+ (void)didReceiveLocalNotification:(UILocalNotification *)notification RCT_DEPRECATED; -/** DEPRECATED. Use didReceiveNotification instead. */ -+ (void)didReceiveRemoteNotification:(NSDictionary *)notification RCT_DEPRECATED; - @end diff --git a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm index 31b7dcb7a89296..86f11c42f60cc4 100644 --- a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm +++ b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm @@ -97,26 +97,6 @@ @implementation RCTConvert (UIBackgroundFetchResult) @implementation RCTPushNotificationManager -/** DEPRECATED. UILocalNotification was deprecated in iOS 10. Please don't add new callsites. */ -static NSDictionary *RCTFormatLocalNotification(UILocalNotification *notification) -{ - NSMutableDictionary *formattedLocalNotification = [NSMutableDictionary dictionary]; - if (notification.fireDate) { - NSDateFormatter *formatter = [NSDateFormatter new]; - [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"]; - NSString *fireDateString = [formatter stringFromDate:notification.fireDate]; - formattedLocalNotification[@"fireDate"] = fireDateString; - } - formattedLocalNotification[@"alertAction"] = RCTNullIfNil(notification.alertAction); - formattedLocalNotification[@"alertBody"] = RCTNullIfNil(notification.alertBody); - formattedLocalNotification[@"applicationIconBadgeNumber"] = @(notification.applicationIconBadgeNumber); - formattedLocalNotification[@"category"] = RCTNullIfNil(notification.category); - formattedLocalNotification[@"soundName"] = RCTNullIfNil(notification.soundName); - formattedLocalNotification[@"userInfo"] = RCTNullIfNil(RCTJSONClean(notification.userInfo)); - formattedLocalNotification[@"remote"] = @NO; - return formattedLocalNotification; -} - /** For delivered notifications */ static NSDictionary *RCTFormatUNNotification(UNNotification *notification) { @@ -267,23 +247,6 @@ + (void)setInitialNotification:(UNNotification *)notification kInitialNotification = notification; } -// Deprecated -+ (void)didReceiveLocalNotification:(UILocalNotification *)notification -{ - [[NSNotificationCenter defaultCenter] postNotificationName:kLocalNotificationReceived - object:self - userInfo:RCTFormatLocalNotification(notification)]; -} - -// Deprecated -+ (void)didReceiveRemoteNotification:(NSDictionary *)notification -{ - NSDictionary *userInfo = @{@"notification" : notification}; - [[NSNotificationCenter defaultCenter] postNotificationName:RCTRemoteNotificationReceived - object:self - userInfo:userInfo]; -} - - (void)invalidate { [super invalidate]; @@ -565,27 +528,6 @@ - (void)handleRemoteNotificationRegistrationError:(NSNotification *)notification return; } - NSMutableDictionary *initialRemoteNotification = - [self.bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] mutableCopy]; - - // The user actioned a remote notification to launch the app. This is a fallback that is deprecated - // in the new architecture. - if (initialRemoteNotification) { - initialRemoteNotification[@"remote"] = @YES; - resolve(initialRemoteNotification); - return; - } - - UILocalNotification *initialLocalNotification = - self.bridge.launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]; - - // The user actioned a local notification to launch the app. Notification is represented by UILocalNotification. This - // is deprecated. - if (initialLocalNotification) { - resolve(RCTFormatLocalNotification(initialLocalNotification)); - return; - } - resolve((id)kCFNull); } diff --git a/packages/react-native/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec b/packages/react-native/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec index 14002a521e975f..7a82e20d911a68 100644 --- a/packages/react-native/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec +++ b/packages/react-native/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -50,7 +50,7 @@ Pod::Spec.new do |s| s.dependency "React-Core/RCTPushNotificationHeaders" s.dependency "React-jsi" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") end diff --git a/packages/react-native/Libraries/ReactNative/getNativeComponentAttributes.js b/packages/react-native/Libraries/ReactNative/getNativeComponentAttributes.js index 318a2d18a4e18e..d768a6487187f9 100644 --- a/packages/react-native/Libraries/ReactNative/getNativeComponentAttributes.js +++ b/packages/react-native/Libraries/ReactNative/getNativeComponentAttributes.js @@ -77,8 +77,8 @@ function getNativeComponentAttributes(uiViewClassName: string): any { ? true : {process} : process == null - ? {diff} - : {diff, process}; + ? {diff} + : {diff, process}; } // Unfortunately, the current setup declares style properties as top-level diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js index 2d08a1c3820f19..4d49bcd510e76a 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js @@ -8,7 +8,7 @@ * @nolint * @providesModule ReactFabric-dev * @preventMunge - * @generated SignedSource<> + * @generated SignedSource<> */ "use strict"; @@ -98,292 +98,14 @@ if (__DEV__) { } } - var fakeNode = null; - - { - if ( - typeof window !== "undefined" && - typeof window.dispatchEvent === "function" && - typeof document !== "undefined" && // $FlowFixMe[method-unbinding] - typeof document.createEvent === "function" - ) { - fakeNode = document.createElement("react"); - } - } - - function invokeGuardedCallbackImpl(name, func, context) { - { - // In DEV mode, we use a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // unintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - // fakeNode signifies we are in an environment with a document and window object - if (fakeNode) { - var evt = document.createEvent("Event"); - var didCall = false; // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - - var didError = true; // Keeps track of the value of window.event so that we can reset it - // during the callback to let user code access window.event in the - // browsers that support it. - - var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event - // dispatching: https://github.com/facebook/react/issues/13688 - - var windowEventDescriptor = Object.getOwnPropertyDescriptor( - window, - "event" - ); - - var restoreAfterDispatch = function () { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the - // window.event assignment in both IE <= 10 as they throw an error - // "Member not found" in strict mode, and in Firefox which does not - // support window.event. - - if ( - typeof window.event !== "undefined" && - window.hasOwnProperty("event") - ) { - window.event = windowEvent; - } - }; // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - // $FlowFixMe[method-unbinding] - - var _funcArgs = Array.prototype.slice.call(arguments, 3); - - var callCallback = function () { - didCall = true; - restoreAfterDispatch(); // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. - - func.apply(context, _funcArgs); - didError = false; - }; // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - - var error; // Use this to track whether the error event is ever called. - - var didSetError = false; - var isCrossOriginError = false; - - var handleWindowError = function (event) { - error = event.error; - didSetError = true; - - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - - if (event.defaultPrevented) { - // Some other error handler has prevented default. - // Browsers silence the error report if this happens. - // We'll remember this to later decide whether to log it or not. - if (error != null && typeof error === "object") { - try { - error._suppressLogging = true; - } catch (inner) { - // Ignore. - } - } - } - }; // Create a fake event type. - - var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - - window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (windowEventDescriptor) { - Object.defineProperty(window, "event", windowEventDescriptor); - } - - if (didCall && didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error( - "An error was thrown inside one of your components, but React " + - "doesn't know what it was. This is likely due to browser " + - 'flakiness. React does its best to preserve the "Pause on ' + - 'exceptions" behavior of the DevTools, which requires some ' + - "DEV-mode only tricks. It's possible that these don't work in " + - "your browser. Try triggering the error in production mode, " + - "or switching to a modern browser. If you suspect that this is " + - "actually an issue with React, please file an issue." - ); - } else if (isCrossOriginError) { - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error( - "A cross-origin error was thrown. React doesn't have access to " + - "the actual error object in development. " + - "See https://reactjs.org/link/crossorigin-error for more information." - ); - } - - this.onError(error); - } // Remove our event listeners - - window.removeEventListener("error", handleWindowError); - - if (didCall) { - return; - } else { - // Something went really wrong, and our event was not dispatched. - // https://github.com/facebook/react/issues/16734 - // https://github.com/facebook/react/issues/16585 - // Fall back to the production implementation. - restoreAfterDispatch(); // we fall through and call the prod version instead - } - } // We only get here if we are in an environment that either does not support the browser - // variant or we had trouble getting the browser to emit the error. - // $FlowFixMe[method-unbinding] - - var funcArgs = Array.prototype.slice.call(arguments, 3); - - try { - // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } - } - } - - var hasError = false; - var caughtError = null; // Used by event system to capture/rethrow the first error. - - var hasRethrowError = false; - var rethrowError = null; - var reporter = { - onError: function (error) { - hasError = true; - caughtError = error; - } - }; - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); - } - /** - * Same as invokeGuardedCallback, but instead of returning an error, it stores - * it in a global so it can be rethrown by `rethrowCaughtError` later. - * TODO: See if caughtError and rethrowError can be unified. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f - ) { - invokeGuardedCallback.apply(this, arguments); - - if (hasError) { - var error = clearCaughtError(); - - if (!hasRethrowError) { - hasRethrowError = true; - rethrowError = error; - } - } - } - /** - * During execution of guarded functions we will capture the first error which - * we will rethrow to be handled by the top level error handler. - */ - - function rethrowCaughtError() { - if (hasRethrowError) { - var error = rethrowError; - hasRethrowError = false; - rethrowError = null; - throw error; - } - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error = caughtError; - hasError = false; - caughtError = null; - return error; - } else { - throw new Error( - "clearCaughtError was called but no error was captured. This error " + - "is likely caused by a bug in React. Please file an issue." - ); - } - } - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } + var hasError = false; + var caughtError = null; var getFiberCurrentPropsFromNode$1 = null; var getInstanceFromNode$1 = null; var getNodeFromInstance$1 = null; @@ -399,7 +121,7 @@ if (__DEV__) { { if (!getNodeFromInstance$1 || !getInstanceFromNode$1) { error( - "EventPluginUtils.setComponentTree(...): Injected " + + "Injected " + "module is missing getNodeFromInstance or getInstanceFromNode." ); } @@ -439,9 +161,17 @@ if (__DEV__) { */ function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance$1(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); + + try { + listener(event); + } catch (error) { + if (!hasError) { + hasError = true; + caughtError = error; + } + } + event.currentTarget = null; } /** @@ -534,7 +264,7 @@ if (__DEV__) { var dispatchInstance = event._dispatchInstances; if (isArray(dispatchListener)) { - throw new Error("executeDirectDispatch(...): Invalid `event`."); + throw new Error("Invalid `event`."); } event.currentTarget = dispatchListener @@ -554,6 +284,14 @@ if (__DEV__) { function hasDispatches(event) { return !!event._dispatchListeners; } + function rethrowCaughtError() { + if (hasError) { + var error = caughtError; + hasError = false; + caughtError = null; + throw error; + } + } var assign = Object.assign; @@ -840,7 +578,7 @@ if (__DEV__) { "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + "If you must keep the original synthetic event around, use event.persist(). " + - "See https://reactjs.org/link/event-pooling for more information.", + "See https://react.dev/link/event-pooling for more information.", action, propName, result @@ -1160,9 +898,7 @@ if (__DEV__) { function accumulate(current, next) { if (next == null) { - throw new Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw new Error("Accumulated items must not be null or undefined."); } if (current == null) { @@ -1200,9 +936,7 @@ if (__DEV__) { function accumulateInto(current, next) { if (next == null) { - throw new Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw new Error("Accumulated items must not be null or undefined."); } if (current == null) { @@ -3229,6 +2963,7 @@ to return true:wantsResponderID| | // where it would do it. } + // ----------------------------------------------------------------------------- var enableSchedulingProfiler = false; var enableProfilerTimer = true; var enableProfilerCommitHooks = true; @@ -3239,6 +2974,7 @@ to return true:wantsResponderID| | var enableLegacyHidden = false; var enableAsyncActions = false; var passChildrenWhenCloningPersistedNodes = false; + var enableBigIntSupport = false; var NoFlags$1 = /* */ @@ -3499,7 +3235,7 @@ to return true:wantsResponderID| | error( "The installed version of React DevTools is too old and will not work " + "with the current version of React. Please update React DevTools. " + - "https://reactjs.org/link/react-devtools" + "https://react.dev/link/react-devtools" ); } // DevTools exists, even though it doesn't support Fiber. @@ -4246,7 +3982,7 @@ to return true:wantsResponderID| | return laneMap; } - function markRootUpdated(root, updateLane) { + function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update // could unblock them. Clear the suspended lanes so that we can try rendering // them again. @@ -4283,7 +4019,7 @@ to return true:wantsResponderID| | markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); } } - function markRootPinged(root, pingedLanes) { + function markRootPinged$1(root, pingedLanes) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } function markRootFinished(root, remainingLanes, spawnedLane) { @@ -4895,6 +4631,14 @@ to return true:wantsResponderID| | function waitForCommitToBeReady() { return null; } + // Microtasks + // ------------------- + + var supportsMicrotasks = + typeof RN$enableMicrotasksInReact !== "undefined" && + !!RN$enableMicrotasksInReact; + var scheduleMicrotask = + typeof queueMicrotask === "function" ? queueMicrotask : scheduleTimeout; // This is ok in DOM because they types are interchangeable, but in React Native // they aren't. @@ -4982,7 +4726,9 @@ to return true:wantsResponderID| | var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); // TODO: Delete with enableRenderableContext + + var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); @@ -5082,13 +4828,21 @@ to return true:wantsResponderID| | } switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: { + var provider = type; + return getContextName$1(provider._context) + ".Provider"; + } + case REACT_CONTEXT_TYPE: var context = type; - return getContextName$1(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName$1(provider._context) + ".Provider"; + { + return getContextName$1(context) + ".Consumer"; + } + + case REACT_CONSUMER_TYPE: { + return null; + } case REACT_FORWARD_REF_TYPE: return getWrappedName$1(type, type.render, "ForwardRef"); @@ -5141,13 +4895,15 @@ to return true:wantsResponderID| | case CacheComponent: return "Cache"; - case ContextConsumer: + case ContextConsumer: { var context = type; return getContextName(context) + ".Consumer"; + } - case ContextProvider: + case ContextProvider: { var provider = type; return getContextName(provider._context) + ".Provider"; + } case DehydratedFragment: return "DehydratedFragment"; @@ -5261,9 +5017,6 @@ to return true:wantsResponderID| | return null; } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } function isMounted(component) { { var owner = ReactCurrentOwner$3.current; @@ -5509,214 +5262,6 @@ to return true:wantsResponderID| | return false; } - function describeBuiltInComponentFrame(name, ownerFn) { - { - var ownerName = null; - - if (ownerFn) { - ownerName = ownerFn.displayName || ownerFn.name || null; - } - - return describeComponentFrame(name, ownerName); - } - } - - { - var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; - new PossiblyWeakMap$1(); - } - - function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - - if (ownerName) { - sourceInfo = " (created by " + ownerName + ")"; - } - - return "\n in " + (name || "Unknown") + sourceInfo; - } - - function describeClassComponentFrame(ctor, ownerFn) { - { - return describeFunctionComponentFrame(ctor, ownerFn); - } - } - function describeFunctionComponentFrame(fn, ownerFn) { - { - if (!fn) { - return ""; - } - - var name = fn.displayName || fn.name || null; - var ownerName = null; - - if (ownerFn) { - ownerName = ownerFn.displayName || ownerFn.name || null; - } - - return describeComponentFrame(name, ownerName); - } - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeFunctionComponentFrame(type, ownerFn); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type, ownerFn); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense", ownerFn); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList", ownerFn); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render, ownerFn); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - var valueStack = []; var fiberStack; @@ -5768,280 +5313,33 @@ to return true:wantsResponderID| | cursor.current = value; } - var warnedAboutMissingGetChildContext; - - { - warnedAboutMissingGetChildContext = {}; - } - - var emptyContextObject = {}; + var emptyContextObject = {}; { Object.freeze(emptyContextObject); } // A cursor to the current merged context object on the stack. - var contextStackCursor$1 = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - - var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. - // We use this to get access to the parent context after we have already - // pushed the next context provider, and now need to merge their contexts. - - var previousContext = emptyContextObject; - - function getUnmaskedContext( - workInProgress, - Component, - didPushOwnContextIfProvider - ) { - { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - // If the fiber is a context provider itself, when we read its context - // we may have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - - return contextStackCursor$1.current; - } - } - - function cacheContext(workInProgress, unmaskedContext, maskedContext) { - { - var instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - } - - function getMaskedContext(workInProgress, unmaskedContext) { - { - var type = workInProgress.type; - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - - var instance = workInProgress.stateNode; - - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === - unmaskedContext - ) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - var context = {}; - - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentNameFromFiber(workInProgress) || "Unknown"; - checkPropTypes(contextTypes, context, "context", name); - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } - } - function hasContextChanged() { { - return didPerformWorkStackCursor.current; + return false; } } function isContextProvider(type) { { - var childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== undefined; - } - } - - function popContext(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor$1, fiber); - } - } - - function popTopLevelContextObject(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor$1, fiber); - } - } - - function pushTopLevelContextObject(fiber, context, didChange) { - { - if (contextStackCursor$1.current !== emptyContextObject) { - throw new Error( - "Unexpected context found on stack. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - push(contextStackCursor$1, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); + return false; } } function processChildContext(fiber, type, parentContext) { { - var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - - if (typeof instance.getChildContext !== "function") { - { - var componentName = getComponentNameFromFiber(fiber) || "Unknown"; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - - error( - "%s.childContextTypes is specified but there is no getChildContext() method " + - "on the instance. You can either define getChildContext() on %s or remove " + - "childContextTypes from it.", - componentName, - componentName - ); - } - } - - return parentContext; - } - - var childContext = instance.getChildContext(); - - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - } - } - - { - var name = getComponentNameFromFiber(fiber) || "Unknown"; - checkPropTypes( - childContextTypes, - childContext, - "child context", - name - ); - } - - return assign({}, parentContext, childContext); - } - } - - function pushContextProvider(workInProgress) { - { - var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - - var memoizedMergedChildContext = - (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, memoizedMergedChildContext, workInProgress); - push( - didPerformWorkStackCursor, - didPerformWorkStackCursor.current, - workInProgress - ); - return true; - } - } - - function invalidateContextProvider(workInProgress, type, didChange) { - { - var instance = workInProgress.stateNode; - - if (!instance) { - throw new Error( - "Expected to have an instance by this point. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - var mergedContext = processChildContext( - workInProgress, - type, - previousContext - ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor$1, workInProgress); // Now push the new context and mark that it has changed. - - push(contextStackCursor$1, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } + return parentContext; } } function findCurrentUnmaskedContext(fiber) { { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error( - "Expected subtree parent to be a mounted class component. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - var node = fiber; - - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - - case ClassComponent: { - var Component = node.type; - - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - - break; - } - } // $FlowFixMe[incompatible-type] we bail out when we get a null - - node = node.return; - } while (node !== null); - - throw new Error( - "Found unexpected detached subtree parent. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + return emptyContextObject; } } @@ -6160,16 +5458,8 @@ to return true:wantsResponderID| | } var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches - // due to earlier mismatches or a suspended fiber. - - var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary var hydrationErrors = null; - function didSuspendOrErrorWhileHydratingDEV() { - { - return didSuspendOrErrorDEV; - } - } function prepareToHydrateHostInstance(fiber, hostContext) { { @@ -6829,7 +6119,31 @@ to return true:wantsResponderID| | } // TODO: Can we land supportsMicrotasks? Which environments don't support it? // Alternatively, can we move this check to the host config? - { + if (supportsMicrotasks) { + scheduleMicrotask(function () { + // In Safari, appending an iframe forces microtasks to run. + // https://github.com/facebook/react/issues/22459 + // We don't support running callbacks in the middle of render + // or commit so we need to check against that. + var executionContext = getExecutionContext(); + + if ( + (executionContext & (RenderContext | CommitContext)) !== + NoContext + ) { + // Note that this would still prematurely flush the callbacks + // if this happens outside render or commit phase (e.g. in an event). + // Intentionally using a macrotask instead of a microtask here. This is + // wrong semantically but it prevents an infinite loop. The bug is + // Safari's, not ours, so we just do our best to not crash even though + // the behavior isn't completely correct. + scheduleCallback$2(ImmediatePriority, cb); + return; + } + + cb(); + }); + } else { // If microtasks are not supported, use Scheduler. scheduleCallback$2(ImmediatePriority, cb); } @@ -7511,6 +6825,9 @@ to return true:wantsResponderID| | } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -7552,6 +6869,61 @@ to return true:wantsResponderID| | return true; } + function describeBuiltInComponentFrame(name, ownerFn) { + { + var ownerName = null; + + if (ownerFn) { + ownerName = ownerFn.displayName || ownerFn.name || null; + } + + return describeComponentFrame(name, ownerName); + } + } + function describeDebugInfoFrame(name, env) { + return describeBuiltInComponentFrame( + name + (env ? " (" + env + ")" : ""), + null + ); + } + + { + var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; + new PossiblyWeakMap$1(); + } + + function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + + if (ownerName) { + sourceInfo = " (created by " + ownerName + ")"; + } + + return "\n in " + (name || "Unknown") + sourceInfo; + } + + function describeClassComponentFrame(ctor, ownerFn) { + { + return describeFunctionComponentFrame(ctor, ownerFn); + } + } + function describeFunctionComponentFrame(fn, ownerFn) { + { + if (!fn) { + return ""; + } + + var name = fn.displayName || fn.name || null; + var ownerName = null; + + if (ownerFn) { + ownerName = ownerFn.displayName || ownerFn.name || null; + } + + return describeComponentFrame(name, ownerName); + } + } + function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null; @@ -7592,7 +6964,22 @@ to return true:wantsResponderID| | var node = workInProgress; do { - info += describeFiber(node); // $FlowFixMe[incompatible-type] we bail out when we get a null + info += describeFiber(node); + + if (true) { + // Add any Server Component stack frames in reverse order. + var debugInfo = node._debugInfo; + + if (debugInfo) { + for (var i = debugInfo.length - 1; i >= 0; i--) { + var entry = debugInfo[i]; + + if (typeof entry.name === "string") { + info += describeDebugInfoFrame(entry.name, entry.env); + } + } + } + } // $FlowFixMe[incompatible-type] we bail out when we get a null node = node.return; } while (node); @@ -7838,7 +7225,7 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move code with side effects to componentDidMount, and set initial state in the constructor.\n" + "\nPlease update the following components: %s", sortedNames @@ -7853,11 +7240,11 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* If you're updating state whenever props change, " + "refactor your code to use memoization techniques or move it to " + - "static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n" + + "static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n" + "\nPlease update the following components: %s", _sortedNames ); @@ -7871,7 +7258,7 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "\nPlease update the following components: %s", _sortedNames2 @@ -7885,7 +7272,7 @@ to return true:wantsResponderID| | warn( "componentWillMount has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move code with side effects to componentDidMount, and set initial state in the constructor.\n" + "* Rename componentWillMount to UNSAFE_componentWillMount to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + @@ -7903,11 +7290,11 @@ to return true:wantsResponderID| | warn( "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* If you're updating state whenever props change, refactor your " + "code to use memoization techniques or move it to " + - "static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n" + + "static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n" + "* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + "To rename all deprecated lifecycles to their new names, you can run " + @@ -7924,7 +7311,7 @@ to return true:wantsResponderID| | warn( "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + @@ -7997,7 +7384,7 @@ to return true:wantsResponderID| | "\n\nThe old API will be supported in all 16.x releases, but applications " + "using it should migrate to the new version." + "\n\nPlease update the following components: %s" + - "\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", + "\n\nLearn more about this warning here: https://react.dev/link/legacy-context", sortedNames ); } finally { @@ -8277,20 +7664,20 @@ to return true:wantsResponderID| | rejectedThenable.reason = error; } } - ); // Check one more time in case the thenable resolved synchronously. + ); + } // Check one more time in case the thenable resolved synchronously. - switch (thenable.status) { - case "fulfilled": { - var fulfilledThenable = thenable; - return fulfilledThenable.value; - } + switch (thenable.status) { + case "fulfilled": { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } - case "rejected": { - var rejectedThenable = thenable; - var _rejectedError = rejectedThenable.reason; - checkIfUseWrappedInAsyncCatch(_rejectedError); - throw _rejectedError; - } + case "rejected": { + var rejectedThenable = thenable; + var _rejectedError = rejectedThenable.reason; + checkIfUseWrappedInAsyncCatch(_rejectedError); + throw _rejectedError; } } // Suspend. // @@ -8368,11 +7755,26 @@ to return true:wantsResponderID| | var thenableState$1 = null; var thenableIndexCounter$1 = 0; + + function mergeDebugInfo(outer, inner) { + if (inner == null) { + return outer; + } else if (outer === null) { + return inner; + } else { + // If we have two debugInfo, we need to create a new one. This makes the array no longer + // live so we'll miss any future updates if we received more so ideally we should always + // do this after both have fully resolved/unsuspended. + return outer.concat(inner); + } + } + var didWarnAboutMaps; var didWarnAboutGenerators; var didWarnAboutStringRefs; var ownerHasKeyUseWarning; var ownerHasFunctionTypeWarning; + var ownerHasSymbolTypeWarning; var warnForMissingKey = function (child, returnFiber) {}; @@ -8388,6 +7790,7 @@ to return true:wantsResponderID| | ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; + ownerHasSymbolTypeWarning = {}; warnForMissingKey = function (child, returnFiber) { if (child === null || typeof child !== "object") { @@ -8417,7 +7820,7 @@ to return true:wantsResponderID| | error( "Each child in a list should have a unique " + - '"key" prop. See https://reactjs.org/link/warning-keys for ' + + '"key" prop. See https://react.dev/link/warning-keys for ' + "more information." ); }; @@ -8438,122 +7841,128 @@ to return true:wantsResponderID| | return trackUsedThenable(thenableState$1, thenable, index); } - function coerceRef(returnFiber, current, element) { - var mixedRef = element.ref; - - if ( - mixedRef !== null && - typeof mixedRef !== "function" && - typeof mixedRef !== "object" - ) { - { - if ( - // Will already throw with "Function components cannot have string refs" - !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs" - !( - typeof element.type === "function" && !isReactClass(element.type) - ) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" - element._owner - ) { - var componentName = - getComponentNameFromFiber(returnFiber) || "Component"; - - if (!didWarnAboutStringRefs[componentName]) { - error( - 'Component "%s" contains the string ref "%s". Support for string refs ' + - "will be removed in a future major release. We recommend using " + - "useRef() or createRef() instead. " + - "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-string-ref", - componentName, - mixedRef - ); - - didWarnAboutStringRefs[componentName] = true; - } - } - } + function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef + ) { + { + checkPropStringCoercion(mixedRef, "ref"); + } - if (element._owner) { - var owner = element._owner; - var inst; + var stringRef = "" + mixedRef; + var owner = element._owner; - if (owner) { - var ownerFiber = owner; + if (!owner) { + throw new Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of" + + " the following reasons:\n" + + "1. You may be adding a ref to a function component\n" + + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + + "3. You have multiple copies of React loaded\n" + + "See https://react.dev/link/refs-must-have-owner for more information." + ); + } - if (ownerFiber.tag !== ClassComponent) { - throw new Error( - "Function components cannot have string refs. " + - "We recommend using useRef() instead. " + - "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-string-ref" - ); - } + if (owner.tag !== ClassComponent) { + throw new Error( + "Function components cannot have string refs. " + + "We recommend using useRef() instead. " + + "Learn more about using refs safely here: " + + "https://react.dev/link/strict-mode-string-ref" + ); + } - inst = ownerFiber.stateNode; - } + { + if ( + // Will already warn with "Function components cannot be given refs" + !(typeof element.type === "function" && !isReactClass(element.type)) + ) { + var componentName = + getComponentNameFromFiber(returnFiber) || "Component"; - if (!inst) { - throw new Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a " + - "bug in React. Please file an issue." + if (!didWarnAboutStringRefs[componentName]) { + error( + 'Component "%s" contains the string ref "%s". Support for string refs ' + + "will be removed in a future major release. We recommend using " + + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://react.dev/link/strict-mode-string-ref", + componentName, + stringRef ); - } // Assigning this to a const so Flow knows it won't change in the closure - - var resolvedInst = inst; - { - checkPropStringCoercion(mixedRef, "ref"); + didWarnAboutStringRefs[componentName] = true; } + } + } - var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + var inst = owner.stateNode; - if ( - current !== null && - current.ref !== null && - typeof current.ref === "function" && - current.ref._stringRef === stringRef - ) { - return current.ref; - } + if (!inst) { + throw new Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a " + + "bug in React. Please file an issue." + ); + } // Check if previous string ref matches new string ref - var ref = function (value) { - var refs = resolvedInst.refs; + if ( + current !== null && + current.ref !== null && + typeof current.ref === "function" && + current.ref._stringRef === stringRef + ) { + // Reuse the existing string ref + var currentRef = current.ref; + return currentRef; + } // Create a new string ref - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; + var ref = function (value) { + var refs = inst.refs; - ref._stringRef = stringRef; - return ref; + if (value === null) { + delete refs[stringRef]; } else { - if (typeof mixedRef !== "string") { - throw new Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - } - - if (!element._owner) { - throw new Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of" + - " the following reasons:\n" + - "1. You may be adding a ref to a function component\n" + - "2. You may be adding a ref to a component that was not created inside a component's render method\n" + - "3. You have multiple copies of React loaded\n" + - "See https://reactjs.org/link/refs-must-have-owner for more information." - ); - } + refs[stringRef] = value; } + }; + + ref._stringRef = stringRef; + return ref; + } + + function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef; + + { + // Old behavior. + mixedRef = element.ref; } - return mixedRef; + var coercedRef; + + if ( + typeof mixedRef === "string" || + typeof mixedRef === "number" || + typeof mixedRef === "boolean" + ) { + coercedRef = convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef + ); + } else { + coercedRef = mixedRef; + } // TODO: If enableRefAsProp is on, we shouldn't use the `ref` field. We + // should always read the ref from the prop. + + workInProgress.ref = coercedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { @@ -8570,22 +7979,68 @@ to return true:wantsResponderID| | ); } - function warnOnFunctionType(returnFiber) { + function warnOnFunctionType(returnFiber, invalidChild) { { - var componentName = - getComponentNameFromFiber(returnFiber) || "Component"; + var parentName = getComponentNameFromFiber(returnFiber) || "Component"; - if (ownerHasFunctionTypeWarning[componentName]) { + if (ownerHasFunctionTypeWarning[parentName]) { return; } - ownerHasFunctionTypeWarning[componentName] = true; + ownerHasFunctionTypeWarning[parentName] = true; + var name = invalidChild.displayName || invalidChild.name || "Component"; - error( - "Functions are not valid as a React child. This may happen if " + - "you return a Component instead of from render. " + - "Or maybe you meant to call this function rather than return it." - ); + if (returnFiber.tag === HostRoot) { + error( + "Functions are not valid as a React child. This may happen if " + + "you return %s instead of <%s /> from render. " + + "Or maybe you meant to call this function rather than return it.\n" + + " root.render(%s)", + name, + name, + name + ); + } else { + error( + "Functions are not valid as a React child. This may happen if " + + "you return %s instead of <%s /> from render. " + + "Or maybe you meant to call this function rather than return it.\n" + + " <%s>{%s}", + name, + name, + parentName, + name, + parentName + ); + } + } + } + + function warnOnSymbolType(returnFiber, invalidChild) { + { + var parentName = getComponentNameFromFiber(returnFiber) || "Component"; + + if (ownerHasSymbolTypeWarning[parentName]) { + return; + } + + ownerHasSymbolTypeWarning[parentName] = true; // eslint-disable-next-line react-internal/safe-string-coercion + + var name = String(invalidChild); + + if (returnFiber.tag === HostRoot) { + error( + "Symbols are not valid as a React child.\n" + " root.render(%s)", + name + ); + } else { + error( + "Symbols are not valid as a React child.\n" + " <%s>%s", + parentName, + name, + parentName + ); + } } } @@ -8632,7 +8087,7 @@ to return true:wantsResponderID| | return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { + function mapRemainingChildren(currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index // instead. @@ -8701,7 +8156,13 @@ to return true:wantsResponderID| | return newFiber; } - function updateTextNode(returnFiber, current, textContent, lanes) { + function updateTextNode( + returnFiber, + current, + textContent, + lanes, + debugInfo + ) { if (current === null || current.tag !== HostText) { // Insert var created = createFiberFromText( @@ -8710,16 +8171,26 @@ to return true:wantsResponderID| | lanes ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, textContent); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function updateElement(returnFiber, current, element, lanes) { + function updateElement(returnFiber, current, element, lanes, debugInfo) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { @@ -8728,7 +8199,8 @@ to return true:wantsResponderID| | current, element.props.children, lanes, - element.key + element.key, + debugInfo ); } @@ -8746,11 +8218,12 @@ to return true:wantsResponderID| | ) { // Move based on index var existing = useFiber(current, element.props); - existing.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, existing, element); existing.return = returnFiber; { existing._debugOwner = element._owner; + existing._debugInfo = debugInfo; } return existing; @@ -8758,12 +8231,17 @@ to return true:wantsResponderID| | } // Insert var created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, created, element); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } - function updatePortal(returnFiber, current, portal, lanes) { + function updatePortal(returnFiber, current, portal, lanes, debugInfo) { if ( current === null || current.tag !== HostPortal || @@ -8773,16 +8251,33 @@ to return true:wantsResponderID| | // Insert var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, portal.children || []); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function updateFragment(returnFiber, current, fragment, lanes, key) { + function updateFragment( + returnFiber, + current, + fragment, + lanes, + key, + debugInfo + ) { if (current === null || current.tag !== Fragment) { // Insert var created = createFiberFromFragment( @@ -8792,29 +8287,46 @@ to return true:wantsResponderID| | key ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, fragment); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function createChild(returnFiber, newChild, lanes) { + function createChild(returnFiber, newChild, lanes, debugInfo) { if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. var created = createFiberFromText( + // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, returnFiber.mode, lanes ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } @@ -8827,8 +8339,16 @@ to return true:wantsResponderID| | lanes ); - _created.ref = coerceRef(returnFiber, null, newChild); + coerceRef(returnFiber, null, _created, newChild); _created.return = returnFiber; + + { + _created._debugInfo = mergeDebugInfo( + debugInfo, + newChild._debugInfo + ); + } + return _created; } @@ -8840,13 +8360,23 @@ to return true:wantsResponderID| | ); _created2.return = returnFiber; + + { + _created2._debugInfo = debugInfo; + } + return _created2; } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; - return createChild(returnFiber, init(payload), lanes); + return createChild( + returnFiber, + init(payload), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) // call merge after init + ); } } @@ -8859,6 +8389,14 @@ to return true:wantsResponderID| | ); _created3.return = returnFiber; + + { + _created3._debugInfo = mergeDebugInfo( + debugInfo, + newChild._debugInfo + ); + } + return _created3; } // Usable node types // @@ -8866,15 +8404,21 @@ to return true:wantsResponderID| | if (typeof newChild.then === "function") { var thenable = newChild; - return createChild(returnFiber, unwrapThenable(thenable), lanes); + return createChild( + returnFiber, + unwrapThenable(thenable), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } if (newChild.$$typeof === REACT_CONTEXT_TYPE) { var context = newChild; return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -8883,20 +8427,25 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } return null; } - function updateSlot(returnFiber, oldFiber, newChild, lanes) { + function updateSlot(returnFiber, oldFiber, newChild, lanes, debugInfo) { // Update the fiber if the keys match, otherwise return null. var key = oldFiber !== null ? oldFiber.key : null; if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text @@ -8905,14 +8454,26 @@ to return true:wantsResponderID| | return null; } - return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes); + return updateTextNode( + returnFiber, + oldFiber, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint + "" + newChild, + lanes, + debugInfo + ); } if (typeof newChild === "object" && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); + return updateElement( + returnFiber, + oldFiber, + newChild, + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } else { return null; } @@ -8920,7 +8481,13 @@ to return true:wantsResponderID| | case REACT_PORTAL_TYPE: { if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); + return updatePortal( + returnFiber, + oldFiber, + newChild, + lanes, + debugInfo + ); } else { return null; } @@ -8929,7 +8496,13 @@ to return true:wantsResponderID| | case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); + return updateSlot( + returnFiber, + oldFiber, + init(payload), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } } @@ -8938,7 +8511,14 @@ to return true:wantsResponderID| | return null; } - return updateFragment(returnFiber, oldFiber, newChild, lanes, null); + return updateFragment( + returnFiber, + oldFiber, + newChild, + lanes, + null, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } // Usable node types // // Unwrap the inner value and recursively call this function again. @@ -8949,7 +8529,8 @@ to return true:wantsResponderID| | returnFiber, oldFiber, unwrapThenable(thenable), - lanes + lanes, + debugInfo ); } @@ -8958,8 +8539,9 @@ to return true:wantsResponderID| | return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -8968,7 +8550,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } @@ -8980,20 +8566,23 @@ to return true:wantsResponderID| | returnFiber, newIdx, newChild, - lanes + lanes, + debugInfo ) { if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. var matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode( returnFiber, - matchedFiber, + matchedFiber, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, - lanes + lanes, + debugInfo ); } @@ -9005,7 +8594,13 @@ to return true:wantsResponderID| | newChild.key === null ? newIdx : newChild.key ) || null; - return updateElement(returnFiber, _matchedFiber, newChild, lanes); + return updateElement( + returnFiber, + _matchedFiber, + newChild, + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } case REACT_PORTAL_TYPE: { @@ -9014,7 +8609,13 @@ to return true:wantsResponderID| | newChild.key === null ? newIdx : newChild.key ) || null; - return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); + return updatePortal( + returnFiber, + _matchedFiber2, + newChild, + lanes, + debugInfo + ); } case REACT_LAZY_TYPE: @@ -9025,7 +8626,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, init(payload), - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -9037,7 +8639,8 @@ to return true:wantsResponderID| | _matchedFiber3, newChild, lanes, - null + null, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } // Usable node types // @@ -9050,7 +8653,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, unwrapThenable(thenable), - lanes + lanes, + debugInfo ); } @@ -9060,8 +8664,9 @@ to return true:wantsResponderID| | existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -9070,7 +8675,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } @@ -9133,7 +8742,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChildren, - lanes + lanes, + debugInfo ) { // This algorithm can't optimize by searching from both ends since we // don't have backpointers on fibers. I'm trying to see how far we can get @@ -9179,7 +8789,8 @@ to return true:wantsResponderID| | returnFiber, oldFiber, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (newFiber === null) { @@ -9233,7 +8844,8 @@ to return true:wantsResponderID| | var _newFiber = createChild( returnFiber, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (_newFiber === null) { @@ -9255,7 +8867,7 @@ to return true:wantsResponderID| | return resultingFirstChild; } // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. + var existingChildren = mapRemainingChildren(oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( @@ -9263,7 +8875,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (_newFiber2 !== null) { @@ -9306,7 +8919,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChildrenIterable, - lanes + lanes, + debugInfo ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. @@ -9391,7 +9005,13 @@ to return true:wantsResponderID| | nextOldFiber = oldFiber.sibling; } - var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); + var newFiber = updateSlot( + returnFiber, + oldFiber, + step.value, + lanes, + debugInfo + ); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's @@ -9441,7 +9061,12 @@ to return true:wantsResponderID| | // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, lanes); + var _newFiber3 = createChild( + returnFiber, + step.value, + lanes, + debugInfo + ); if (_newFiber3 === null) { continue; @@ -9462,7 +9087,7 @@ to return true:wantsResponderID| | return resultingFirstChild; } // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. + var existingChildren = mapRemainingChildren(oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( @@ -9470,7 +9095,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, step.value, - lanes + lanes, + debugInfo ); if (_newFiber4 !== null) { @@ -9537,7 +9163,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, element, - lanes + lanes, + debugInfo ) { var key = element.key; var child = currentFirstChild; @@ -9556,6 +9183,7 @@ to return true:wantsResponderID| | { existing._debugOwner = element._owner; + existing._debugInfo = debugInfo; } return existing; @@ -9576,11 +9204,12 @@ to return true:wantsResponderID| | var _existing = useFiber(child, element.props); - _existing.ref = coerceRef(returnFiber, child, element); + coerceRef(returnFiber, child, _existing, element); _existing.return = returnFiber; { _existing._debugOwner = element._owner; + _existing._debugInfo = debugInfo; } return _existing; @@ -9604,6 +9233,11 @@ to return true:wantsResponderID| | element.key ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { var _created4 = createFiberFromElement( @@ -9612,8 +9246,13 @@ to return true:wantsResponderID| | lanes ); - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); + coerceRef(returnFiber, currentFirstChild, _created4, element); _created4.return = returnFiber; + + { + _created4._debugInfo = debugInfo; + } + return _created4; } } @@ -9622,7 +9261,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, portal, - lanes + lanes, + debugInfo ) { var key = portal.key; var child = currentFirstChild; @@ -9662,7 +9302,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + debugInfo ) { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, @@ -9690,7 +9331,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ) ); @@ -9706,13 +9348,13 @@ to return true:wantsResponderID| | case REACT_LAZY_TYPE: var payload = newChild._payload; - var init = newChild._init; // TODO: This function is supposed to be non-recursive. - - return reconcileChildFibers( + var init = newChild._init; + return reconcileChildFibersImpl( returnFiber, currentFirstChild, init(payload), - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -9721,7 +9363,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -9730,7 +9373,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } // Usables are a valid React node type. When React encounters a Usable in // a child position, it unwraps it using the same algorithm as `use`. For @@ -9755,7 +9399,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, unwrapThenable(thenable), - lanes + lanes, + mergeDebugInfo(debugInfo, thenable._debugInfo) ); } @@ -9764,8 +9409,9 @@ to return true:wantsResponderID| | return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -9774,12 +9420,13 @@ to return true:wantsResponderID| | if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { return placeSingleChild( reconcileSingleTextNode( returnFiber, - currentFirstChild, + currentFirstChild, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, lanes ) @@ -9788,7 +9435,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } // Remaining cases are all treated as empty. @@ -9808,7 +9459,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + null // debugInfo ); thenableState$1 = null; // Don't bother to reset `thenableIndexCounter` to 0 because it always gets // set at the beginning. @@ -10244,7 +9896,7 @@ to return true:wantsResponderID| | error( "React has detected a change in the order of Hooks called by %s. " + "This will lead to bugs and errors if not fixed. " + - "For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n" + + "For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n" + " Previous render Next render\n" + " ------------------------------------------------------\n" + "%s" + @@ -10295,7 +9947,7 @@ to return true:wantsResponderID| | "1. You might have mismatching versions of React and the renderer (such as React DOM)\n" + "2. You might be breaking the Rules of Hooks\n" + "3. You might have more than one copy of React in the same app\n" + - "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } @@ -11867,8 +11519,8 @@ to return true:wantsResponderID| | } function updateTransition() { - var _updateState = updateState(), - booleanOrThenable = _updateState[0]; + var _updateState2 = updateState(), + booleanOrThenable = _updateState2[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; @@ -12127,7 +11779,7 @@ to return true:wantsResponderID| | "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + "You can only call Hooks at the top level of your React function. " + "For more information, see " + - "https://reactjs.org/link/rules-of-hooks" + "https://react.dev/link/rules-of-hooks" ); }; @@ -13156,7 +12808,6 @@ to return true:wantsResponderID| | var didWarnAboutLegacyLifecyclesAndDerivedState; var didWarnAboutUndefinedDerivedState; var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; var didWarnAboutInvalidateContextType; var didWarnOnInvalidCallback; @@ -13167,7 +12818,6 @@ to return true:wantsResponderID| | didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); didWarnAboutDirectlyAssigningPropsToState = new Set(); didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); didWarnOnInvalidCallback = new Set(); // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for @@ -13191,21 +12841,20 @@ to return true:wantsResponderID| | Object.freeze(fakeInternalInstance); } - function warnOnInvalidCallback(callback, callerName) { + function warnOnInvalidCallback(callback) { { if (callback === null || typeof callback === "function") { return; - } + } // eslint-disable-next-line react-internal/safe-string-coercion - var key = callerName + "_" + callback; + var key = String(callback); if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); error( - "%s(...): Expected the last optional `callback` argument to be a " + + "Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", - callerName, callback ); } @@ -13279,7 +12928,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "setState"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13301,7 +12950,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "replaceState"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13323,7 +12972,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "forceUpdate"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13403,13 +13052,13 @@ to return true:wantsResponderID| | if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === "function") { error( - "%s(...): No `render` method found on the returned component " + + "No `render` method found on the %s " + "instance: did you accidentally return an object from the constructor?", name ); } else { error( - "%s(...): No `render` method found on the returned component " + + "No `render` method found on the %s " + "instance: you may have forgotten to define `render`.", name ); @@ -13458,24 +13107,18 @@ to return true:wantsResponderID| | } { - if (instance.contextTypes) { + if (ctor.childContextTypes) { error( - "contextTypes was defined as an instance property on %s. Use a static " + - "property to define contextTypes instead.", + "%s uses the legacy childContextTypes API which is no longer supported. " + + "Use React.createContext() instead.", name ); } - if ( - ctor.contextType && - ctor.contextTypes && - !didWarnAboutContextTypeAndContextTypes.has(ctor) - ) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - + if (ctor.contextTypes) { error( - "%s declares both contextTypes and contextType static properties. " + - "The legacy contextTypes property will be ignored.", + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with static contextType instead.", name ); } @@ -13544,9 +13187,8 @@ to return true:wantsResponderID| | if (instance.props !== undefined && hasMutatedProps) { error( - "%s(...): When calling super() in `%s`, make sure to pass " + + "When calling super() in `%s`, make sure to pass " + "up the same props that your component's constructor was passed.", - name, name ); } @@ -13629,8 +13271,6 @@ to return true:wantsResponderID| | } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = false; - var unmaskedContext = emptyContextObject; var context = emptyContextObject; var contextType = ctor.contextType; @@ -13639,8 +13279,7 @@ to return true:wantsResponderID| | var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE && - contextType._context === undefined); // Not a + contextType.$$typeof === REACT_CONTEXT_TYPE); if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); @@ -13654,11 +13293,7 @@ to return true:wantsResponderID| | "try moving the createContext() call to a separate file."; } else if (typeof contextType !== "object") { addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = - " Did you accidentally pass the Context.Provider instead?"; - } else if (contextType._context !== undefined) { - // + } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { addendum = " Did you accidentally pass the Context.Consumer instead?"; } else { @@ -13680,14 +13315,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { context = readContext(contextType); - } else { - unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - var contextTypes = ctor.contextTypes; - isLegacyContextConsumer = - contextTypes !== null && contextTypes !== undefined; - context = isLegacyContextConsumer - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject; } var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. @@ -13795,7 +13422,7 @@ to return true:wantsResponderID| | "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://reactjs.org/link/unsafe-component-lifecycles", + "https://react.dev/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -13807,12 +13434,7 @@ to return true:wantsResponderID| | } } } - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - - if (isLegacyContextConsumer) { - cacheContext(workInProgress, unmaskedContext, context); - } + } // Cache unmasked context so we can avoid recreating masked context unless necessary. return instance; } @@ -13902,8 +13524,7 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else { - var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - instance.context = getMaskedContext(workInProgress, unmaskedContext); + instance.context = emptyContextObject; } { @@ -13987,16 +13608,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); - } else { - var nextLegacyUnmaskedContext = getUnmaskedContext( - workInProgress, - ctor, - true - ); - nextContext = getMaskedContext( - workInProgress, - nextLegacyUnmaskedContext - ); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; @@ -14140,13 +13751,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); - } else { - var nextUnmaskedContext = getUnmaskedContext( - workInProgress, - ctor, - true - ); - nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; @@ -14300,17 +13904,37 @@ to return true:wantsResponderID| | return shouldUpdate; } + var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. + var stack; + + if (typeof value === "object" && value !== null) { + var capturedStack = CapturedStacks.get(value); + + if (typeof capturedStack === "string") { + stack = capturedStack; + } else { + stack = getStackByFiberInDevAndProd(source); + CapturedStacks.set(value, stack); + } + } else { + stack = getStackByFiberInDevAndProd(source); + } + return { value: value, source: source, - stack: getStackByFiberInDevAndProd(source), + stack: stack, digest: null }; } - function createCapturedValue(value, digest, stack) { + function createCapturedValueFromError(value, digest, stack) { + if (typeof stack === "string") { + CapturedStacks.set(value, stack); + } + return { value: value, source: null, @@ -14356,25 +13980,8 @@ to return true:wantsResponderID| | if (true) { var source = errorInfo.source; var stack = errorInfo.stack; - var componentStack = stack !== null ? stack : ""; // Browsers support silencing uncaught errors by calling - // `preventDefault()` in window `error` handler. - // We record this information as an expando on the error. - - if (error != null && error._suppressLogging) { - if (boundary.tag === ClassComponent) { - // The error is recoverable and was silenced. - // Ignore it and don't print the stack addendum. - // This is handy for testing error boundaries without noise. - return; - } // The error is fatal. Since the silencing might have - // been accidental, we'll surface it anyway. - // However, the browser would have silenced the original error - // so we'll print it first, and then print the stack addendum. - - console["error"](error); // Don't transform to our wrapper - // For a more detailed description of this block, see: - // https://github.com/facebook/react/pull/13384 - } + var componentStack = stack !== null ? stack : ""; // TODO: There's no longer a way to silence these warnings e.g. for tests. + // See https://github.com/facebook/react/pull/13384 var componentName = source ? getComponentNameFromFiber(source) : null; var componentNameMessage = componentName @@ -14387,7 +13994,7 @@ to return true:wantsResponderID| | if (boundary.tag === HostRoot) { errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\n" + - "Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries."; + "Visit https://react.dev/link/error-boundaries to learn more about error boundaries."; } else { var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous"; @@ -14396,19 +14003,17 @@ to return true:wantsResponderID| | ("using the error boundary you provided, " + errorBoundaryName + "."); - } - - var combinedMessage = - componentNameMessage + - "\n" + - componentStack + - "\n\n" + - ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. - // We don't include the original error message and JS stack because the browser - // has already printed it. Even if the application swallows the error, it is still - // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. - - console["error"](combinedMessage); // Don't transform to our wrapper + } // In development, we provide our own message which includes the component stack + // in addition to the error. + + console["error"]( + // Don't transform to our wrapper + "%o\n\n%s\n%s\n\n%s", + error, + componentNameMessage, + componentStack, + errorBoundaryMessage + ); } } catch (e) { // This method must not throw, or React internal state will get messed up. @@ -14999,25 +14604,13 @@ to return true:wantsResponderID| | // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; - var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent + var ref = workInProgress.ref; + var propsWithoutRef; + + { + propsWithoutRef = nextProps; + } // The rest is a fork of updateFunctionComponent var nextChildren; prepareToReadContext(workInProgress, renderLanes); @@ -15029,7 +14622,7 @@ to return true:wantsResponderID| | current, workInProgress, render, - nextProps, + propsWithoutRef, ref, renderLanes ); @@ -15090,19 +14683,6 @@ to return true:wantsResponderID| | } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -15132,22 +14712,6 @@ to return true:wantsResponderID| | return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -15193,40 +14757,6 @@ to return true:wantsResponderID| | // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -15299,7 +14829,7 @@ to return true:wantsResponderID| | var nextIsDetached = (workInProgress.stateNode._pendingVisibility & OffscreenDetached) !== 0; var prevState = current !== null ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if (nextProps.mode === "hidden" || enableLegacyHidden || nextIsDetached) { // Rendering a hidden tree. @@ -15464,16 +14994,26 @@ to return true:wantsResponderID| | return workInProgress.child; } - function markRef$1(current, workInProgress) { + function markRef(current, workInProgress) { + // TODO: Check props.ref instead of fiber.ref when enableRefAsProp is on. var ref = workInProgress.ref; - if ( - (current === null && ref !== null) || - (current !== null && current.ref !== ref) - ) { - // Schedule a Ref effect - workInProgress.flags |= Ref; - workInProgress.flags |= RefStatic; + if (ref === null) { + if (current !== null && current.ref !== null) { + // Schedule a Ref effect + workInProgress.flags |= Ref | RefStatic; + } + } else { + if (typeof ref !== "function" && typeof ref !== "object") { + throw new Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + } + + if (current === null || current.ref !== ref) { + // Schedule a Ref effect + workInProgress.flags |= Ref | RefStatic; + } } } @@ -15484,34 +15024,8 @@ to return true:wantsResponderID| | nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; - { - var unmaskedContext = getUnmaskedContext( - workInProgress, - Component, - true - ); - context = getMaskedContext(workInProgress, unmaskedContext); - } - var nextChildren; prepareToReadContext(workInProgress, renderLanes); @@ -15621,30 +15135,14 @@ to return true:wantsResponderID| | break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -15714,15 +15212,10 @@ to return true:wantsResponderID| | renderLanes ) { // Refs should update even if shouldComponentUpdate returns false - markRef$1(current, workInProgress); + markRef(current, workInProgress); var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags$1; if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, Component, false); - } - return bailoutOnAlreadyFinishedWork( current, workInProgress, @@ -15788,27 +15281,12 @@ to return true:wantsResponderID| | workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. - if (hasContext) { - invalidateContextProvider(workInProgress, Component, true); - } - return workInProgress.child; } function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; - if (root.pendingContext) { - pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - pushHostContainer(workInProgress, root.containerInfo); } @@ -15860,7 +15338,7 @@ to return true:wantsResponderID| | workInProgress.flags |= ContentReset; } - markRef$1(current, workInProgress); + markRef(current, workInProgress); reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } @@ -15941,21 +15419,6 @@ to return true:wantsResponderID| | } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -16005,9 +15468,8 @@ to return true:wantsResponderID| | var hasContext; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -16035,15 +15497,6 @@ to return true:wantsResponderID| | var props = workInProgress.pendingProps; var context; - { - var unmaskedContext = getUnmaskedContext( - workInProgress, - Component, - false - ); - context = getMaskedContext(workInProgress, unmaskedContext); - } - prepareToReadContext(workInProgress, renderLanes); var value; @@ -16153,9 +15606,8 @@ to return true:wantsResponderID| | var hasContext = false; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -16179,6 +15631,16 @@ to return true:wantsResponderID| | // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { + if (Component.contextTypes) { + error( + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with React.useContext() instead.", + getComponentNameFromType(Component) || "Unknown" + ); + } + } + reconcileChildren(null, workInProgress, value, renderLanes); { @@ -16194,7 +15656,8 @@ to return true:wantsResponderID| | if (Component) { if (Component.childContextTypes) { error( - "%s(...): childContextTypes cannot be defined on a function component.", + "childContextTypes cannot be defined on a function component.\n" + + " %s.childContextTypes = ...", Component.displayName || Component.name || "Component" ); } @@ -16828,7 +16291,7 @@ to return true:wantsResponderID| | } error.digest = digest; - capturedValue = createCapturedValue(error, digest, stack); + capturedValue = createCapturedValueFromError(error, digest, stack); } return retrySuspenseComponentWithoutHydrating( @@ -16938,7 +16401,7 @@ to return true:wantsResponderID| | pushPrimaryTreeSuspenseHandler(workInProgress); workInProgress.flags &= ~ForceClientRender; - var _capturedValue = createCapturedValue( + var _capturedValue = createCapturedValueFromError( new Error( "There was an error while hydrating this Suspense boundary. " + "Switched to client rendering." @@ -17427,8 +16890,12 @@ to return true:wantsResponderID| | var hasWarnedAboutUsingNoValuePropOnContextProvider = false; function updateContextProvider(current, workInProgress, renderLanes) { - var providerType = workInProgress.type; - var context = providerType._context; + var context; + + { + context = workInProgress.type._context; + } + var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; var newValue = newProps.value; @@ -17443,17 +16910,6 @@ to return true:wantsResponderID| | ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -17487,34 +16943,16 @@ to return true:wantsResponderID| | return workInProgress.child; } - var hasWarnedAboutUsingContextAsConsumer = false; - function updateContextConsumer(current, workInProgress, renderLanes) { - var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. + var context; { - if (context._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; + context = workInProgress.type; - error( - "Rendering directly is not supported and will be removed in " + - "a future major release. Did you mean to render instead?" - ); - } + { + if (context._context !== undefined) { + context = context._context; } - } else { - context = context._context; } } @@ -17615,7 +17053,11 @@ to return true:wantsResponderID| | newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. + newWorkInProgress.ref = oldWorkInProgress.ref; + + { + newWorkInProgress._debugInfo = oldWorkInProgress._debugInfo; + } // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; @@ -17687,12 +17129,6 @@ to return true:wantsResponderID| | break; case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - pushContextProvider(workInProgress); - } - break; } @@ -17705,7 +17141,12 @@ to return true:wantsResponderID| | case ContextProvider: { var newValue = workInProgress.memoizedProps.value; - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + pushProvider(workInProgress, context, newValue); break; } @@ -17863,7 +17304,7 @@ to return true:wantsResponderID| | return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } - function beginWork$1(current, workInProgress, renderLanes) { + function beginWork(current, workInProgress, renderLanes) { { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. @@ -18049,31 +17490,16 @@ to return true:wantsResponderID| | return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } - - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -18437,7 +17863,7 @@ to return true:wantsResponderID| | return readContextForConsumer(currentlyRenderingFiber, context); } - function readContextDuringReconcilation(consumer, context, renderLanes) { + function readContextDuringReconciliation(consumer, context, renderLanes) { if (currentlyRenderingFiber === null) { prepareToReadContext(consumer, renderLanes); } @@ -18516,10 +17942,6 @@ to return true:wantsResponderID| | function markUpdate(workInProgress) { workInProgress.flags |= Update; } - - function markRef(workInProgress) { - workInProgress.flags |= Ref | RefStatic; - } /** * In persistent mode, return whether this update needs to clone the subtree. */ @@ -19159,12 +18581,6 @@ to return true:wantsResponderID| | return null; case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - bubbleProperties(workInProgress); return null; } @@ -19172,7 +18588,6 @@ to return true:wantsResponderID| | case HostRoot: { var fiberRoot = workInProgress.stateNode; popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; @@ -19229,10 +18644,6 @@ to return true:wantsResponderID| | if (current !== null && workInProgress.stateNode != null) { updateHostComponent(current, workInProgress, _type2, newProps); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } } else { if (!newProps) { if (workInProgress.stateNode === null) { @@ -19272,11 +18683,6 @@ to return true:wantsResponderID| | appendAllChildren(_instance3, workInProgress, false, false); workInProgress.stateNode = _instance3; // Certain renderers require commit-time effects for initial mount. } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } } bubbleProperties(workInProgress); // This must come at the very end of the complete phase, because it might @@ -19331,7 +18737,6 @@ to return true:wantsResponderID| | } case SuspenseComponent: { - popSuspenseHandler(workInProgress); var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this // to its own fiber type so that we can add other kinds of hydration // boundaries that aren't associated with a Suspense tree. In anticipation @@ -19352,17 +18757,21 @@ to return true:wantsResponderID| | if (!fallthroughToNormalSuspensePath) { if (workInProgress.flags & ForceClientRender) { - // Special case. There were remaining unhydrated nodes. We treat + popSuspenseHandler(workInProgress); // Special case. There were remaining unhydrated nodes. We treat // this as a mismatch. Revert to client rendering. + return workInProgress; } else { - // Did not finish hydrating, either because this is the initial + popSuspenseHandler(workInProgress); // Did not finish hydrating, either because this is the initial // render or because something suspended. + return null; } } // Continue with the normal Suspense path. } + popSuspenseHandler(workInProgress); + if ((workInProgress.flags & DidCapture) !== NoFlags$1) { // Something suspended. Re-render with the fallback children. workInProgress.lanes = renderLanes; // Do not reset the effect list. @@ -19429,20 +18838,17 @@ to return true:wantsResponderID| | case ContextProvider: // Pop provider fiber - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + popProvider(context, workInProgress); bubbleProperties(workInProgress); return null; case IncompleteClassComponent: { - // Same as class component case. I put it down here so that the tags are - // sequential to ensure this switch is compiled to a jump table. - var _Component = workInProgress.type; - - if (isContextProvider(_Component)) { - popContext(workInProgress); - } - bubbleProperties(workInProgress); return null; } @@ -19734,12 +19140,6 @@ to return true:wantsResponderID| | function unwindWork(current, workInProgress, renderLanes) { switch (workInProgress.tag) { case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - var flags = workInProgress.flags; if (flags & ShouldCapture) { @@ -19757,7 +19157,6 @@ to return true:wantsResponderID| | case HostRoot: { popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); var _flags = workInProgress.flags; if ( @@ -19821,7 +19220,12 @@ to return true:wantsResponderID| | return null; case ContextProvider: - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + popProvider(context, workInProgress); return null; @@ -19858,18 +19262,11 @@ to return true:wantsResponderID| | function unwindInterruptedWork(current, interruptedWork, renderLanes) { switch (interruptedWork.tag) { case ClassComponent: { - var childContextTypes = interruptedWork.type.childContextTypes; - - if (childContextTypes !== null && childContextTypes !== undefined) { - popContext(interruptedWork); - } - break; } case HostRoot: { popHostContainer(interruptedWork); - popTopLevelContextObject(interruptedWork); break; } @@ -19893,7 +19290,12 @@ to return true:wantsResponderID| | break; case ContextProvider: - var context = interruptedWork.type._context; + var context; + + { + context = interruptedWork.type._context; + } + popProvider(context, interruptedWork); break; @@ -19927,20 +19329,6 @@ to return true:wantsResponderID| | ); } - function reportUncaughtErrorInDEV(error) { - // Wrapping each small part of the commit phase into a guarded - // callback is a bit too slow (https://github.com/facebook/react/pull/21666). - // But we rely on it to surface errors to DEV tools like overlays - // (https://github.com/facebook/react/issues/21712). - // As a compromise, rethrow only caught errors in a guard. - { - invokeGuardedCallback(null, function () { - throw error; - }); - clearCaughtError(); - } - } - function callComponentWillUnmountWithTimer(current, instance) { instance.props = current.memoizedProps; instance.state = current.memoizedState; @@ -20317,7 +19705,7 @@ to return true:wantsResponderID| | " }\n" + " fetchData();\n" + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + - "Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching"; + "Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching"; } else { addendum = " You returned: " + destroy; } @@ -20866,6 +20254,8 @@ to return true:wantsResponderID| | } } else { { + // TODO: We should move these warnings to happen during the render + // phase (markRef). if (!ref.hasOwnProperty("current")) { error( "Unexpected ref object provided for %s. " + @@ -22806,7 +22196,9 @@ to return true:wantsResponderID| | var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. // We will log them once the tree commits. - var workInProgressRootRecoverableErrors = null; // The most recent time we either committed a fallback, or when a fallback was + var workInProgressRootRecoverableErrors = null; // Tracks when an update occurs during the render phase. + + var workInProgressRootDidIncludeRecursiveRenderUpdate = false; // Thacks when an update occurs during the commit phase. It's a separate // filled in with the resolved UI. This lets us throttle the appearance of new // content as it streams in, to minimize jank. // TODO: Think of a better name for this variable? @@ -22830,7 +22222,7 @@ to return true:wantsResponderID| | } var hasUncaughtError = false; var firstUncaughtError = null; - var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; + var legacyErrorBoundariesThatAlreadyFailed = null; var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsLanes = NoLanes; @@ -23322,6 +22714,7 @@ to return true:wantsResponderID| | root, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane ); } else { @@ -23352,6 +22745,7 @@ to return true:wantsResponderID| | finishedWork, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane ), @@ -23366,6 +22760,7 @@ to return true:wantsResponderID| | finishedWork, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane ); @@ -23377,6 +22772,7 @@ to return true:wantsResponderID| | finishedWork, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, lanes, spawnedLane ) { @@ -23401,14 +22797,26 @@ to return true:wantsResponderID| | // us that it's ready. This will be canceled if we start work on the // root again. root.cancelPendingCommit = schedulePendingCommit( - commitRoot.bind(null, root, recoverableErrors, transitions) + commitRoot.bind( + null, + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate + ) ); markRootSuspended(root, lanes, spawnedLane); return; } } // Otherwise, commit immediately. - commitRoot(root, recoverableErrors, transitions, spawnedLane); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); } function isRenderConsistentWithExternalStores(finishedWork) { @@ -23471,13 +22879,23 @@ to return true:wantsResponderID| | // eslint-disable-next-line no-unreachable return true; + } // The extra indirections around markRootUpdated and markRootSuspended is + // needed to avoid a circular dependency between this module and + // ReactFiberLane. There's probably a better way to split up these modules and + // avoid this problem. Perhaps all the root-marking functions should move into + // the work loop. + + function markRootUpdated(root, updatedLanes) { + markRootUpdated$1(root, updatedLanes); + } + + function markRootPinged(root, pingedLanes) { + markRootPinged$1(root, pingedLanes); } function markRootSuspended(root, suspendedLanes, spawnedLane) { // When suspending, we should always exclude lanes that were pinged or (more // rarely, since we try to avoid it) updated during the render phase. - // TODO: Lol maybe there's a better way to factor this besides this - // obnoxiously named function :) suspendedLanes = removeLanes( suspendedLanes, workInProgressRootPingedLanes @@ -23486,6 +22904,7 @@ to return true:wantsResponderID| | suspendedLanes, workInProgressRootInterleavedUpdatedLanes ); + markRootSuspended$1(root, suspendedLanes, spawnedLane); } // This is the entry point for synchronous tasks that don't go // through Scheduler @@ -23560,6 +22979,7 @@ to return true:wantsResponderID| | root, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane ); // Before exiting, make sure there's a callback scheduled for the next // pending level. @@ -23704,7 +23124,8 @@ to return true:wantsResponderID| | workInProgressRootPingedLanes = NoLanes; workInProgressDeferredLane = NoLane; workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; // Get the lanes that are entangled with whatever we're about to render. We + workInProgressRootRecoverableErrors = null; + workInProgressRootDidIncludeRecursiveRenderUpdate = false; // Get the lanes that are entangled with whatever we're about to render. We // track these separately so we can distinguish the priority of the render // task from the priority of the lanes it is entangled with. For example, a // transition may not be allowed to finish unless it includes the Sync lane, @@ -24379,15 +23800,6 @@ to return true:wantsResponderID| | : resolveDefaultProps(Component, unresolvedProps); var context; - { - var unmaskedContext = getUnmaskedContext( - unitOfWork, - Component, - true - ); - context = getMaskedContext(unitOfWork, unmaskedContext); - } - next = replayFunctionComponent( current, unitOfWork, @@ -24668,7 +24080,13 @@ to return true:wantsResponderID| | workInProgress = null; } - function commitRoot(root, recoverableErrors, transitions, spawnedLane) { + function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ) { // TODO: This no longer makes any sense. We already wrap the mutation and // layout phases. Should be able to remove. var previousUpdateLanePriority = getCurrentUpdatePriority(); @@ -24681,6 +24099,7 @@ to return true:wantsResponderID| | root, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, previousUpdateLanePriority, spawnedLane ); @@ -24696,6 +24115,7 @@ to return true:wantsResponderID| | root, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, renderPriorityLevel, spawnedLane ) { @@ -24755,7 +24175,7 @@ to return true:wantsResponderID| | var concurrentlyUpdatedLanes = getConcurrentlyUpdatedLanes(); remainingLanes = mergeLanes(remainingLanes, concurrentlyUpdatedLanes); - markRootFinished(root, remainingLanes, spawnedLane); + markRootFinished(root, remainingLanes, spawnedLane); // Reset this before firing side effects so we can detect recursive updates. if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -24818,7 +24238,7 @@ to return true:wantsResponderID| | // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. commitMutationEffects(root, finishedWork, lanes); // the mutation phase, so that the previous tree is still current during @@ -24937,6 +24357,9 @@ to return true:wantsResponderID| | // hydration is conceptually not an update. if ( + // Check if there was a recursive update spawned by this render, in either + // the render phase or the commit phase. We track these explicitly because + // we can't infer from the remaining lanes alone. // Was the finished render the result of an update (not hydration)? includesSomeLane(lanes, UpdateLanes) && // Did it schedule a sync update? includesSomeLane(remainingLanes, SyncUpdateLanes) @@ -25136,7 +24559,6 @@ to return true:wantsResponderID| | error$1 ) { { - reportUncaughtErrorInDEV(error$1); setIsRunningInsertionEffect(false); } @@ -25358,6 +24780,7 @@ to return true:wantsResponderID| | nestedPassiveUpdateCount = 0; rootWithNestedUpdates = null; rootWithPassiveNestedUpdates = null; + throw new Error( "Maximum update depth exceeded. This can happen when a component " + "repeatedly calls setState inside componentWillUpdate or " + @@ -25514,81 +24937,6 @@ to return true:wantsResponderID| | } } } - var beginWork; - - { - var dummyFiber = null; - - beginWork = function (current, unitOfWork, lanes) { - // If a component throws an error, we replay it again in a synchronously - // dispatched event, so that the debugger will treat it as an uncaught - // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy - // fiber. If beginWork throws, we'll use this to reset the state. - var originalWorkInProgressCopy = assignFiberPropertiesInDEV( - dummyFiber, - unitOfWork - ); - - try { - return beginWork$1(current, unitOfWork, lanes); - } catch (originalError) { - if ( - didSuspendOrErrorWhileHydratingDEV() || - originalError === SuspenseException || - originalError === SelectiveHydrationException || - (originalError !== null && - typeof originalError === "object" && - typeof originalError.then === "function") - ) { - // Don't replay promises. - // Don't replay errors if we are hydrating and have already suspended or handled an error - throw originalError; - } // Don't reset current debug fiber, since we're about to work on the - // same fiber again. - // Unwind the failed stack frame - - resetSuspendedWorkLoopOnUnwind(unitOfWork); - unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. - - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - - if (unitOfWork.mode & ProfileMode) { - // Reset the profiler timer. - startProfilerTimer(unitOfWork); - } // Run beginWork again. - - invokeGuardedCallback( - null, - beginWork$1, - null, - current, - unitOfWork, - lanes - ); - - if (hasCaughtError()) { - var replayError = clearCaughtError(); - - if ( - typeof replayError === "object" && - replayError !== null && - replayError._suppressLogging && - typeof originalError === "object" && - originalError !== null && - !originalError._suppressLogging - ) { - // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. - originalError._suppressLogging = true; - } - } // We always throw the original error in case the second render pass is not idempotent. - // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. - - throw originalError; - } - }; - } - var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInRenderForAnotherComponent; @@ -25619,7 +24967,7 @@ to return true:wantsResponderID| | error( "Cannot update a component (`%s`) while rendering a " + "different component (`%s`). To locate the bad setState() call inside `%s`, " + - "follow the stack trace as described in https://reactjs.org/link/setstate-in-render", + "follow the stack trace as described in https://react.dev/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName @@ -25728,7 +25076,7 @@ to return true:wantsResponderID| | "/* assert on the output */\n\n" + "This ensures that you're testing the behavior the user would see " + "in the browser." + - " Learn more at https://reactjs.org/link/wrap-tests-with-act", + " Learn more at https://react.dev/link/wrap-tests-with-act", getComponentNameFromFiber(fiber) ); } finally { @@ -25760,7 +25108,7 @@ to return true:wantsResponderID| | "/* assert on the output */\n\n" + "This ensures that you're testing the behavior the user would see " + "in the browser." + - " Learn more at https://reactjs.org/link/wrap-tests-with-act" + " Learn more at https://react.dev/link/wrap-tests-with-act" ); } } @@ -26297,6 +25645,7 @@ to return true:wantsResponderID| | { // This isn't directly used but is handy for debugging internals: + this._debugInfo = null; this._debugOwner = null; this._debugNeedsRemount = false; this._debugHookTypes = null; @@ -26435,6 +25784,7 @@ to return true:wantsResponderID| | } { + workInProgress._debugInfo = current._debugInfo; workInProgress._debugNeedsRemount = current._debugNeedsRemount; switch (workInProgress.tag) { @@ -26633,14 +25983,21 @@ to return true:wantsResponderID| | default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: + case REACT_PROVIDER_TYPE: { fiberTag = ContextProvider; break getTag; + } - case REACT_CONTEXT_TYPE: - // This is a consumer + // Fall through + + case REACT_CONTEXT_TYPE: { fiberTag = ContextConsumer; break getTag; + } + + case REACT_CONSUMER_TYPE: + + // Fall through case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; @@ -26809,54 +26166,6 @@ to return true:wantsResponderID| | implementation: portal.implementation }; return fiber; - } // Used for stashing WIP properties to replay failed work in DEV. - - function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoMode); - } // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.refCleanup = source.refCleanup; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - - { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; } function FiberRootNode( @@ -26968,7 +26277,7 @@ to return true:wantsResponderID| | return root; } - var ReactVersion = "18.3.0-canary-03d6f7cf0-20240209"; + var ReactVersion = "18.3.0-canary-9372c6311-20240315"; function createPortal$1( children, @@ -27010,12 +26319,12 @@ to return true:wantsResponderID| | } var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); + var parentContext = findCurrentUnmaskedContext(); if (fiber.tag === ClassComponent) { var Component = fiber.type; - if (isContextProvider(Component)) { + if (isContextProvider()) { return processChildContext(fiber, Component, parentContext); } } @@ -27060,7 +26369,7 @@ to return true:wantsResponderID| | "%s was passed an instance of %s which is inside StrictMode. " + "Instead, add a ref directly to the element you want to reference. " + "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-find-node", + "https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName @@ -27071,7 +26380,7 @@ to return true:wantsResponderID| | "%s was passed an instance of %s which renders StrictMode children. " + "Instead, add a ref directly to the element you want to reference. " + "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-find-node", + "https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName @@ -27161,7 +26470,7 @@ to return true:wantsResponderID| | { if (typeof callback !== "function") { error( - "render(...): Expected the last optional `callback` argument to be a " + + "Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callback ); diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js index 6753ca0e3d8f0f..3e5cf860260b7c 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js @@ -8,76 +8,33 @@ * @nolint * @providesModule ReactFabric-prod * @preventMunge - * @generated SignedSource<> + * @generated SignedSource<<9a40170807089a671035525b144e9dcd>> */ "use strict"; require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), - Scheduler = require("scheduler"); -function invokeGuardedCallbackImpl(name, func, context) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } -} -var hasError = !1, + Scheduler = require("scheduler"), + isArrayImpl = Array.isArray, + hasError = !1, caughtError = null, - hasRethrowError = !1, - rethrowError = null, - reporter = { - onError: function (error) { - hasError = !0; - caughtError = error; - } - }; -function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = !1; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); -} -function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f -) { - invokeGuardedCallback.apply(this, arguments); - if (hasError) { - if (hasError) { - var error = caughtError; - hasError = !1; - caughtError = null; - } else - throw Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ); - hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); - } -} -var isArrayImpl = Array.isArray, getFiberCurrentPropsFromNode$1 = null, getInstanceFromNode$1 = null, getNodeFromInstance$1 = null; function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance$1(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event); + try { + listener(event); + } catch (error) { + hasError || ((hasError = !0), (caughtError = error)); + } event.currentTarget = null; } function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - if (isArrayImpl(dispatchListener)) - throw Error("executeDirectDispatch(...): Invalid `event`."); + if (isArrayImpl(dispatchListener)) throw Error("Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance$1(dispatchInstance) : null; @@ -336,9 +293,7 @@ var instrumentationCallback, }; function accumulate(current, next) { if (null == next) - throw Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); return null == current ? next : isArrayImpl(current) @@ -349,9 +304,7 @@ function accumulate(current, next) { } function accumulateInto(current, next) { if (null == next) - throw Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); if (null == current) return next; if (isArrayImpl(current)) { if (isArrayImpl(next)) return current.push.apply(current, next), current; @@ -940,7 +893,7 @@ eventPluginOrder = Array.prototype.slice.call([ "ReactNativeBridgeEventPlugin" ]); recomputePluginOrdering(); -var injectedNamesToPlugins$jscomp$inline_232 = { +var injectedNamesToPlugins$jscomp$inline_227 = { ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: { eventTypes: {}, @@ -986,32 +939,32 @@ var injectedNamesToPlugins$jscomp$inline_232 = { } } }, - isOrderingDirty$jscomp$inline_233 = !1, - pluginName$jscomp$inline_234; -for (pluginName$jscomp$inline_234 in injectedNamesToPlugins$jscomp$inline_232) + isOrderingDirty$jscomp$inline_228 = !1, + pluginName$jscomp$inline_229; +for (pluginName$jscomp$inline_229 in injectedNamesToPlugins$jscomp$inline_227) if ( - injectedNamesToPlugins$jscomp$inline_232.hasOwnProperty( - pluginName$jscomp$inline_234 + injectedNamesToPlugins$jscomp$inline_227.hasOwnProperty( + pluginName$jscomp$inline_229 ) ) { - var pluginModule$jscomp$inline_235 = - injectedNamesToPlugins$jscomp$inline_232[pluginName$jscomp$inline_234]; + var pluginModule$jscomp$inline_230 = + injectedNamesToPlugins$jscomp$inline_227[pluginName$jscomp$inline_229]; if ( - !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_234) || - namesToPlugins[pluginName$jscomp$inline_234] !== - pluginModule$jscomp$inline_235 + !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_229) || + namesToPlugins[pluginName$jscomp$inline_229] !== + pluginModule$jscomp$inline_230 ) { - if (namesToPlugins[pluginName$jscomp$inline_234]) + if (namesToPlugins[pluginName$jscomp$inline_229]) throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - (pluginName$jscomp$inline_234 + "`.") + (pluginName$jscomp$inline_229 + "`.") ); - namesToPlugins[pluginName$jscomp$inline_234] = - pluginModule$jscomp$inline_235; - isOrderingDirty$jscomp$inline_233 = !0; + namesToPlugins[pluginName$jscomp$inline_229] = + pluginModule$jscomp$inline_230; + isOrderingDirty$jscomp$inline_228 = !0; } } -isOrderingDirty$jscomp$inline_233 && recomputePluginOrdering(); +isOrderingDirty$jscomp$inline_228 && recomputePluginOrdering(); var emptyObject = {}, removedKeys = null, removedKeyCount = 0, @@ -1304,12 +1257,9 @@ function dispatchEvent(target, topLevelType, nativeEvent) { throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); - if (hasRethrowError) + if (hasError) throw ( - ((event = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - event) + ((event = caughtError), (hasError = !1), (caughtError = null), event) ); } }); @@ -1491,7 +1441,7 @@ function createLaneMap(initial) { for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial); return laneMap; } -function markRootUpdated(root, updateLane) { +function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; 268435456 !== updateLane && ((root.suspendedLanes = 0), (root.pingedLanes = 0)); @@ -1624,6 +1574,11 @@ function cloneHiddenInstance(instance) { canonical: instance.canonical }; } +var supportsMicrotasks = + "undefined" !== typeof RN$enableMicrotasksInReact && + !!RN$enableMicrotasksInReact, + scheduleMicrotask = + "function" === typeof queueMicrotask ? queueMicrotask : scheduleTimeout; function getInstanceFromNode(node) { return null != node.canonical && null != node.canonical.internalInstanceHandle ? node.canonical.internalInstanceHandle @@ -1662,6 +1617,7 @@ var REACT_ELEMENT_TYPE = Symbol.for("react.element"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), @@ -1682,115 +1638,7 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } -var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); -function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE - ? null - : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if ("object" === typeof type) - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - return (type.displayName || "Context") + ".Consumer"; - case REACT_PROVIDER_TYPE: - return (type._context.displayName || "Context") + ".Provider"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || - ((type = innerType.displayName || innerType.name || ""), - (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); - return type; - case REACT_MEMO_TYPE: - return ( - (innerType = type.displayName || null), - null !== innerType - ? innerType - : getComponentNameFromType(type.type) || "Memo" - ); - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) {} - } - return null; -} -function getComponentNameFromFiber(fiber) { - var type = fiber.type; - switch (fiber.tag) { - case 24: - return "Cache"; - case 9: - return (type.displayName || "Context") + ".Consumer"; - case 10: - return (type._context.displayName || "Context") + ".Provider"; - case 18: - return "DehydratedFragment"; - case 11: - return ( - (fiber = type.render), - (fiber = fiber.displayName || fiber.name || ""), - type.displayName || - ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef") - ); - case 7: - return "Fragment"; - case 26: - case 27: - case 5: - return type; - case 4: - return "Portal"; - case 3: - return "Root"; - case 6: - return "Text"; - case 16: - return getComponentNameFromType(type); - case 8: - return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode"; - case 22: - return "Offscreen"; - case 12: - return "Profiler"; - case 21: - return "Scope"; - case 13: - return "Suspense"; - case 19: - return "SuspenseList"; - case 25: - return "TracingMarker"; - case 1: - case 0: - case 17: - case 2: - case 14: - case 15: - if ("function" === typeof type) - return type.displayName || type.name || null; - if ("string" === typeof type) return type; - } - return null; -} +Symbol.for("react.client.reference"); function getNearestMountedFiber(fiber) { var node = fiber, nearestMounted = fiber; @@ -1899,18 +1747,7 @@ function findCurrentHostFiberImpl(node) { } return null; } -function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - ownerName && (sourceInfo = " (created by " + ownerName + ")"); - return "\n in " + (name || "Unknown") + sourceInfo; -} -function describeFunctionComponentFrame(fn) { - return fn - ? describeComponentFrame(fn.displayName || fn.name || null, null) - : ""; -} -var hasOwnProperty = Object.prototype.hasOwnProperty, - valueStack = [], +var valueStack = [], index = -1; function createCursor(defaultValue) { return { current: defaultValue }; @@ -1924,89 +1761,7 @@ function push(cursor, value) { valueStack[index] = cursor.current; cursor.current = value; } -var emptyContextObject = {}, - contextStackCursor$1 = createCursor(emptyContextObject), - didPerformWorkStackCursor = createCursor(!1), - previousContext = emptyContextObject; -function getMaskedContext(workInProgress, unmaskedContext) { - var contextTypes = workInProgress.type.contextTypes; - if (!contextTypes) return emptyContextObject; - var instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) - return instance.__reactInternalMemoizedMaskedChildContext; - var context = {}, - key; - for (key in contextTypes) context[key] = unmaskedContext[key]; - instance && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); - return context; -} -function isContextProvider(type) { - type = type.childContextTypes; - return null !== type && void 0 !== type; -} -function popContext() { - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); -} -function pushTopLevelContextObject(fiber, context, didChange) { - if (contextStackCursor$1.current !== emptyContextObject) - throw Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); - push(contextStackCursor$1, context); - push(didPerformWorkStackCursor, didChange); -} -function processChildContext(fiber, type, parentContext) { - var instance = fiber.stateNode; - type = type.childContextTypes; - if ("function" !== typeof instance.getChildContext) return parentContext; - instance = instance.getChildContext(); - for (var contextKey in instance) - if (!(contextKey in type)) - throw Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - return assign({}, parentContext, instance); -} -function pushContextProvider(workInProgress) { - workInProgress = - ((workInProgress = workInProgress.stateNode) && - workInProgress.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current); - return !0; -} -function invalidateContextProvider(workInProgress, type, didChange) { - var instance = workInProgress.stateNode; - if (!instance) - throw Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ); - didChange - ? ((workInProgress = processChildContext( - workInProgress, - type, - previousContext - )), - (instance.__reactInternalMemoizedMergedChildContext = workInProgress), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - push(contextStackCursor$1, workInProgress)) - : pop(didPerformWorkStackCursor); - push(didPerformWorkStackCursor, didChange); -} +var emptyContextObject = {}; function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } @@ -2143,7 +1898,7 @@ function ensureRootIsScheduled(root) { mightHavePendingSyncWork = !0; didScheduleMicrotask || ((didScheduleMicrotask = !0), - scheduleCallback$2(ImmediatePriority, processRootScheduleInMicrotask)); + scheduleImmediateTask(processRootScheduleInMicrotask)); scheduleTaskForRootDuringMicrotask(root, now()); } function flushSyncWorkAcrossRoots_impl(onlyLegacy) { @@ -2212,6 +1967,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { workInProgressRootRenderLanes$9, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane )); } @@ -2229,8 +1985,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { if ("function" === typeof AggregateError) throw new AggregateError(errors); for (onlyLegacy = 1; onlyLegacy < errors.length; onlyLegacy++) - (didPerformSomeWork = throwError.bind(null, errors[onlyLegacy])), - scheduleCallback$2(ImmediatePriority, didPerformSomeWork); + scheduleImmediateTask(throwError.bind(null, errors[onlyLegacy])); } throw errors[0]; } @@ -2330,6 +2085,15 @@ function scheduleTaskForRootDuringMicrotask(root, currentTime) { root.callbackNode = suspendedLanes; return currentTime; } +function scheduleImmediateTask(cb) { + supportsMicrotasks + ? scheduleMicrotask(function () { + 0 !== (executionContext & 6) + ? scheduleCallback$2(ImmediatePriority, cb) + : cb(); + }) + : scheduleCallback$2(ImmediatePriority, cb); +} var hasForceUpdate = !1; function initializeUpdateQueue(fiber) { fiber.updateQueue = { @@ -2566,6 +2330,7 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { if (objectIs(objA, objB)) return !0; if ( @@ -2588,6 +2353,16 @@ function shallowEqual(objA, objB) { } return !0; } +function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + ownerName && (sourceInfo = " (created by " + ownerName + ")"); + return "\n in " + (name || "Unknown") + sourceInfo; +} +function describeFunctionComponentFrame(fn) { + return fn + ? describeComponentFrame(fn.displayName || fn.name || null, null) + : ""; +} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -2612,6 +2387,18 @@ function describeFiber(fiber) { return ""; } } +function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ""; + do + (info += describeFiber(workInProgress)), + (workInProgress = workInProgress.return); + while (workInProgress); + return info; + } catch (x) { + return "\nError generating stack: " + x.message + "\n" + x.stack; + } +} var SuspenseException = Error( "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`" ), @@ -2664,16 +2451,16 @@ function trackUsedThenable(thenableState, thenable, index) { } } ); - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw ( - ((thenableState = thenable.reason), - checkIfUseWrappedInAsyncCatch(thenableState), - thenableState) - ); - } + } + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw ( + ((thenableState = thenable.reason), + checkIfUseWrappedInAsyncCatch(thenableState), + thenableState) + ); } suspendedThenable = thenable; throw SuspenseException; @@ -2703,56 +2490,54 @@ function unwrapThenable(thenable) { null === thenableState$1 && (thenableState$1 = []); return trackUsedThenable(thenableState$1, thenable, index); } -function coerceRef(returnFiber, current, element) { - returnFiber = element.ref; - if ( - null !== returnFiber && - "function" !== typeof returnFiber && - "object" !== typeof returnFiber - ) { - if (element._owner) { - element = element._owner; - if (element) { - if (1 !== element.tag) - throw Error( - "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref" - ); - var inst = element.stateNode; - } - if (!inst) - throw Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ); - var resolvedInst = inst, - stringRef = "" + returnFiber; - if ( - null !== current && - null !== current.ref && - "function" === typeof current.ref && - current.ref._stringRef === stringRef - ) - return current.ref; - current = function (value) { - var refs = resolvedInst.refs; - null === value ? delete refs[stringRef] : (refs[stringRef] = value); - }; - current._stringRef = stringRef; - return current; - } - if ("string" !== typeof returnFiber) - throw Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - if (!element._owner) - throw Error( - "Element ref was specified as a string (" + - returnFiber + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information." - ); +function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef +) { + function ref(value) { + var refs = inst.refs; + null === value ? delete refs[stringRef] : (refs[stringRef] = value); } - return returnFiber; + var stringRef = "" + mixedRef; + returnFiber = element._owner; + if (!returnFiber) + throw Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://react.dev/link/refs-must-have-owner for more information." + ); + if (1 !== returnFiber.tag) + throw Error( + "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://react.dev/link/strict-mode-string-ref" + ); + var inst = returnFiber.stateNode; + if (!inst) + throw Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + if ( + null !== current && + null !== current.ref && + "function" === typeof current.ref && + current.ref._stringRef === stringRef + ) + return current.ref; + ref._stringRef = stringRef; + return ref; +} +function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef = element.ref; + returnFiber = + "string" === typeof mixedRef || + "number" === typeof mixedRef || + "boolean" === typeof mixedRef + ? convertStringRefToCallbackRef(returnFiber, current, element, mixedRef) + : mixedRef; + workInProgress.ref = returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { returnFiber = Object.prototype.toString.call(newChild); @@ -2784,13 +2569,13 @@ function createChildReconciler(shouldTrackSideEffects) { (currentFirstChild = currentFirstChild.sibling); return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { - for (returnFiber = new Map(); null !== currentFirstChild; ) + function mapRemainingChildren(currentFirstChild) { + for (var existingChildren = new Map(); null !== currentFirstChild; ) null !== currentFirstChild.key - ? returnFiber.set(currentFirstChild.key, currentFirstChild) - : returnFiber.set(currentFirstChild.index, currentFirstChild), + ? existingChildren.set(currentFirstChild.key, currentFirstChild) + : existingChildren.set(currentFirstChild.index, currentFirstChild), (currentFirstChild = currentFirstChild.sibling); - return returnFiber; + return existingChildren; } function useFiber(fiber, pendingProps) { fiber = createWorkInProgress(fiber, pendingProps); @@ -2850,7 +2635,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) return ( (lanes = useFiber(current, element.props)), - (lanes.ref = coerceRef(returnFiber, current, element)), + coerceRef(returnFiber, current, lanes, element), (lanes.return = returnFiber), lanes ); @@ -2862,7 +2647,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes ); - lanes.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, lanes, element); lanes.return = returnFiber; return lanes; } @@ -2924,7 +2709,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef(returnFiber, null, newChild)), + coerceRef(returnFiber, null, lanes, newChild), (lanes.return = returnFiber), lanes ); @@ -2958,7 +2743,7 @@ function createChildReconciler(shouldTrackSideEffects) { if (newChild.$$typeof === REACT_CONTEXT_TYPE) return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3005,7 +2790,7 @@ function createChildReconciler(shouldTrackSideEffects) { return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3073,7 +2858,7 @@ function createChildReconciler(shouldTrackSideEffects) { existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3139,7 +2924,7 @@ function createChildReconciler(shouldTrackSideEffects) { return resultingFirstChild; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++ ) @@ -3227,7 +3012,7 @@ function createChildReconciler(shouldTrackSideEffects) { return iteratorFn; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildrenIterable.next() ) @@ -3289,11 +3074,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) { deleteRemainingChildren(returnFiber, child.sibling); currentFirstChild = useFiber(child, newChild.props); - currentFirstChild.ref = coerceRef( - returnFiber, - child, - newChild - ); + coerceRef(returnFiber, child, currentFirstChild, newChild); currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; @@ -3320,11 +3101,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef( - returnFiber, - currentFirstChild, - newChild - )), + coerceRef(returnFiber, currentFirstChild, lanes, newChild), (lanes.return = returnFiber), (returnFiber = lanes)); } @@ -3370,7 +3147,7 @@ function createChildReconciler(shouldTrackSideEffects) { case REACT_LAZY_TYPE: return ( (child = newChild._init), - reconcileChildFibers( + reconcileChildFibersImpl( returnFiber, currentFirstChild, child(newChild._payload), @@ -3403,7 +3180,7 @@ function createChildReconciler(shouldTrackSideEffects) { return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3427,12 +3204,7 @@ function createChildReconciler(shouldTrackSideEffects) { placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild); } - function reconcileChildFibers( - returnFiber, - currentFirstChild, - newChild, - lanes - ) { + return function (returnFiber, currentFirstChild, newChild, lanes) { thenableIndexCounter$1 = 0; returnFiber = reconcileChildFibersImpl( returnFiber, @@ -3442,8 +3214,7 @@ function createChildReconciler(shouldTrackSideEffects) { ); thenableState$1 = null; return returnFiber; - } - return reconcileChildFibers; + }; } var reconcileChildFibers = createChildReconciler(!0), mountChildFibers = createChildReconciler(!1), @@ -3536,7 +3307,7 @@ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, globalClientIdCounter = 0; function throwInvalidHookError() { throw Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } function areHookInputsEqual(nextDeps, prevDeps) { @@ -4425,30 +4196,17 @@ function checkShouldComponentUpdate( : !0; } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = !1, - unmaskedContext = emptyContextObject; - var context = ctor.contextType; - "object" === typeof context && null !== context - ? (context = readContext(context)) - : ((unmaskedContext = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (isLegacyContextConsumer = ctor.contextTypes), - (context = (isLegacyContextConsumer = - null !== isLegacyContextConsumer && void 0 !== isLegacyContextConsumer) - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject)); + var context = emptyContextObject, + contextType = ctor.contextType; + "object" === typeof contextType && + null !== contextType && + (context = readContext(contextType)); ctor = new ctor(props, context); workInProgress.memoizedState = null !== ctor.state && void 0 !== ctor.state ? ctor.state : null; ctor.updater = classComponentUpdater; workInProgress.stateNode = ctor; ctor._reactInternals = workInProgress; - isLegacyContextConsumer && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); return ctor; } function callComponentWillReceiveProps( @@ -4472,12 +4230,10 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { instance.refs = {}; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; - "object" === typeof contextType && null !== contextType - ? (instance.context = readContext(contextType)) - : ((contextType = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (instance.context = getMaskedContext(workInProgress, contextType))); + instance.context = + "object" === typeof contextType && null !== contextType + ? readContext(contextType) + : emptyContextObject; instance.state = workInProgress.memoizedState; contextType = ctor.getDerivedStateFromProps; "function" === typeof contextType && @@ -4499,22 +4255,23 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { "function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308); } +var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { - try { - var info = "", - node = source; - do (info += describeFiber(node)), (node = node.return); - while (node); - var JSCompiler_inline_result = info; - } catch (x) { - JSCompiler_inline_result = - "\nError generating stack: " + x.message + "\n" + x.stack; - } + if ("object" === typeof value && null !== value) { + var stack = CapturedStacks.get(value); + "string" !== typeof stack && + ((stack = getStackByFiberInDevAndProd(source)), + CapturedStacks.set(value, stack)); + } else stack = getStackByFiberInDevAndProd(source); + return { value: value, source: source, stack: stack, digest: null }; +} +function createCapturedValueFromError(value, digest, stack) { + "string" === typeof stack && CapturedStacks.set(value, stack); return { value: value, - source: source, - stack: JSCompiler_inline_result, - digest: null + source: null, + stack: null != stack ? stack : null, + digest: null != digest ? digest : null }; } if ( @@ -4860,7 +4617,7 @@ function updateOffscreenComponent(current, workInProgress, renderLanes) { nextChildren = nextProps.children, nextIsDetached = 0 !== (workInProgress.stateNode._pendingVisibility & 2), prevState = null !== current ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if ("hidden" === nextProps.mode || nextIsDetached) { if (0 !== (workInProgress.flags & 128)) { renderLanes = @@ -4914,13 +4671,20 @@ function deferHiddenOffscreenComponent(current, workInProgress, nextBaseLanes) { pushOffscreenSuspenseHandler(workInProgress); return null; } -function markRef$1(current, workInProgress) { +function markRef(current, workInProgress) { var ref = workInProgress.ref; - if ( - (null === current && null !== ref) || - (null !== current && current.ref !== ref) - ) - (workInProgress.flags |= 512), (workInProgress.flags |= 2097152); + if (null === ref) + null !== current && + null !== current.ref && + (workInProgress.flags |= 2097664); + else { + if ("function" !== typeof ref && "object" !== typeof ref) + throw Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + if (null === current || current.ref !== ref) + workInProgress.flags |= 2097664; + } } function updateFunctionComponent( current, @@ -4929,17 +4693,13 @@ function updateFunctionComponent( nextProps, renderLanes ) { - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(workInProgress, context); prepareToReadContext(workInProgress, renderLanes); Component = renderWithHooks( current, workInProgress, Component, nextProps, - context, + void 0, renderLanes ); if (null !== current && !didReceiveUpdate) @@ -4983,10 +4743,6 @@ function updateClassComponent( nextProps, renderLanes ) { - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; prepareToReadContext(workInProgress, renderLanes); if (null === workInProgress.stateNode) resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), @@ -4998,36 +4754,30 @@ function updateClassComponent( oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context, - contextType = Component.contextType; - "object" === typeof contextType && null !== contextType - ? (contextType = readContext(contextType)) - : ((contextType = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (contextType = getMaskedContext(workInProgress, contextType))); - var getDerivedStateFromProps = Component.getDerivedStateFromProps, - hasNewLifecycles = - "function" === typeof getDerivedStateFromProps || - "function" === typeof instance.getSnapshotBeforeUpdate; - hasNewLifecycles || + contextType = Component.contextType, + nextContext = emptyContextObject; + "object" === typeof contextType && + null !== contextType && + (nextContext = readContext(contextType)); + var getDerivedStateFromProps = Component.getDerivedStateFromProps; + (contextType = + "function" === typeof getDerivedStateFromProps || + "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== nextProps || oldContext !== contextType) && + ((oldProps !== nextProps || oldContext !== nextContext) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - contextType + nextContext )); hasForceUpdate = !1; var oldState = workInProgress.memoizedState; instance.state = oldState; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); oldContext = workInProgress.memoizedState; - oldProps !== nextProps || - oldState !== oldContext || - didPerformWorkStackCursor.current || - hasForceUpdate + oldProps !== nextProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps( workInProgress, @@ -5045,9 +4795,9 @@ function updateClassComponent( nextProps, oldState, oldContext, - contextType + nextContext )) - ? (hasNewLifecycles || + ? (contextType || ("function" !== typeof instance.UNSAFE_componentWillMount && "function" !== typeof instance.componentWillMount) || ("function" === typeof instance.componentWillMount && @@ -5062,7 +4812,7 @@ function updateClassComponent( (workInProgress.memoizedState = oldContext)), (instance.props = nextProps), (instance.state = oldContext), - (instance.context = contextType), + (instance.context = nextContext), (nextProps = oldProps)) : ("function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308), @@ -5070,48 +4820,46 @@ function updateClassComponent( } else { instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); - oldProps = workInProgress.memoizedProps; + nextContext = workInProgress.memoizedProps; contextType = workInProgress.type === workInProgress.elementType - ? oldProps - : resolveDefaultProps(workInProgress.type, oldProps); + ? nextContext + : resolveDefaultProps(workInProgress.type, nextContext); instance.props = contextType; - hasNewLifecycles = workInProgress.pendingProps; - oldState = instance.context; + getDerivedStateFromProps = workInProgress.pendingProps; + var oldContext$jscomp$0 = instance.context; oldContext = Component.contextType; - "object" === typeof oldContext && null !== oldContext - ? (oldContext = readContext(oldContext)) - : ((oldContext = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (oldContext = getMaskedContext(workInProgress, oldContext))); - var getDerivedStateFromProps$jscomp$0 = Component.getDerivedStateFromProps; - (getDerivedStateFromProps = - "function" === typeof getDerivedStateFromProps$jscomp$0 || + oldProps = emptyContextObject; + "object" === typeof oldContext && + null !== oldContext && + (oldProps = readContext(oldContext)); + oldState = Component.getDerivedStateFromProps; + (oldContext = + "function" === typeof oldState || "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== hasNewLifecycles || oldState !== oldContext) && + ((nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== oldProps) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - oldContext + oldProps )); hasForceUpdate = !1; - oldState = workInProgress.memoizedState; - instance.state = oldState; + oldContext$jscomp$0 = workInProgress.memoizedState; + instance.state = oldContext$jscomp$0; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); var newState = workInProgress.memoizedState; - oldProps !== hasNewLifecycles || - oldState !== newState || - didPerformWorkStackCursor.current || + nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== newState || hasForceUpdate - ? ("function" === typeof getDerivedStateFromProps$jscomp$0 && + ? ("function" === typeof oldState && (applyDerivedStateFromProps( workInProgress, Component, - getDerivedStateFromProps$jscomp$0, + oldState, nextProps ), (newState = workInProgress.memoizedState)), @@ -5122,47 +4870,47 @@ function updateClassComponent( Component, contextType, nextProps, - oldState, + oldContext$jscomp$0, newState, - oldContext + oldProps ) || !1) - ? (getDerivedStateFromProps || + ? (oldContext || ("function" !== typeof instance.UNSAFE_componentWillUpdate && "function" !== typeof instance.componentWillUpdate) || ("function" === typeof instance.componentWillUpdate && - instance.componentWillUpdate(nextProps, newState, oldContext), + instance.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof instance.UNSAFE_componentWillUpdate && instance.UNSAFE_componentWillUpdate( nextProps, newState, - oldContext + oldProps )), "function" === typeof instance.componentDidUpdate && (workInProgress.flags |= 4), "function" === typeof instance.getSnapshotBeforeUpdate && (workInProgress.flags |= 1024)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (workInProgress.memoizedProps = nextProps), (workInProgress.memoizedState = newState)), (instance.props = nextProps), (instance.state = newState), - (instance.context = oldContext), + (instance.context = oldProps), (nextProps = contextType)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (nextProps = !1)); } @@ -5171,7 +4919,7 @@ function updateClassComponent( workInProgress, Component, nextProps, - hasContext, + !1, renderLanes ); } @@ -5183,21 +4931,18 @@ function finishClassComponent( hasContext, renderLanes ) { - markRef$1(current, workInProgress); - var didCaptureError = 0 !== (workInProgress.flags & 128); - if (!shouldUpdate && !didCaptureError) - return ( - hasContext && invalidateContextProvider(workInProgress, Component, !1), - bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) - ); + markRef(current, workInProgress); + hasContext = 0 !== (workInProgress.flags & 128); + if (!shouldUpdate && !hasContext) + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); shouldUpdate = workInProgress.stateNode; ReactCurrentOwner$1.current = workInProgress; - var nextChildren = - didCaptureError && "function" !== typeof Component.getDerivedStateFromError + Component = + hasContext && "function" !== typeof Component.getDerivedStateFromError ? null : shouldUpdate.render(); workInProgress.flags |= 1; - null !== current && didCaptureError + null !== current && hasContext ? ((workInProgress.child = reconcileChildFibers( workInProgress, current.child, @@ -5207,26 +4952,13 @@ function finishClassComponent( (workInProgress.child = reconcileChildFibers( workInProgress, null, - nextChildren, + Component, renderLanes ))) - : reconcileChildren(current, workInProgress, nextChildren, renderLanes); + : reconcileChildren(current, workInProgress, Component, renderLanes); workInProgress.memoizedState = shouldUpdate.state; - hasContext && invalidateContextProvider(workInProgress, Component, !0); return workInProgress.child; } -function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - root.pendingContext - ? pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ) - : root.context && - pushTopLevelContextObject(workInProgress, root.context, !1); - pushHostContainer(workInProgress, root.containerInfo); -} var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: null }; @@ -5418,18 +5150,16 @@ function updateDehydratedSuspenseComponent( return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags &= -257), + (didPrimaryChildrenDefer = createCapturedValueFromError( + Error( + "There was an error while hydrating this Suspense boundary. Switched to client rendering." + ) + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: Error( - "There was an error while hydrating this Suspense boundary. Switched to client rendering." - ), - source: null, - stack: null, - digest: null - } + didPrimaryChildrenDefer ) ); if (null !== workInProgress.memoizedState) @@ -5486,17 +5216,16 @@ function updateDehydratedSuspenseComponent( "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering." )), (suspenseState.digest = didPrimaryChildrenDefer), + (didPrimaryChildrenDefer = createCapturedValueFromError( + suspenseState, + didPrimaryChildrenDefer, + void 0 + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: suspenseState, - source: null, - stack: null, - digest: - null != didPrimaryChildrenDefer ? didPrimaryChildrenDefer : null - } + didPrimaryChildrenDefer ) ); didPrimaryChildrenDefer = 0 !== (renderLanes & current.childLanes); @@ -5726,29 +5455,25 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ) { switch (workInProgress.tag) { case 3: - pushHostRootContext(workInProgress); + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 27: case 5: pushHostContext(workInProgress); break; - case 1: - isContextProvider(workInProgress.type) && - pushContextProvider(workInProgress); - break; case 4: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 10: - var context = workInProgress.type._context, - nextValue = workInProgress.memoizedProps.value; + var newValue = workInProgress.memoizedProps.value, + context = workInProgress.type._context; push(valueCursor, context._currentValue2); - context._currentValue2 = nextValue; + context._currentValue2 = newValue; break; case 13: - context = workInProgress.memoizedState; - if (null !== context) { - if (null !== context.dehydrated) + newValue = workInProgress.memoizedState; + if (null !== newValue) { + if (null !== newValue.dehydrated) return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags |= 128), @@ -5767,9 +5492,9 @@ function attemptEarlyBailoutIfNoScheduledUpdate( pushPrimaryTreeSuspenseHandler(workInProgress); break; case 19: - context = 0 !== (renderLanes & workInProgress.childLanes); + newValue = 0 !== (renderLanes & workInProgress.childLanes); if (0 !== (current.flags & 128)) { - if (context) + if (newValue) return updateSuspenseListComponent( current, workInProgress, @@ -5777,13 +5502,13 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ); workInProgress.flags |= 128; } - nextValue = workInProgress.memoizedState; - null !== nextValue && - ((nextValue.rendering = null), - (nextValue.tail = null), - (nextValue.lastEffect = null)); + context = workInProgress.memoizedState; + null !== context && + ((context.rendering = null), + (context.tail = null), + (context.lastEffect = null)); push(suspenseStackCursor, suspenseStackCursor.current); - if (context) break; + if (newValue) break; else return null; case 22: case 23: @@ -5794,3107 +5519,3081 @@ function attemptEarlyBailoutIfNoScheduledUpdate( } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } -var valueCursor = createCursor(null), - currentlyRenderingFiber = null, - lastContextDependency = null, - lastFullyObservedContext = null; -function resetContextDependencies() { - lastFullyObservedContext = - lastContextDependency = - currentlyRenderingFiber = - null; -} -function popProvider(context) { - context._currentValue2 = valueCursor.current; - pop(valueCursor); -} -function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - for (; null !== parent; ) { - var alternate = parent.alternate; - (parent.childLanes & renderLanes) !== renderLanes - ? ((parent.childLanes |= renderLanes), - null !== alternate && (alternate.childLanes |= renderLanes)) - : null !== alternate && - (alternate.childLanes & renderLanes) !== renderLanes && - (alternate.childLanes |= renderLanes); - if (parent === propagationRoot) break; - parent = parent.return; - } -} -function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastFullyObservedContext = lastContextDependency = null; - workInProgress = workInProgress.dependencies; - null !== workInProgress && - null !== workInProgress.firstContext && - (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), - (workInProgress.firstContext = null)); -} -function readContext(context) { - return readContextForConsumer(currentlyRenderingFiber, context); -} -function readContextDuringReconcilation(consumer, context, renderLanes) { - null === currentlyRenderingFiber && - prepareToReadContext(consumer, renderLanes); - return readContextForConsumer(consumer, context); -} -function readContextForConsumer(consumer, context) { - var value = context._currentValue2; - if (lastFullyObservedContext !== context) - if ( - ((context = { context: context, memoizedValue: value, next: null }), - null === lastContextDependency) - ) { - if (null === consumer) - throw Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." +function beginWork(current, workInProgress, renderLanes) { + if (null !== current) + if (current.memoizedProps !== workInProgress.pendingProps) + didReceiveUpdate = !0; + else { + if ( + 0 === (current.lanes & renderLanes) && + 0 === (workInProgress.flags & 128) + ) + return ( + (didReceiveUpdate = !1), + attemptEarlyBailoutIfNoScheduledUpdate( + current, + workInProgress, + renderLanes + ) ); - lastContextDependency = context; - consumer.dependencies = { lanes: 0, firstContext: context }; - } else lastContextDependency = lastContextDependency.next = context; - return value; -} -var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; -function handleAsyncAction() {} -function doesRequireClone(current, completedWork) { - if (null !== current && current.child === completedWork.child) return !1; - if (0 !== (completedWork.flags & 16)) return !0; - for (current = completedWork.child; null !== current; ) { - if (0 !== (current.flags & 12854) || 0 !== (current.subtreeFlags & 12854)) - return !0; - current = current.sibling; - } - return !1; -} -function appendAllChildren( - parent, - workInProgress, - needsVisibilityToggle, - isHidden -) { - for (var node = workInProgress.child; null !== node; ) { - if (5 === node.tag) { - var instance = node.stateNode; - needsVisibilityToggle && - isHidden && - (instance = cloneHiddenInstance(instance)); - appendChildNode(parent.node, instance.node); - } else if (6 === node.tag) { - instance = node.stateNode; - if (needsVisibilityToggle && isHidden) - throw Error("Not yet implemented."); - appendChildNode(parent.node, instance.node); - } else if (4 !== node.tag) - if (22 === node.tag && null !== node.memoizedState) - (instance = node.child), - null !== instance && (instance.return = node), - appendAllChildren(parent, node, !0, !0); - else if (null !== node.child) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === workInProgress) return; - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } -} -function appendAllChildrenToContainer( - containerChildSet, - workInProgress, - needsVisibilityToggle, - isHidden -) { - for (var node = workInProgress.child; null !== node; ) { - if (5 === node.tag) { - var instance = node.stateNode; - needsVisibilityToggle && - isHidden && - (instance = cloneHiddenInstance(instance)); - appendChildNodeToSet(containerChildSet, instance.node); - } else if (6 === node.tag) { - instance = node.stateNode; - if (needsVisibilityToggle && isHidden) - throw Error("Not yet implemented."); - appendChildNodeToSet(containerChildSet, instance.node); - } else if (4 !== node.tag) - if (22 === node.tag && null !== node.memoizedState) - (instance = node.child), - null !== instance && (instance.return = node), - appendAllChildrenToContainer( - containerChildSet, - node, - !( - null !== node.memoizedProps && - "manual" === node.memoizedProps.mode - ), - !0 - ); - else if (null !== node.child) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === workInProgress) return; - node = node.return; + didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; } - node.sibling.return = node.return; - node = node.sibling; - } -} -function updateHostContainer(current, workInProgress) { - if (doesRequireClone(current, workInProgress)) { - current = workInProgress.stateNode; - var container = current.containerInfo, - newChildSet = createChildNodeSet(); - appendAllChildrenToContainer(newChildSet, workInProgress, !1, !1); - current.pendingChildren = newChildSet; - workInProgress.flags |= 4; - completeRoot(container, newChildSet); - } -} -function scheduleRetryEffect(workInProgress, retryQueue) { - null !== retryQueue - ? (workInProgress.flags |= 4) - : workInProgress.flags & 16384 && - ((retryQueue = - 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), - (workInProgress.lanes |= retryQueue)); -} -function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - switch (renderState.tailMode) { - case "hidden": - hasRenderedATailFallback = renderState.tail; - for (var lastTailNode = null; null !== hasRenderedATailFallback; ) - null !== hasRenderedATailFallback.alternate && - (lastTailNode = hasRenderedATailFallback), - (hasRenderedATailFallback = hasRenderedATailFallback.sibling); - null === lastTailNode - ? (renderState.tail = null) - : (lastTailNode.sibling = null); - break; - case "collapsed": - lastTailNode = renderState.tail; - for (var lastTailNode$61 = null; null !== lastTailNode; ) - null !== lastTailNode.alternate && (lastTailNode$61 = lastTailNode), - (lastTailNode = lastTailNode.sibling); - null === lastTailNode$61 - ? hasRenderedATailFallback || null === renderState.tail - ? (renderState.tail = null) - : (renderState.tail.sibling = null) - : (lastTailNode$61.sibling = null); - } -} -function bubbleProperties(completedWork) { - var didBailout = - null !== completedWork.alternate && - completedWork.alternate.child === completedWork.child, - newChildLanes = 0, - subtreeFlags = 0; - if (didBailout) - for (var child$62 = completedWork.child; null !== child$62; ) - (newChildLanes |= child$62.lanes | child$62.childLanes), - (subtreeFlags |= child$62.subtreeFlags & 31457280), - (subtreeFlags |= child$62.flags & 31457280), - (child$62.return = completedWork), - (child$62 = child$62.sibling); - else - for (child$62 = completedWork.child; null !== child$62; ) - (newChildLanes |= child$62.lanes | child$62.childLanes), - (subtreeFlags |= child$62.subtreeFlags), - (subtreeFlags |= child$62.flags), - (child$62.return = completedWork), - (child$62 = child$62.sibling); - completedWork.subtreeFlags |= subtreeFlags; - completedWork.childLanes = newChildLanes; - return didBailout; -} -function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; + else didReceiveUpdate = !1; + workInProgress.lanes = 0; switch (workInProgress.tag) { case 2: + var Component = workInProgress.type; + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + prepareToReadContext(workInProgress, renderLanes); + var value = renderWithHooks( + null, + workInProgress, + Component, + current, + void 0, + renderLanes + ); + workInProgress.flags |= 1; + "object" === typeof value && + null !== value && + "function" === typeof value.render && + void 0 === value.$$typeof + ? ((workInProgress.tag = 1), + (workInProgress.memoizedState = null), + (workInProgress.updateQueue = null), + (workInProgress.memoizedState = + null !== value.state && void 0 !== value.state + ? value.state + : null), + initializeUpdateQueue(workInProgress), + (value.updater = classComponentUpdater), + (workInProgress.stateNode = value), + (value._reactInternals = workInProgress), + mountClassInstance(workInProgress, Component, current, renderLanes), + (workInProgress = finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ))) + : ((workInProgress.tag = 0), + reconcileChildren(null, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 16: - case 15: + Component = workInProgress.elementType; + a: { + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + value = Component._init; + Component = value(Component._payload); + workInProgress.type = Component; + value = workInProgress.tag = resolveLazyComponentTag(Component); + current = resolveDefaultProps(Component, current); + switch (value) { + case 0: + workInProgress = updateFunctionComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 1: + workInProgress = updateClassComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 11: + workInProgress = updateForwardRef( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 14: + workInProgress = updateMemoComponent( + null, + workInProgress, + Component, + resolveDefaultProps(Component.type, current), + renderLanes + ); + break a; + } + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + ); + } + return workInProgress; case 0: - case 11: - case 7: - case 8: - case 12: - case 9: - case 14: - return bubbleProperties(workInProgress), null; + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateFunctionComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) + ); case 1: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateClassComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); case 3: - return ( - (newProps = workInProgress.stateNode), - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)), - (null !== current && null !== current.child) || - null === current || - (current.memoizedState.isDehydrated && - 0 === (workInProgress.flags & 256)) || - ((workInProgress.flags |= 1024), - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), - (hydrationErrors = null))), - updateHostContainer(current, workInProgress), - bubbleProperties(workInProgress), - null - ); + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + if (null === current) + throw Error("Should have a current fiber. This is a bug in React."); + value = workInProgress.pendingProps; + Component = workInProgress.memoizedState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, value, null, renderLanes); + value = workInProgress.memoizedState.element; + value === Component + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + )) + : (reconcileChildren(current, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 26: case 27: case 5: - popHostContext(workInProgress); - renderLanes = workInProgress.type; - if (null !== current && null != workInProgress.stateNode) { - renderLanes = current.stateNode; - var oldProps = current.memoizedProps, - requiresClone = doesRequireClone(current, workInProgress); - if (requiresClone || oldProps !== newProps) { - b: { - oldProps = diffProperties( - null, - oldProps, - newProps, - renderLanes.canonical.viewConfig.validAttributes - ); - renderLanes.canonical.currentProps = newProps; - newProps = renderLanes.node; - if (requiresClone) - newProps = - null !== oldProps - ? cloneNodeWithNewChildrenAndProps(newProps, oldProps) - : cloneNodeWithNewChildren(newProps); - else if (null !== oldProps) - newProps = cloneNodeWithNewProps(newProps, oldProps); - else { - newProps = renderLanes; - break b; - } - newProps = { node: newProps, canonical: renderLanes.canonical }; - } - newProps === renderLanes - ? (workInProgress.stateNode = renderLanes) - : ((workInProgress.stateNode = newProps), - requiresClone - ? appendAllChildren(newProps, workInProgress, !1, !1) - : (workInProgress.flags |= 4)); - } else workInProgress.stateNode = renderLanes; - current.ref !== workInProgress.ref && (workInProgress.flags |= 2097664); - } else { - if (!newProps) { - if (null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - bubbleProperties(workInProgress); - return null; - } - requiresClone = rootInstanceStackCursor.current; - current = nextReactTag; - nextReactTag += 2; - renderLanes = getViewConfigForType(renderLanes); - oldProps = diffProperties( - null, - emptyObject, - newProps, - renderLanes.validAttributes - ); - requiresClone = createNode( - current, - renderLanes.uiViewClassName, - requiresClone, - oldProps, - workInProgress - ); - oldProps = ReactNativePrivateInterface.createPublicInstance( - current, - renderLanes, - workInProgress - ); - current = { - node: requiresClone, - canonical: { - nativeTag: current, - viewConfig: renderLanes, - currentProps: newProps, - internalInstanceHandle: workInProgress, - publicInstance: oldProps - } - }; - appendAllChildren(current, workInProgress, !1, !1); - workInProgress.stateNode = current; - null !== workInProgress.ref && (workInProgress.flags |= 2097664); - } - bubbleProperties(workInProgress); - workInProgress.flags &= -16777217; - return null; + return ( + pushHostContext(workInProgress), + (Component = workInProgress.pendingProps.children), + markRef(current, workInProgress), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); case 6: - if (current && null != workInProgress.stateNode) - current.memoizedProps !== newProps - ? ((workInProgress.stateNode = createTextInstance( - newProps, - rootInstanceStackCursor.current, - contextStackCursor.current, - workInProgress - )), - (workInProgress.flags |= 4)) - : (workInProgress.stateNode = current.stateNode); - else { - if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgress.stateNode = createTextInstance( - newProps, - rootInstanceStackCursor.current, - contextStackCursor.current, - workInProgress - ); - } - bubbleProperties(workInProgress); return null; case 13: - popSuspenseHandler(workInProgress); - newProps = workInProgress.memoizedState; - if ( - null === current || - (null !== current.memoizedState && - null !== current.memoizedState.dehydrated) - ) { - if (null !== newProps && null !== newProps.dehydrated) { - if (null === current) { - throw Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ); - throw Error( - "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ); - } - 0 === (workInProgress.flags & 128) && - (workInProgress.memoizedState = null); - workInProgress.flags |= 4; - bubbleProperties(workInProgress); - requiresClone = !1; - } else - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), - (requiresClone = !0); - if (!requiresClone) - return workInProgress.flags & 256 ? workInProgress : null; - } - if (0 !== (workInProgress.flags & 128)) - return (workInProgress.lanes = renderLanes), workInProgress; - newProps = null !== newProps; - newProps !== (null !== current && null !== current.memoizedState) && - newProps && - (workInProgress.child.flags |= 8192); - scheduleRetryEffect(workInProgress, workInProgress.updateQueue); - bubbleProperties(workInProgress); - return null; + return updateSuspenseComponent(current, workInProgress, renderLanes); case 4: return ( - popHostContainer(), - updateHostContainer(current, workInProgress), - bubbleProperties(workInProgress), - null + pushHostContainer( + workInProgress, + workInProgress.stateNode.containerInfo + ), + (Component = workInProgress.pendingProps), + null === current + ? (workInProgress.child = reconcileChildFibers( + workInProgress, + null, + Component, + renderLanes + )) + : reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 10: + case 11: return ( - popProvider(workInProgress.type._context), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateForwardRef(current, workInProgress, Component, value, renderLanes) ); - case 17: + case 7: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps, + renderLanes + ), + workInProgress.child ); - case 19: - pop(suspenseStackCursor); - requiresClone = workInProgress.memoizedState; - if (null === requiresClone) return bubbleProperties(workInProgress), null; - newProps = 0 !== (workInProgress.flags & 128); - oldProps = requiresClone.rendering; - if (null === oldProps) - if (newProps) cutOffTailIfNeeded(requiresClone, !1); - else { - if ( - 0 !== workInProgressRootExitStatus || - (null !== current && 0 !== (current.flags & 128)) - ) - for (current = workInProgress.child; null !== current; ) { - oldProps = findFirstSuspended(current); - if (null !== oldProps) { - workInProgress.flags |= 128; - cutOffTailIfNeeded(requiresClone, !1); - current = oldProps.updateQueue; - workInProgress.updateQueue = current; - scheduleRetryEffect(workInProgress, current); - workInProgress.subtreeFlags = 0; - current = renderLanes; - for (newProps = workInProgress.child; null !== newProps; ) - resetWorkInProgress(newProps, current), - (newProps = newProps.sibling); - push( - suspenseStackCursor, - (suspenseStackCursor.current & 1) | 2 - ); - return workInProgress.child; - } - current = current.sibling; + case 8: + return ( + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child + ); + case 12: + return ( + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child + ); + case 10: + a: { + Component = workInProgress.type._context; + value = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps, + newValue = value.value; + push(valueCursor, Component._currentValue2); + Component._currentValue2 = newValue; + if (null !== oldProps) + if (objectIs(oldProps.value, newValue)) { + if (oldProps.children === value.children) { + workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + ); + break a; } - null !== requiresClone.tail && - now() > workInProgressRootRenderTargetTime && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(requiresClone, !1), - (workInProgress.lanes = 4194304)); - } - else { - if (!newProps) - if (((current = findFirstSuspended(oldProps)), null !== current)) { - if ( - ((workInProgress.flags |= 128), - (newProps = !0), - (current = current.updateQueue), - (workInProgress.updateQueue = current), - scheduleRetryEffect(workInProgress, current), - cutOffTailIfNeeded(requiresClone, !0), - null === requiresClone.tail && - "hidden" === requiresClone.tailMode && - !oldProps.alternate) - ) - return bubbleProperties(workInProgress), null; } else - 2 * now() - requiresClone.renderingStartTime > - workInProgressRootRenderTargetTime && - 536870912 !== renderLanes && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(requiresClone, !1), - (workInProgress.lanes = 4194304)); - requiresClone.isBackwards - ? ((oldProps.sibling = workInProgress.child), - (workInProgress.child = oldProps)) - : ((current = requiresClone.last), - null !== current - ? (current.sibling = oldProps) - : (workInProgress.child = oldProps), - (requiresClone.last = oldProps)); + for ( + oldProps = workInProgress.child, + null !== oldProps && (oldProps.return = workInProgress); + null !== oldProps; + + ) { + var list = oldProps.dependencies; + if (null !== list) { + newValue = oldProps.child; + for ( + var dependency = list.firstContext; + null !== dependency; + + ) { + if (dependency.context === Component) { + if (1 === oldProps.tag) { + dependency = createUpdate(renderLanes & -renderLanes); + dependency.tag = 2; + var updateQueue = oldProps.updateQueue; + if (null !== updateQueue) { + updateQueue = updateQueue.shared; + var pending = updateQueue.pending; + null === pending + ? (dependency.next = dependency) + : ((dependency.next = pending.next), + (pending.next = dependency)); + updateQueue.pending = dependency; + } + } + oldProps.lanes |= renderLanes; + dependency = oldProps.alternate; + null !== dependency && (dependency.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + oldProps.return, + renderLanes, + workInProgress + ); + list.lanes |= renderLanes; + break; + } + dependency = dependency.next; + } + } else if (10 === oldProps.tag) + newValue = + oldProps.type === workInProgress.type ? null : oldProps.child; + else if (18 === oldProps.tag) { + newValue = oldProps.return; + if (null === newValue) + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + newValue.lanes |= renderLanes; + list = newValue.alternate; + null !== list && (list.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + newValue, + renderLanes, + workInProgress + ); + newValue = oldProps.sibling; + } else newValue = oldProps.child; + if (null !== newValue) newValue.return = oldProps; + else + for (newValue = oldProps; null !== newValue; ) { + if (newValue === workInProgress) { + newValue = null; + break; + } + oldProps = newValue.sibling; + if (null !== oldProps) { + oldProps.return = newValue.return; + newValue = oldProps; + break; + } + newValue = newValue.return; + } + oldProps = newValue; + } + reconcileChildren(current, workInProgress, value.children, renderLanes); + workInProgress = workInProgress.child; } - if (null !== requiresClone.tail) - return ( - (workInProgress = requiresClone.tail), - (requiresClone.rendering = workInProgress), - (requiresClone.tail = workInProgress.sibling), - (requiresClone.renderingStartTime = now()), - (workInProgress.sibling = null), - (current = suspenseStackCursor.current), - push(suspenseStackCursor, newProps ? (current & 1) | 2 : current & 1), - workInProgress - ); - bubbleProperties(workInProgress); - return null; - case 22: - case 23: + return workInProgress; + case 9: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (newProps = null !== workInProgress.memoizedState), - null !== current - ? (null !== current.memoizedState) !== newProps && - (workInProgress.flags |= 8192) - : newProps && (workInProgress.flags |= 8192), - newProps && 0 !== (workInProgress.mode & 1) - ? 0 !== (renderLanes & 536870912) && - 0 === (workInProgress.flags & 128) && - (bubbleProperties(workInProgress), - workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) - : bubbleProperties(workInProgress), - (current = workInProgress.updateQueue), - null !== current && - scheduleRetryEffect(workInProgress, current.retryQueue), - null + (value = workInProgress.type), + (Component = workInProgress.pendingProps.children), + prepareToReadContext(workInProgress, renderLanes), + (value = readContext(value)), + (Component = Component(value)), + (workInProgress.flags |= 1), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 24: - return null; - case 25: - return null; - } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -} -function unwindWork(current, workInProgress) { - switch (workInProgress.tag) { - case 1: + case 14: return ( - isContextProvider(workInProgress.type) && popContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + (Component = workInProgress.type), + (value = resolveDefaultProps(Component, workInProgress.pendingProps)), + (value = resolveDefaultProps(Component.type, value)), + updateMemoComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); - case 3: - return ( - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - (current = workInProgress.flags), - 0 !== (current & 65536) && 0 === (current & 128) - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + case 15: + return updateSimpleMemoComponent( + current, + workInProgress, + workInProgress.type, + workInProgress.pendingProps, + renderLanes ); - case 26: - case 27: - case 5: - return popHostContext(workInProgress), null; - case 13: - popSuspenseHandler(workInProgress); - current = workInProgress.memoizedState; - if ( - null !== current && - null !== current.dehydrated && - null === workInProgress.alternate - ) - throw Error( - "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." - ); - current = workInProgress.flags; - return current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null; - case 19: - return pop(suspenseStackCursor), null; - case 4: - return popHostContainer(), null; - case 10: - return popProvider(workInProgress.type._context), null; - case 22: - case 23: + case 17: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), + (workInProgress.tag = 1), + prepareToReadContext(workInProgress, renderLanes), + constructClassInstance(workInProgress, Component, value), + mountClassInstance(workInProgress, Component, value, renderLanes), + finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ) ); - case 24: - return null; - case 25: - return null; - default: - return null; - } -} -function unwindInterruptedWork(current, interruptedWork) { - switch (interruptedWork.tag) { - case 1: - current = interruptedWork.type.childContextTypes; - null !== current && void 0 !== current && popContext(); - break; - case 3: - popHostContainer(); - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); - break; - case 26: - case 27: - case 5: - popHostContext(interruptedWork); - break; - case 4: - popHostContainer(); - break; - case 13: - popSuspenseHandler(interruptedWork); - break; case 19: - pop(suspenseStackCursor); - break; - case 10: - popProvider(interruptedWork.type._context); - break; + return updateSuspenseListComponent(current, workInProgress, renderLanes); case 22: - case 23: - popSuspenseHandler(interruptedWork), popHiddenContext(); + return updateOffscreenComponent(current, workInProgress, renderLanes); } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); } -var offscreenSubtreeIsHidden = !1, - offscreenSubtreeWasHidden = !1, - PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, - nextEffect = null; -function safelyAttachRef(current, nearestMountedAncestor) { - try { - var ref = current.ref; - if (null !== ref) { - var instance = current.stateNode; - switch (current.tag) { - case 26: - case 27: - case 5: - var instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - "function" === typeof ref - ? (current.refCleanup = ref(instanceToUse)) - : (ref.current = instanceToUse); - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } +var valueCursor = createCursor(null), + currentlyRenderingFiber = null, + lastContextDependency = null, + lastFullyObservedContext = null; +function resetContextDependencies() { + lastFullyObservedContext = + lastContextDependency = + currentlyRenderingFiber = + null; } -function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref, - refCleanup = current.refCleanup; - if (null !== ref) - if ("function" === typeof refCleanup) - try { - refCleanup(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } finally { - (current.refCleanup = null), - (current = current.alternate), - null != current && (current.refCleanup = null); - } - else if ("function" === typeof ref) - try { - ref(null); - } catch (error$77) { - captureCommitPhaseError(current, nearestMountedAncestor, error$77); - } - else ref.current = null; +function popProvider(context) { + context._currentValue2 = valueCursor.current; + pop(valueCursor); } -function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); +function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + for (; null !== parent; ) { + var alternate = parent.alternate; + (parent.childLanes & renderLanes) !== renderLanes + ? ((parent.childLanes |= renderLanes), + null !== alternate && (alternate.childLanes |= renderLanes)) + : null !== alternate && + (alternate.childLanes & renderLanes) !== renderLanes && + (alternate.childLanes |= renderLanes); + if (parent === propagationRoot) break; + parent = parent.return; } } -var shouldFireAfterActiveInstanceBlur = !1; -function commitBeforeMutationEffects(root, firstChild) { - for (nextEffect = firstChild; null !== nextEffect; ) - if ( - ((root = nextEffect), - (firstChild = root.child), - 0 !== (root.subtreeFlags & 1028) && null !== firstChild) - ) - (firstChild.return = root), (nextEffect = firstChild); - else - for (; null !== nextEffect; ) { - root = nextEffect; - try { - var current = root.alternate, - flags = root.flags; - switch (root.tag) { - case 0: - break; - case 11: - case 15: - break; - case 1: - if (0 !== (flags & 1024) && null !== current) { - var prevProps = current.memoizedProps, - prevState = current.memoizedState, - instance = root.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - root.elementType === root.type - ? prevProps - : resolveDefaultProps(root.type, prevProps), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - break; - case 5: - case 26: - case 27: - case 6: - case 4: - case 17: - break; - default: - if (0 !== (flags & 1024)) - throw Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ); - } - } catch (error) { - captureCommitPhaseError(root, root.return, error); - } - firstChild = root.sibling; - if (null !== firstChild) { - firstChild.return = root.return; - nextEffect = firstChild; - break; - } - nextEffect = root.return; - } - current = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = !1; - return current; +function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastFullyObservedContext = lastContextDependency = null; + workInProgress = workInProgress.dependencies; + null !== workInProgress && + null !== workInProgress.firstContext && + (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), + (workInProgress.firstContext = null)); } -function commitHookEffectListUnmount( - flags, - finishedWork, - nearestMountedAncestor -) { - var updateQueue = finishedWork.updateQueue; - updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; - if (null !== updateQueue) { - var effect = (updateQueue = updateQueue.next); - do { - if ((effect.tag & flags) === flags) { - var inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - ((inst.destroy = void 0), - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); - } - effect = effect.next; - } while (effect !== updateQueue); - } +function readContext(context) { + return readContextForConsumer(currentlyRenderingFiber, context); } -function commitHookEffectListMount(flags, finishedWork) { - finishedWork = finishedWork.updateQueue; - finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; - if (null !== finishedWork) { - var effect = (finishedWork = finishedWork.next); - do { - if ((effect.tag & flags) === flags) { - var create$78 = effect.create, - inst = effect.inst; - create$78 = create$78(); - inst.destroy = create$78; - } - effect = effect.next; - } while (effect !== finishedWork); - } +function readContextDuringReconciliation(consumer, context, renderLanes) { + null === currentlyRenderingFiber && + prepareToReadContext(consumer, renderLanes); + return readContextForConsumer(consumer, context); } -function commitHookLayoutEffects(finishedWork, hookFlags) { - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function readContextForConsumer(consumer, context) { + var value = context._currentValue2; + if (lastFullyObservedContext !== context) + if ( + ((context = { context: context, memoizedValue: value, next: null }), + null === lastContextDependency) + ) { + if (null === consumer) + throw Error( + "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." + ); + lastContextDependency = context; + consumer.dependencies = { lanes: 0, firstContext: context }; + } else lastContextDependency = lastContextDependency.next = context; + return value; } -function commitClassCallbacks(finishedWork) { - var updateQueue = finishedWork.updateQueue; - if (null !== updateQueue) { - var instance = finishedWork.stateNode; - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; +function handleAsyncAction() {} +function doesRequireClone(current, completedWork) { + if (null !== current && current.child === completedWork.child) return !1; + if (0 !== (completedWork.flags & 16)) return !0; + for (current = completedWork.child; null !== current; ) { + if (0 !== (current.flags & 12854) || 0 !== (current.subtreeFlags & 12854)) + return !0; + current = current.sibling; } + return !1; } -function commitHostComponentMount(finishedWork) { - try { - throw Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); +function appendAllChildren( + parent, + workInProgress, + needsVisibilityToggle, + isHidden +) { + for (var node = workInProgress.child; null !== node; ) { + if (5 === node.tag) { + var instance = node.stateNode; + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance(instance)); + appendChildNode(parent.node, instance.node); + } else if (6 === node.tag) { + instance = node.stateNode; + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); + appendChildNode(parent.node, instance.node); + } else if (4 !== node.tag) + if (22 === node.tag && null !== node.memoizedState) + (instance = node.child), + null !== instance && (instance.return = node), + appendAllChildren(parent, node, !0, !0); + else if (null !== node.child) { + node.child.return = node; + node = node.child; + continue; + } + if (node === workInProgress) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; } } -function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { - var flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitHookLayoutEffects(finishedWork, 5); - break; - case 1: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 4) - if (((finishedRoot = finishedWork.stateNode), null === current)) - try { - finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current.memoizedProps - : resolveDefaultProps(finishedWork.type, current.memoizedProps); - current = current.memoizedState; - try { - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$79) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$79 - ); - } - } - flags & 64 && commitClassCallbacks(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; - case 3: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { - finishedRoot = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 27: - case 5: - finishedRoot = getPublicInstance(finishedWork.child.stateNode); - break; - case 1: - finishedRoot = finishedWork.child.stateNode; - } - try { - commitCallbacks(flags, finishedRoot); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function appendAllChildrenToContainer( + containerChildSet, + workInProgress, + needsVisibilityToggle, + isHidden +) { + for (var node = workInProgress.child; null !== node; ) { + if (5 === node.tag) { + var instance = node.stateNode; + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance(instance)); + appendChildNodeToSet(containerChildSet, instance.node); + } else if (6 === node.tag) { + instance = node.stateNode; + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); + appendChildNodeToSet(containerChildSet, instance.node); + } else if (4 !== node.tag) + if (22 === node.tag && null !== node.memoizedState) + (instance = node.child), + null !== instance && (instance.return = node), + appendAllChildrenToContainer( + containerChildSet, + node, + !( + null !== node.memoizedProps && + "manual" === node.memoizedProps.mode + ), + !0 + ); + else if (null !== node.child) { + node.child.return = node; + node = node.child; + continue; } - break; - case 26: - case 27: - case 5: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - null === current && flags & 4 && commitHostComponentMount(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 13: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 22: - if (0 !== (finishedWork.mode & 1)) { - if ( - ((prevProps = - null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), - !prevProps) - ) { - current = - (null !== current && null !== current.memoizedState) || - offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevProps; - (offscreenSubtreeWasHidden = current) && - !prevOffscreenSubtreeWasHidden - ? recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - 0 !== (finishedWork.subtreeFlags & 8772) - ) - : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } - } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && - ("manual" === finishedWork.memoizedProps.mode - ? safelyAttachRef(finishedWork, finishedWork.return) - : safelyDetachRef(finishedWork, finishedWork.return)); - break; - default: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (node === workInProgress) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; } } -function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - null !== alternate && - ((fiber.alternate = null), detachFiberAfterEffects(alternate)); - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - fiber.stateNode = null; - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - fiber.updateQueue = null; +function updateHostContainer(current, workInProgress) { + if (doesRequireClone(current, workInProgress)) { + current = workInProgress.stateNode; + var container = current.containerInfo, + newChildSet = createChildNodeSet(); + appendAllChildrenToContainer(newChildSet, workInProgress, !1, !1); + current.pendingChildren = newChildSet; + workInProgress.flags |= 4; + completeRoot(container, newChildSet); + } } -function recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - parent -) { - for (parent = parent.child; null !== parent; ) - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), - (parent = parent.sibling); +function scheduleRetryEffect(workInProgress, retryQueue) { + null !== retryQueue + ? (workInProgress.flags |= 4) + : workInProgress.flags & 16384 && + ((retryQueue = + 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), + (workInProgress.lanes |= retryQueue)); } -function commitDeletionEffectsOnFiber( - finishedRoot, - nearestMountedAncestor, - deletedFiber -) { - if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) - try { - injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); - } catch (err) {} - switch (deletedFiber.tag) { - case 26: - case 27: - case 5: - offscreenSubtreeWasHidden || - safelyDetachRef(deletedFiber, nearestMountedAncestor); - case 6: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 18: - break; - case 4: - createChildNodeSet(); - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); +function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + switch (renderState.tailMode) { + case "hidden": + hasRenderedATailFallback = renderState.tail; + for (var lastTailNode = null; null !== hasRenderedATailFallback; ) + null !== hasRenderedATailFallback.alternate && + (lastTailNode = hasRenderedATailFallback), + (hasRenderedATailFallback = hasRenderedATailFallback.sibling); + null === lastTailNode + ? (renderState.tail = null) + : (lastTailNode.sibling = null); break; + case "collapsed": + lastTailNode = renderState.tail; + for (var lastTailNode$61 = null; null !== lastTailNode; ) + null !== lastTailNode.alternate && (lastTailNode$61 = lastTailNode), + (lastTailNode = lastTailNode.sibling); + null === lastTailNode$61 + ? hasRenderedATailFallback || null === renderState.tail + ? (renderState.tail = null) + : (renderState.tail.sibling = null) + : (lastTailNode$61.sibling = null); + } +} +function bubbleProperties(completedWork) { + var didBailout = + null !== completedWork.alternate && + completedWork.alternate.child === completedWork.child, + newChildLanes = 0, + subtreeFlags = 0; + if (didBailout) + for (var child$62 = completedWork.child; null !== child$62; ) + (newChildLanes |= child$62.lanes | child$62.childLanes), + (subtreeFlags |= child$62.subtreeFlags & 31457280), + (subtreeFlags |= child$62.flags & 31457280), + (child$62.return = completedWork), + (child$62 = child$62.sibling); + else + for (child$62 = completedWork.child; null !== child$62; ) + (newChildLanes |= child$62.lanes | child$62.childLanes), + (subtreeFlags |= child$62.subtreeFlags), + (subtreeFlags |= child$62.flags), + (child$62.return = completedWork), + (child$62 = child$62.sibling); + completedWork.subtreeFlags |= subtreeFlags; + completedWork.childLanes = newChildLanes; + return didBailout; +} +function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; + switch (workInProgress.tag) { + case 2: + case 16: + case 15: case 0: case 11: - case 14: - case 15: - if (!offscreenSubtreeWasHidden) { - var updateQueue = deletedFiber.updateQueue; + case 7: + case 8: + case 12: + case 9: + case 14: + return bubbleProperties(workInProgress), null; + case 1: + return bubbleProperties(workInProgress), null; + case 3: + return ( + (newProps = workInProgress.stateNode), + popHostContainer(), + newProps.pendingContext && + ((newProps.context = newProps.pendingContext), + (newProps.pendingContext = null)), + (null !== current && null !== current.child) || + null === current || + (current.memoizedState.isDehydrated && + 0 === (workInProgress.flags & 256)) || + ((workInProgress.flags |= 1024), + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), + (hydrationErrors = null))), + updateHostContainer(current, workInProgress), + bubbleProperties(workInProgress), + null + ); + case 26: + case 27: + case 5: + popHostContext(workInProgress); + renderLanes = workInProgress.type; + if (null !== current && null != workInProgress.stateNode) { + renderLanes = current.stateNode; + var oldProps = current.memoizedProps; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + (current = doesRequireClone(current, workInProgress)) || + oldProps !== newProps ) { - var effect = (updateQueue = updateQueue.next); - do { - var tag = effect.tag, - inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - (0 !== (tag & 2) - ? ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )) - : 0 !== (tag & 4) && - ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - ))); - effect = effect.next; - } while (effect !== updateQueue); + b: { + oldProps = diffProperties( + null, + oldProps, + newProps, + renderLanes.canonical.viewConfig.validAttributes + ); + renderLanes.canonical.currentProps = newProps; + newProps = renderLanes.node; + if (current) + newProps = + null !== oldProps + ? cloneNodeWithNewChildrenAndProps(newProps, oldProps) + : cloneNodeWithNewChildren(newProps); + else if (null !== oldProps) + newProps = cloneNodeWithNewProps(newProps, oldProps); + else { + newProps = renderLanes; + break b; + } + newProps = { node: newProps, canonical: renderLanes.canonical }; + } + newProps === renderLanes + ? (workInProgress.stateNode = renderLanes) + : ((workInProgress.stateNode = newProps), + current + ? appendAllChildren(newProps, workInProgress, !1, !1) + : (workInProgress.flags |= 4)); + } else workInProgress.stateNode = renderLanes; + } else { + if (!newProps) { + if (null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + bubbleProperties(workInProgress); + return null; } + oldProps = rootInstanceStackCursor.current; + current = nextReactTag; + nextReactTag += 2; + renderLanes = getViewConfigForType(renderLanes); + var updatePayload = diffProperties( + null, + emptyObject, + newProps, + renderLanes.validAttributes + ); + oldProps = createNode( + current, + renderLanes.uiViewClassName, + oldProps, + updatePayload, + workInProgress + ); + updatePayload = ReactNativePrivateInterface.createPublicInstance( + current, + renderLanes, + workInProgress + ); + current = { + node: oldProps, + canonical: { + nativeTag: current, + viewConfig: renderLanes, + currentProps: newProps, + internalInstanceHandle: workInProgress, + publicInstance: updatePayload + } + }; + appendAllChildren(current, workInProgress, !1, !1); + workInProgress.stateNode = current; } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 1: + bubbleProperties(workInProgress); + workInProgress.flags &= -16777217; + return null; + case 6: + if (current && null != workInProgress.stateNode) + current.memoizedProps !== newProps + ? ((workInProgress.stateNode = createTextInstance( + newProps, + rootInstanceStackCursor.current, + contextStackCursor.current, + workInProgress + )), + (workInProgress.flags |= 4)) + : (workInProgress.stateNode = current.stateNode); + else { + if ("string" !== typeof newProps && null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgress.stateNode = createTextInstance( + newProps, + rootInstanceStackCursor.current, + contextStackCursor.current, + workInProgress + ); + } + bubbleProperties(workInProgress); + return null; + case 13: + newProps = workInProgress.memoizedState; if ( - !offscreenSubtreeWasHidden && - (safelyDetachRef(deletedFiber, nearestMountedAncestor), - (updateQueue = deletedFiber.stateNode), - "function" === typeof updateQueue.componentWillUnmount) - ) - try { - (updateQueue.props = deletedFiber.memoizedProps), - (updateQueue.state = deletedFiber.memoizedState), - updateQueue.componentWillUnmount(); - } catch (error) { - captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + null === current || + (null !== current.memoizedState && + null !== current.memoizedState.dehydrated) + ) { + if (null !== newProps && null !== newProps.dehydrated) { + if (null === current) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + 0 === (workInProgress.flags & 128) && + (workInProgress.memoizedState = null); + workInProgress.flags |= 4; + bubbleProperties(workInProgress); + oldProps = !1; + } else + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), + (oldProps = !0); + if (!oldProps) { + if (workInProgress.flags & 256) + return popSuspenseHandler(workInProgress), workInProgress; + popSuspenseHandler(workInProgress); + return null; } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 21: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber + } + popSuspenseHandler(workInProgress); + if (0 !== (workInProgress.flags & 128)) + return (workInProgress.lanes = renderLanes), workInProgress; + newProps = null !== newProps; + newProps !== (null !== current && null !== current.memoizedState) && + newProps && + (workInProgress.child.flags |= 8192); + scheduleRetryEffect(workInProgress, workInProgress.updateQueue); + bubbleProperties(workInProgress); + return null; + case 4: + return ( + popHostContainer(), + updateHostContainer(current, workInProgress), + bubbleProperties(workInProgress), + null ); - break; - case 22: - safelyDetachRef(deletedFiber, nearestMountedAncestor); - deletedFiber.mode & 1 - ? ((offscreenSubtreeWasHidden = - (updateQueue = offscreenSubtreeWasHidden) || - null !== deletedFiber.memoizedState), - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ), - (offscreenSubtreeWasHidden = updateQueue)) - : recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - default: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber + case 10: + return ( + popProvider(workInProgress.type._context), + bubbleProperties(workInProgress), + null ); - } -} -function getRetryCache(finishedWork) { - switch (finishedWork.tag) { - case 13: + case 17: + return bubbleProperties(workInProgress), null; case 19: - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); - return retryCache; + pop(suspenseStackCursor); + oldProps = workInProgress.memoizedState; + if (null === oldProps) return bubbleProperties(workInProgress), null; + newProps = 0 !== (workInProgress.flags & 128); + updatePayload = oldProps.rendering; + if (null === updatePayload) + if (newProps) cutOffTailIfNeeded(oldProps, !1); + else { + if ( + 0 !== workInProgressRootExitStatus || + (null !== current && 0 !== (current.flags & 128)) + ) + for (current = workInProgress.child; null !== current; ) { + updatePayload = findFirstSuspended(current); + if (null !== updatePayload) { + workInProgress.flags |= 128; + cutOffTailIfNeeded(oldProps, !1); + current = updatePayload.updateQueue; + workInProgress.updateQueue = current; + scheduleRetryEffect(workInProgress, current); + workInProgress.subtreeFlags = 0; + current = renderLanes; + for (newProps = workInProgress.child; null !== newProps; ) + resetWorkInProgress(newProps, current), + (newProps = newProps.sibling); + push( + suspenseStackCursor, + (suspenseStackCursor.current & 1) | 2 + ); + return workInProgress.child; + } + current = current.sibling; + } + null !== oldProps.tail && + now() > workInProgressRootRenderTargetTime && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(oldProps, !1), + (workInProgress.lanes = 4194304)); + } + else { + if (!newProps) + if ( + ((current = findFirstSuspended(updatePayload)), null !== current) + ) { + if ( + ((workInProgress.flags |= 128), + (newProps = !0), + (current = current.updateQueue), + (workInProgress.updateQueue = current), + scheduleRetryEffect(workInProgress, current), + cutOffTailIfNeeded(oldProps, !0), + null === oldProps.tail && + "hidden" === oldProps.tailMode && + !updatePayload.alternate) + ) + return bubbleProperties(workInProgress), null; + } else + 2 * now() - oldProps.renderingStartTime > + workInProgressRootRenderTargetTime && + 536870912 !== renderLanes && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(oldProps, !1), + (workInProgress.lanes = 4194304)); + oldProps.isBackwards + ? ((updatePayload.sibling = workInProgress.child), + (workInProgress.child = updatePayload)) + : ((current = oldProps.last), + null !== current + ? (current.sibling = updatePayload) + : (workInProgress.child = updatePayload), + (oldProps.last = updatePayload)); + } + if (null !== oldProps.tail) + return ( + (workInProgress = oldProps.tail), + (oldProps.rendering = workInProgress), + (oldProps.tail = workInProgress.sibling), + (oldProps.renderingStartTime = now()), + (workInProgress.sibling = null), + (current = suspenseStackCursor.current), + push(suspenseStackCursor, newProps ? (current & 1) | 2 : current & 1), + workInProgress + ); + bubbleProperties(workInProgress); + return null; case 22: + case 23: return ( - (finishedWork = finishedWork.stateNode), - (retryCache = finishedWork._retryCache), - null === retryCache && - (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), - retryCache - ); - default: - throw Error( - "Unexpected Suspense handler tag (" + - finishedWork.tag + - "). This is a bug in React." + popSuspenseHandler(workInProgress), + popHiddenContext(), + (newProps = null !== workInProgress.memoizedState), + null !== current + ? (null !== current.memoizedState) !== newProps && + (workInProgress.flags |= 8192) + : newProps && (workInProgress.flags |= 8192), + newProps && 0 !== (workInProgress.mode & 1) + ? 0 !== (renderLanes & 536870912) && + 0 === (workInProgress.flags & 128) && + (bubbleProperties(workInProgress), + workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) + : bubbleProperties(workInProgress), + (current = workInProgress.updateQueue), + null !== current && + scheduleRetryEffect(workInProgress, current.retryQueue), + null ); + case 24: + return null; + case 25: + return null; } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); } -function attachSuspenseRetryListeners(finishedWork, wakeables) { - var retryCache = getRetryCache(finishedWork); - wakeables.forEach(function (wakeable) { - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - retryCache.has(wakeable) || - (retryCache.add(wakeable), wakeable.then(retry, retry)); - }); -} -function recursivelyTraverseMutationEffects(root, parentFiber) { - var deletions = parentFiber.deletions; - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - try { - commitDeletionEffectsOnFiber(root, parentFiber, childToDelete); - var alternate = childToDelete.alternate; - null !== alternate && (alternate.return = null); - childToDelete.return = null; - } catch (error) { - captureCommitPhaseError(childToDelete, parentFiber, error); - } - } - if (parentFiber.subtreeFlags & 12854) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitMutationEffectsOnFiber(parentFiber, root), - (parentFiber = parentFiber.sibling); -} -function commitMutationEffectsOnFiber(finishedWork, root) { - var current = finishedWork.alternate, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - try { - commitHookEffectListUnmount(3, finishedWork, finishedWork.return), - commitHookEffectListMount(3, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - try { - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$81) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$81); - } - } - break; +function unwindWork(current, workInProgress) { + switch (workInProgress.tag) { case 1: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - flags & 64 && - offscreenSubtreeIsHidden && - ((finishedWork = finishedWork.updateQueue), - null !== finishedWork && - ((flags = finishedWork.callbacks), - null !== flags && - ((current = finishedWork.shared.hiddenCallbacks), - (finishedWork.shared.hiddenCallbacks = - null === current ? flags : current.concat(flags))))); - break; + return ( + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); + case 3: + return ( + popHostContainer(), + (current = workInProgress.flags), + 0 !== (current & 65536) && 0 === (current & 128) + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); case 26: case 27: case 5: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && + return popHostContext(workInProgress), null; + case 13: + popSuspenseHandler(workInProgress); + current = workInProgress.memoizedState; + if ( null !== current && - safelyDetachRef(current, current.return); - break; - case 6: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - break; + null !== current.dehydrated && + null === workInProgress.alternate + ) + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + current = workInProgress.flags; + return current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null; + case 19: + return pop(suspenseStackCursor), null; + case 4: + return popHostContainer(), null; + case 10: + return popProvider(workInProgress.type._context), null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); + case 24: + return null; + case 25: + return null; + default: + return null; + } +} +function unwindInterruptedWork(current, interruptedWork) { + switch (interruptedWork.tag) { case 3: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); + break; + case 26: + case 27: + case 5: + popHostContext(interruptedWork); break; case 4: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); break; case 13: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - finishedWork.child.flags & 8192 && - ((current = null !== current && null !== current.memoizedState), - null === finishedWork.memoizedState || - current || - (globalMostRecentFallbackTime = now())); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); - break; - case 22: - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - var isHidden = null !== finishedWork.memoizedState, - wasHidden = null !== current && null !== current.memoizedState; - if (finishedWork.mode & 1) { - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; - recursivelyTraverseMutationEffects(root, finishedWork); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - } else recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - root = finishedWork.stateNode; - root._current = finishedWork; - root._visibility &= -3; - root._visibility |= root._pendingVisibility & 2; - flags & 8192 && - ((root._visibility = isHidden - ? root._visibility & -2 - : root._visibility | 1), - isHidden && - ((isHidden = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), - null === current || - wasHidden || - isHidden || - (0 !== (finishedWork.mode & 1) && - recursivelyTraverseDisappearLayoutEffects(finishedWork)))); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((current = flags.retryQueue), - null !== current && - ((flags.retryQueue = null), - attachSuspenseRetryListeners(finishedWork, current)))); + popSuspenseHandler(interruptedWork); break; case 19: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); + pop(suspenseStackCursor); break; - case 21: + case 10: + popProvider(interruptedWork.type._context); break; - default: - recursivelyTraverseMutationEffects(root, finishedWork), - commitReconciliationEffects(finishedWork); + case 22: + case 23: + popSuspenseHandler(interruptedWork), popHiddenContext(); } } -function commitReconciliationEffects(finishedWork) { - var flags = finishedWork.flags; - flags & 2 && (finishedWork.flags &= -3); - flags & 4096 && (finishedWork.flags &= -4097); -} -function recursivelyTraverseLayoutEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 8772) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), - (parentFiber = parentFiber.sibling); -} -function recursivelyTraverseDisappearLayoutEffects(parentFiber) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - commitHookEffectListUnmount(4, finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 1: - safelyDetachRef(finishedWork, finishedWork.return); - var instance = finishedWork.stateNode; - if ("function" === typeof instance.componentWillUnmount) { - var current = finishedWork, - nearestMountedAncestor = finishedWork.return; - try { - var current$jscomp$0 = current; - instance.props = current$jscomp$0.memoizedProps; - instance.state = current$jscomp$0.memoizedState; - instance.componentWillUnmount(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 26: - case 27: - case 5: - safelyDetachRef(finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 22: - safelyDetachRef(finishedWork, finishedWork.return); - null === finishedWork.memoizedState && - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - default: - recursivelyTraverseDisappearLayoutEffects(finishedWork); +var offscreenSubtreeIsHidden = !1, + offscreenSubtreeWasHidden = !1, + PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, + nextEffect = null; +function safelyAttachRef(current, nearestMountedAncestor) { + try { + var ref = current.ref; + if (null !== ref) { + var instance = current.stateNode; + switch (current.tag) { + case 26: + case 27: + case 5: + var instanceToUse = getPublicInstance(instance); + break; + default: + instanceToUse = instance; + } + "function" === typeof ref + ? (current.refCleanup = ref(instanceToUse)) + : (ref.current = instanceToUse); } - parentFiber = parentFiber.sibling; + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); } } -function recursivelyTraverseReappearLayoutEffects( - finishedRoot$jscomp$0, - parentFiber, - includeWorkInProgressEffects -) { - includeWorkInProgressEffects = - includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var current = parentFiber.alternate, - finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - commitHookLayoutEffects(finishedWork, 4); - break; - case 1: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - finishedRoot = finishedWork.stateNode; - if ("function" === typeof finishedRoot.componentDidMount) - try { - finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - current = finishedWork.updateQueue; - if (null !== current) { - var hiddenCallbacks = current.shared.hiddenCallbacks; - if (null !== hiddenCallbacks) - for ( - current.shared.hiddenCallbacks = null, current = 0; - current < hiddenCallbacks.length; - current++ - ) - callCallback(hiddenCallbacks[current], finishedRoot); - } - includeWorkInProgressEffects && - flags & 64 && - commitClassCallbacks(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 26: - case 27: - case 5: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - includeWorkInProgressEffects && - null === current && - flags & 4 && - commitHostComponentMount(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 13: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 22: - null === finishedWork.memoizedState && - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - default: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - } - parentFiber = parentFiber.sibling; - } +function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref, + refCleanup = current.refCleanup; + if (null !== ref) + if ("function" === typeof refCleanup) + try { + refCleanup(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } finally { + (current.refCleanup = null), + (current = current.alternate), + null != current && (current.refCleanup = null); + } + else if ("function" === typeof ref) + try { + ref(null); + } catch (error$76) { + captureCommitPhaseError(current, nearestMountedAncestor, error$76); + } + else ref.current = null; } -function commitHookPassiveMountEffects(finishedWork, hookFlags) { +function safelyCallDestroy(current, nearestMountedAncestor, destroy) { try { - commitHookEffectListMount(hookFlags, finishedWork); + destroy(); } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); + captureCommitPhaseError(current, nearestMountedAncestor, error); } } -function recursivelyTraversePassiveMountEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveMountOnFiber(root, parentFiber), - (parentFiber = parentFiber.sibling); +var shouldFireAfterActiveInstanceBlur = !1; +function commitBeforeMutationEffects(root, firstChild) { + for (nextEffect = firstChild; null !== nextEffect; ) + if ( + ((root = nextEffect), + (firstChild = root.child), + 0 !== (root.subtreeFlags & 1028) && null !== firstChild) + ) + (firstChild.return = root), (nextEffect = firstChild); + else + for (; null !== nextEffect; ) { + root = nextEffect; + try { + var current = root.alternate, + flags = root.flags; + switch (root.tag) { + case 0: + break; + case 11: + case 15: + break; + case 1: + if (0 !== (flags & 1024) && null !== current) { + var prevProps = current.memoizedProps, + prevState = current.memoizedState, + instance = root.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + root.elementType === root.type + ? prevProps + : resolveDefaultProps(root.type, prevProps), + prevState + ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + case 3: + break; + case 5: + case 26: + case 27: + case 6: + case 4: + case 17: + break; + default: + if (0 !== (flags & 1024)) + throw Error( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + } catch (error) { + captureCommitPhaseError(root, root.return, error); + } + firstChild = root.sibling; + if (null !== firstChild) { + firstChild.return = root.return; + nextEffect = firstChild; + break; + } + nextEffect = root.return; + } + current = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = !1; + return current; } -function commitPassiveMountOnFiber(finishedRoot, finishedWork) { +function commitHookEffectListUnmount( + flags, + finishedWork, + nearestMountedAncestor +) { + var updateQueue = finishedWork.updateQueue; + updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; + if (null !== updateQueue) { + var effect = (updateQueue = updateQueue.next); + do { + if ((effect.tag & flags) === flags) { + var inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + ((inst.destroy = void 0), + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); + } + effect = effect.next; + } while (effect !== updateQueue); + } +} +function commitHookEffectListMount(flags, finishedWork) { + finishedWork = finishedWork.updateQueue; + finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; + if (null !== finishedWork) { + var effect = (finishedWork = finishedWork.next); + do { + if ((effect.tag & flags) === flags) { + var create$77 = effect.create, + inst = effect.inst; + create$77 = create$77(); + inst.destroy = create$77; + } + effect = effect.next; + } while (effect !== finishedWork); + } +} +function commitHookLayoutEffects(finishedWork, hookFlags) { + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } +} +function commitClassCallbacks(finishedWork) { + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var instance = finishedWork.stateNode; + try { + commitCallbacks(updateQueue, instance); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } +} +function commitHostComponentMount(finishedWork) { + try { + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } +} +function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { var flags = finishedWork.flags; switch (finishedWork.tag) { case 0: case 11: case 15: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitHookLayoutEffects(finishedWork, 5); + break; + case 1: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 4) + if (((finishedRoot = finishedWork.stateNode), null === current)) + try { + finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + else { + var prevProps = + finishedWork.elementType === finishedWork.type + ? current.memoizedProps + : resolveDefaultProps(finishedWork.type, current.memoizedProps); + current = current.memoizedState; + try { + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$78) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$78 + ); + } + } + flags & 64 && commitClassCallbacks(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); break; case 3: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { + finishedRoot = null; + if (null !== finishedWork.child) + switch (finishedWork.child.tag) { + case 27: + case 5: + finishedRoot = getPublicInstance(finishedWork.child.stateNode); + break; + case 1: + finishedRoot = finishedWork.child.stateNode; + } + try { + commitCallbacks(flags, finishedRoot); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } break; - case 23: + case 26: + case 27: + case 5: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + null === current && flags & 4 && commitHostComponentMount(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); break; - case 22: - flags = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : finishedWork.mode & 1 || - ((flags._visibility |= 4), - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) - : flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : ((flags._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); + case 12: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); break; - case 24: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + case 13: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + break; + case 22: + if (0 !== (finishedWork.mode & 1)) { + if ( + ((prevProps = + null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), + !prevProps) + ) { + current = + (null !== current && null !== current.memoizedState) || + offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevProps; + (offscreenSubtreeWasHidden = current) && + !prevOffscreenSubtreeWasHidden + ? recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + 0 !== (finishedWork.subtreeFlags & 8772) + ) + : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } + } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && + ("manual" === finishedWork.memoizedProps.mode + ? safelyAttachRef(finishedWork, finishedWork.return) + : safelyDetachRef(finishedWork, finishedWork.return)); break; default: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); } } -function recursivelyTraverseReconnectPassiveEffects( - finishedRoot$jscomp$0, - parentFiber -) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - commitHookPassiveMountEffects(finishedWork, 8); - break; - case 23: - break; - case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? instance._visibility & 4 - ? recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - ) - : finishedWork.mode & 1 || - ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )) - : ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - break; - default: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - } - parentFiber = parentFiber.sibling; - } +function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; + null !== alternate && + ((fiber.alternate = null), detachFiberAfterEffects(alternate)); + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + fiber.stateNode = null; + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; } -var suspenseyCommitFlag = 8192; -function recursivelyAccumulateSuspenseyCommit(parentFiber) { - if (parentFiber.subtreeFlags & suspenseyCommitFlag) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - accumulateSuspenseyCommitOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); +function recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + parent +) { + for (parent = parent.child; null !== parent; ) + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), + (parent = parent.sibling); } -function accumulateSuspenseyCommitOnFiber(fiber) { - switch (fiber.tag) { +function commitDeletionEffectsOnFiber( + finishedRoot, + nearestMountedAncestor, + deletedFiber +) { + if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) + try { + injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); + } catch (err) {} + switch (deletedFiber.tag) { case 26: - recursivelyAccumulateSuspenseyCommit(fiber); - if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) - throw Error( - "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." - ); - break; + case 27: case 5: - recursivelyAccumulateSuspenseyCommit(fiber); + offscreenSubtreeWasHidden || + safelyDetachRef(deletedFiber, nearestMountedAncestor); + case 6: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; - case 3: - case 4: - recursivelyAccumulateSuspenseyCommit(fiber); + case 18: break; - case 22: - if (null === fiber.memoizedState) { - var current = fiber.alternate; - null !== current && null !== current.memoizedState - ? ((current = suspenseyCommitFlag), - (suspenseyCommitFlag = 16777216), - recursivelyAccumulateSuspenseyCommit(fiber), - (suspenseyCommitFlag = current)) - : recursivelyAccumulateSuspenseyCommit(fiber); - } + case 4: + createChildNodeSet(); + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; - default: - recursivelyAccumulateSuspenseyCommit(fiber); - } -} -function detachAlternateSiblings(parentFiber) { - var previousFiber = parentFiber.alternate; - if ( - null !== previousFiber && - ((parentFiber = previousFiber.child), null !== parentFiber) - ) { - previousFiber.child = null; - do - (previousFiber = parentFiber.sibling), - (parentFiber.sibling = null), - (parentFiber = previousFiber); - while (null !== parentFiber); - } -} -function recursivelyTraversePassiveUnmountEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveUnmountOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); -} -function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { case 0: case 11: + case 14: case 15: - recursivelyTraversePassiveUnmountEffects(finishedWork); - finishedWork.flags & 2048 && - commitHookEffectListUnmount(9, finishedWork, finishedWork.return); + if (!offscreenSubtreeWasHidden) { + var updateQueue = deletedFiber.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + ) { + var effect = (updateQueue = updateQueue.next); + do { + var tag = effect.tag, + inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + (0 !== (tag & 2) + ? ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )) + : 0 !== (tag & 4) && + ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + ))); + effect = effect.next; + } while (effect !== updateQueue); + } + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 1: + if ( + !offscreenSubtreeWasHidden && + (safelyDetachRef(deletedFiber, nearestMountedAncestor), + (updateQueue = deletedFiber.stateNode), + "function" === typeof updateQueue.componentWillUnmount) + ) + try { + (updateQueue.props = deletedFiber.memoizedProps), + (updateQueue.state = deletedFiber.memoizedState), + updateQueue.componentWillUnmount(); + } catch (error) { + captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 21: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState && - instance._visibility & 4 && - (null === finishedWork.return || 13 !== finishedWork.return.tag) - ? ((instance._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(finishedWork)) - : recursivelyTraversePassiveUnmountEffects(finishedWork); + safelyDetachRef(deletedFiber, nearestMountedAncestor); + deletedFiber.mode & 1 + ? ((offscreenSubtreeWasHidden = + (updateQueue = offscreenSubtreeWasHidden) || + null !== deletedFiber.memoizedState), + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ), + (offscreenSubtreeWasHidden = updateQueue)) + : recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; default: - recursivelyTraversePassiveUnmountEffects(finishedWork); + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); } } -function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - deletions = parentFiber; - switch (deletions.tag) { +function getRetryCache(finishedWork) { + switch (finishedWork.tag) { + case 13: + case 19: + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); + return retryCache; + case 22: + return ( + (finishedWork = finishedWork.stateNode), + (retryCache = finishedWork._retryCache), + null === retryCache && + (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), + retryCache + ); + default: + throw Error( + "Unexpected Suspense handler tag (" + + finishedWork.tag + + "). This is a bug in React." + ); + } +} +function attachSuspenseRetryListeners(finishedWork, wakeables) { + var retryCache = getRetryCache(finishedWork); + wakeables.forEach(function (wakeable) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + retryCache.has(wakeable) || + (retryCache.add(wakeable), wakeable.then(retry, retry)); + }); +} +function recursivelyTraverseMutationEffects(root, parentFiber) { + var deletions = parentFiber.deletions; + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + commitDeletionEffectsOnFiber(root, parentFiber, childToDelete); + var alternate = childToDelete.alternate; + null !== alternate && (alternate.return = null); + childToDelete.return = null; + } catch (error) { + captureCommitPhaseError(childToDelete, parentFiber, error); + } + } + if (parentFiber.subtreeFlags & 12854) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitMutationEffectsOnFiber(parentFiber, root), + (parentFiber = parentFiber.sibling); +} +function commitMutationEffectsOnFiber(finishedWork, root) { + var current = finishedWork.alternate, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + try { + commitHookEffectListUnmount(3, finishedWork, finishedWork.return), + commitHookEffectListMount(3, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + try { + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$80) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$80); + } + } + break; + case 1: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + flags & 64 && + offscreenSubtreeIsHidden && + ((finishedWork = finishedWork.updateQueue), + null !== finishedWork && + ((flags = finishedWork.callbacks), + null !== flags && + ((current = finishedWork.shared.hiddenCallbacks), + (finishedWork.shared.hiddenCallbacks = + null === current ? flags : current.concat(flags))))); + break; + case 26: + case 27: + case 5: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + break; + case 6: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 3: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 4: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 13: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + finishedWork.child.flags & 8192 && + ((current = null !== current && null !== current.memoizedState), + null === finishedWork.memoizedState || + current || + (globalMostRecentFallbackTime = now())); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 22: + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + var isHidden = null !== finishedWork.memoizedState, + wasHidden = null !== current && null !== current.memoizedState; + if (finishedWork.mode & 1) { + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; + recursivelyTraverseMutationEffects(root, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + } else recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + root = finishedWork.stateNode; + root._current = finishedWork; + root._visibility &= -3; + root._visibility |= root._pendingVisibility & 2; + flags & 8192 && + ((root._visibility = isHidden + ? root._visibility & -2 + : root._visibility | 1), + isHidden && + ((isHidden = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), + null === current || + wasHidden || + isHidden || + (0 !== (finishedWork.mode & 1) && + recursivelyTraverseDisappearLayoutEffects(finishedWork)))); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((current = flags.retryQueue), + null !== current && + ((flags.retryQueue = null), + attachSuspenseRetryListeners(finishedWork, current)))); + break; + case 19: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 21: + break; + default: + recursivelyTraverseMutationEffects(root, finishedWork), + commitReconciliationEffects(finishedWork); + } +} +function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + flags & 2 && (finishedWork.flags &= -3); + flags & 4096 && (finishedWork.flags &= -4097); +} +function recursivelyTraverseLayoutEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 8772) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), + (parentFiber = parentFiber.sibling); +} +function recursivelyTraverseDisappearLayoutEffects(parentFiber) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedWork = parentFiber; + switch (finishedWork.tag) { case 0: case 11: + case 14: case 15: - commitHookEffectListUnmount(8, deletions, deletions.return); - recursivelyTraverseDisconnectPassiveEffects(deletions); + commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 1: + safelyDetachRef(finishedWork, finishedWork.return); + var instance = finishedWork.stateNode; + if ("function" === typeof instance.componentWillUnmount) { + var current = finishedWork, + nearestMountedAncestor = finishedWork.return; + try { + var current$jscomp$0 = current; + instance.props = current$jscomp$0.memoizedProps; + instance.state = current$jscomp$0.memoizedState; + instance.componentWillUnmount(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 26: + case 27: + case 5: + safelyDetachRef(finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); break; case 22: - i = deletions.stateNode; - i._visibility & 4 && - ((i._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(deletions)); + safelyDetachRef(finishedWork, finishedWork.return); + null === finishedWork.memoizedState && + recursivelyTraverseDisappearLayoutEffects(finishedWork); break; default: - recursivelyTraverseDisconnectPassiveEffects(deletions); + recursivelyTraverseDisappearLayoutEffects(finishedWork); } parentFiber = parentFiber.sibling; } } -function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - deletedSubtreeRoot, - nearestMountedAncestor +function recursivelyTraverseReappearLayoutEffects( + finishedRoot$jscomp$0, + parentFiber, + includeWorkInProgressEffects ) { - for (; null !== nextEffect; ) { - var fiber = nextEffect; - switch (fiber.tag) { + includeWorkInProgressEffects = + includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var current = parentFiber.alternate, + finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber, + flags = finishedWork.flags; + switch (finishedWork.tag) { case 0: case 11: case 15: - commitHookEffectListUnmount(8, fiber, nearestMountedAncestor); - } - var child = fiber.child; - if (null !== child) (child.return = fiber), (nextEffect = child); - else - a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { - child = nextEffect; - var sibling = child.sibling, - returnFiber = child.return; - detachFiberAfterEffects(child); - if (child === fiber) { - nextEffect = null; - break a; - } - if (null !== sibling) { - sibling.return = returnFiber; - nextEffect = sibling; - break a; + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + commitHookLayoutEffects(finishedWork, 4); + break; + case 1: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + finishedRoot = finishedWork.stateNode; + if ("function" === typeof finishedRoot.componentDidMount) + try { + finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + current = finishedWork.updateQueue; + if (null !== current) { + var hiddenCallbacks = current.shared.hiddenCallbacks; + if (null !== hiddenCallbacks) + for ( + current.shared.hiddenCallbacks = null, current = 0; + current < hiddenCallbacks.length; + current++ + ) + callCallback(hiddenCallbacks[current], finishedRoot); } - nextEffect = returnFiber; - } + includeWorkInProgressEffects && + flags & 64 && + commitClassCallbacks(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 26: + case 27: + case 5: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + includeWorkInProgressEffects && + null === current && + flags & 4 && + commitHostComponentMount(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 12: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 13: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 22: + null === finishedWork.memoizedState && + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + default: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + } + parentFiber = parentFiber.sibling; } } -var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, - executionContext = 0, - workInProgressRoot = null, - workInProgress = null, - workInProgressRootRenderLanes = 0, - workInProgressSuspendedReason = 0, - workInProgressThrownValue = null, - workInProgressRootDidAttachPingListener = !1, - entangledRenderLanes = 0, - workInProgressRootExitStatus = 0, - workInProgressRootFatalError = null, - workInProgressRootSkippedLanes = 0, - workInProgressRootInterleavedUpdatedLanes = 0, - workInProgressRootPingedLanes = 0, - workInProgressDeferredLane = 0, - workInProgressRootConcurrentErrors = null, - workInProgressRootRecoverableErrors = null, - globalMostRecentFallbackTime = 0, - workInProgressRootRenderTargetTime = Infinity, - workInProgressTransitions = null, - hasUncaughtError = !1, - firstUncaughtError = null, - legacyErrorBoundariesThatAlreadyFailed = null, - rootDoesHavePassiveEffects = !1, - rootWithPendingPassiveEffects = null, - pendingPassiveEffectsLanes = 0, - nestedUpdateCount = 0, - rootWithNestedUpdates = null; -function requestUpdateLane(fiber) { - if (0 === (fiber.mode & 1)) return 2; - if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) - return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; - fiber = ReactCurrentBatchConfig$1.transition; - null !== fiber && fiber._callbacks.add(handleAsyncAction); - if (null !== fiber) - return ( - 0 === currentEventTransitionLane && - (currentEventTransitionLane = claimNextTransitionLane()), - currentEventTransitionLane - ); - fiber = currentUpdatePriority; - if (0 === fiber) - a: { - fiber = fabricGetCurrentEventPriority - ? fabricGetCurrentEventPriority() - : null; - if (null != fiber) - switch (fiber) { - case FabricDiscretePriority: - fiber = 2; - break a; - } - fiber = 32; - } - return fiber; +function commitHookPassiveMountEffects(finishedWork, hookFlags) { + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } } -function requestDeferredLane() { - 0 === workInProgressDeferredLane && - (workInProgressDeferredLane = - 0 !== (workInProgressRootRenderLanes & 536870912) - ? 536870912 - : claimNextTransitionLane()); - var suspenseHandler = suspenseHandlerStackCursor.current; - null !== suspenseHandler && (suspenseHandler.flags |= 32); - return workInProgressDeferredLane; +function recursivelyTraversePassiveMountEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveMountOnFiber(root, parentFiber), + (parentFiber = parentFiber.sibling); } -function scheduleUpdateOnFiber(root, fiber, lane) { - if ( - (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || - null !== root.cancelPendingCommit - ) - prepareFreshStack(root, 0), - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); - markRootUpdated(root, lane); - if (0 === (executionContext & 2) || root !== workInProgressRoot) - root === workInProgressRoot && - (0 === (executionContext & 2) && - (workInProgressRootInterleavedUpdatedLanes |= lane), - 4 === workInProgressRootExitStatus && - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - )), - ensureRootIsScheduled(root), - 2 === lane && - 0 === executionContext && - 0 === (fiber.mode & 1) && - ((workInProgressRootRenderTargetTime = now() + 500), - flushSyncWorkAcrossRoots_impl(!0)); +function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + break; + case 3: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + case 23: + break; + case 22: + flags = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : finishedWork.mode & 1 || + ((flags._visibility |= 4), + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) + : flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : ((flags._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + } } -function performConcurrentWorkOnRoot(root, didTimeout) { - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var originalCallbackNode = root.callbackNode; - if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) - return null; - var lanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : 0 - ); - if (0 === lanes) return null; - var exitStatus = (didTimeout = - 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) - ? renderRootConcurrent(root, lanes) - : renderRootSync(root, lanes); - if (0 !== exitStatus) { - var renderWasConcurrent = didTimeout; - do { - if (6 === exitStatus) markRootSuspended(root, lanes, 0); - else { - didTimeout = root.current.alternate; - if ( - renderWasConcurrent && - !isRenderConsistentWithExternalStores(didTimeout) - ) { - exitStatus = renderRootSync(root, lanes); - renderWasConcurrent = !1; - continue; - } - if (2 === exitStatus) { - renderWasConcurrent = lanes; - var errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - renderWasConcurrent - ); - 0 !== errorRetryLanes && - ((lanes = errorRetryLanes), - (exitStatus = recoverFromConcurrentError( - root, - renderWasConcurrent, - errorRetryLanes - ))); - } - if (1 === exitStatus) - throw ( - ((originalCallbackNode = workInProgressRootFatalError), - prepareFreshStack(root, 0), - markRootSuspended(root, lanes, 0), - ensureRootIsScheduled(root), - originalCallbackNode) - ); - root.finishedWork = didTimeout; - root.finishedLanes = lanes; - a: { - renderWasConcurrent = root; - switch (exitStatus) { - case 0: - case 1: - throw Error("Root did not complete. This is a bug in React."); - case 4: - if ((lanes & 4194176) === lanes) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane - ); - break a; - } - break; - case 2: - case 3: - case 5: - break; - default: - throw Error("Unknown root exit status."); - } - if ( - (lanes & 62914560) === lanes && - 3 === exitStatus && - ((exitStatus = globalMostRecentFallbackTime + 300 - now()), - 10 < exitStatus) - ) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane - ); - if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; - renderWasConcurrent.timeoutHandle = scheduleTimeout( - commitRootWhenReady.bind( - null, - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ), - exitStatus - ); - break a; - } - commitRootWhenReady( - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ); - } - } - break; - } while (1); - } - ensureRootIsScheduled(root); - scheduleTaskForRootDuringMicrotask(root, now()); - root = - root.callbackNode === originalCallbackNode - ? performConcurrentWorkOnRoot.bind(null, root) - : null; - return root; -} -function recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes +function recursivelyTraverseReconnectPassiveEffects( + finishedRoot$jscomp$0, + parentFiber ) { - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, - JSCompiler_inline_result; - (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && - (prepareFreshStack(root, errorRetryLanes).flags |= 256); - errorRetryLanes = renderRootSync(root, errorRetryLanes); - if (2 !== errorRetryLanes) { - if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) - return ( - (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), - (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), - 4 - ); - root = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - null !== root && queueRecoverableErrors(root); + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + commitHookPassiveMountEffects(finishedWork, 8); + break; + case 23: + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? instance._visibility & 4 + ? recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + ) + : finishedWork.mode & 1 || + ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )) + : ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + } + parentFiber = parentFiber.sibling; } - return errorRetryLanes; -} -function queueRecoverableErrors(errors) { - null === workInProgressRootRecoverableErrors - ? (workInProgressRootRecoverableErrors = errors) - : workInProgressRootRecoverableErrors.push.apply( - workInProgressRootRecoverableErrors, - errors - ); } -function commitRootWhenReady( - root, - finishedWork, - recoverableErrors, - transitions, - lanes, - spawnedLane -) { - 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); - commitRoot(root, recoverableErrors, transitions, spawnedLane); +var suspenseyCommitFlag = 8192; +function recursivelyAccumulateSuspenseyCommit(parentFiber) { + if (parentFiber.subtreeFlags & suspenseyCommitFlag) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + accumulateSuspenseyCommitOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); } -function isRenderConsistentWithExternalStores(finishedWork) { - for (var node = finishedWork; ; ) { - if (node.flags & 16384) { - var updateQueue = node.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.stores), null !== updateQueue) - ) - for (var i = 0; i < updateQueue.length; i++) { - var check = updateQueue[i], - getSnapshot = check.getSnapshot; - check = check.value; - try { - if (!objectIs(getSnapshot(), check)) return !1; - } catch (error) { - return !1; - } - } - } - updateQueue = node.child; - if (node.subtreeFlags & 16384 && null !== updateQueue) - (updateQueue.return = node), (node = updateQueue); - else { - if (node === finishedWork) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === finishedWork) return !0; - node = node.return; +function accumulateSuspenseyCommitOnFiber(fiber) { + switch (fiber.tag) { + case 26: + recursivelyAccumulateSuspenseyCommit(fiber); + if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) + throw Error( + "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." + ); + break; + case 5: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 3: + case 4: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 22: + if (null === fiber.memoizedState) { + var current = fiber.alternate; + null !== current && null !== current.memoizedState + ? ((current = suspenseyCommitFlag), + (suspenseyCommitFlag = 16777216), + recursivelyAccumulateSuspenseyCommit(fiber), + (suspenseyCommitFlag = current)) + : recursivelyAccumulateSuspenseyCommit(fiber); } - node.sibling.return = node.return; - node = node.sibling; - } + break; + default: + recursivelyAccumulateSuspenseyCommit(fiber); } - return !0; } -function markRootSuspended(root, suspendedLanes, spawnedLane) { - suspendedLanes &= ~workInProgressRootPingedLanes; - suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - for ( - var expirationTimes = root.expirationTimes, lanes = suspendedLanes; - 0 < lanes; - +function detachAlternateSiblings(parentFiber) { + var previousFiber = parentFiber.alternate; + if ( + null !== previousFiber && + ((parentFiber = previousFiber.child), null !== parentFiber) ) { - var index$4 = 31 - clz32(lanes), - lane = 1 << index$4; - expirationTimes[index$4] = -1; - lanes &= ~lane; + previousFiber.child = null; + do + (previousFiber = parentFiber.sibling), + (parentFiber.sibling = null), + (parentFiber = previousFiber); + while (null !== parentFiber); } - 0 !== spawnedLane && - markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); } -function resetWorkInProgressStack() { - if (null !== workInProgress) { - if (0 === workInProgressSuspendedReason) - var interruptedWork = workInProgress.return; - else - (interruptedWork = workInProgress), - resetContextDependencies(), - resetHooksOnUnwind(interruptedWork), - (thenableState$1 = null), - (thenableIndexCounter$1 = 0), - (interruptedWork = workInProgress); - for (; null !== interruptedWork; ) - unwindInterruptedWork(interruptedWork.alternate, interruptedWork), - (interruptedWork = interruptedWork.return); - workInProgress = null; +function recursivelyTraversePassiveUnmountEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); + } + detachAlternateSiblings(parentFiber); } + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveUnmountOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); } -function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = 0; - var timeoutHandle = root.timeoutHandle; - -1 !== timeoutHandle && - ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); - timeoutHandle = root.cancelPendingCommit; - null !== timeoutHandle && - ((root.cancelPendingCommit = null), timeoutHandle()); - resetWorkInProgressStack(); - workInProgressRoot = root; - workInProgress = timeoutHandle = createWorkInProgress(root.current, null); - workInProgressRootRenderLanes = lanes; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - workInProgressRootDidAttachPingListener = !1; - workInProgressRootExitStatus = 0; - workInProgressRootFatalError = null; - workInProgressDeferredLane = - workInProgressRootPingedLanes = - workInProgressRootInterleavedUpdatedLanes = - workInProgressRootSkippedLanes = - 0; - workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = - null; - 0 !== (lanes & 8) && (lanes |= lanes & 32); - var allEntangledLanes = root.entangledLanes; - if (0 !== allEntangledLanes) - for ( - root = root.entanglements, allEntangledLanes &= lanes; - 0 < allEntangledLanes; - - ) { - var index$2 = 31 - clz32(allEntangledLanes), - lane = 1 << index$2; - lanes |= root[index$2]; - allEntangledLanes &= ~lane; - } - entangledRenderLanes = lanes; - finishQueueingConcurrentUpdates(); - return timeoutHandle; -} -function handleThrow(root, thrownValue) { - currentlyRenderingFiber$1 = null; - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - ReactCurrentOwner.current = null; - thrownValue === SuspenseException - ? ((thrownValue = getSuspendedThenable()), - (root = suspenseHandlerStackCursor.current), - (workInProgressSuspendedReason = - (null !== root && - ((workInProgressRootRenderLanes & 4194176) === - workInProgressRootRenderLanes - ? null !== shellBoundary - : ((workInProgressRootRenderLanes & 62914560) !== - workInProgressRootRenderLanes && - 0 === (workInProgressRootRenderLanes & 536870912)) || - root !== shellBoundary)) || - 0 !== (workInProgressRootSkippedLanes & 134217727) || - 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) - ? 3 - : 2)) - : thrownValue === SuspenseyCommitException - ? ((thrownValue = getSuspendedThenable()), - (workInProgressSuspendedReason = 4)) - : (workInProgressSuspendedReason = - thrownValue === SelectiveHydrationException - ? 8 - : null !== thrownValue && - "object" === typeof thrownValue && - "function" === typeof thrownValue.then - ? 6 - : 1); - workInProgressThrownValue = thrownValue; - null === workInProgress && - ((workInProgressRootExitStatus = 1), - (workInProgressRootFatalError = thrownValue)); -} -function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; -} -function renderDidSuspendDelayIfPossible() { - workInProgressRootExitStatus = 4; - (0 === (workInProgressRootSkippedLanes & 134217727) && - 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || - null === workInProgressRoot || - markRootSuspended( - workInProgressRoot, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); +function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveUnmountEffects(finishedWork); + finishedWork.flags & 2048 && + commitHookEffectListUnmount(9, finishedWork, finishedWork.return); + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState && + instance._visibility & 4 && + (null === finishedWork.return || 13 !== finishedWork.return.tag) + ? ((instance._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(finishedWork)) + : recursivelyTraversePassiveUnmountEffects(finishedWork); + break; + default: + recursivelyTraversePassiveUnmountEffects(finishedWork); + } } -function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) - (workInProgressTransitions = null), prepareFreshStack(root, lanes); - lanes = !1; - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - var unitOfWork = workInProgress, - thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - case 3: - case 2: - lanes || - null !== suspenseHandlerStackCursor.current || - (lanes = !0); - default: - (workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, unitOfWork, thrownValue); - } +function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); } - workLoopSync(); - break; - } catch (thrownValue$89) { - handleThrow(root, thrownValue$89); + detachAlternateSiblings(parentFiber); + } + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + deletions = parentFiber; + switch (deletions.tag) { + case 0: + case 11: + case 15: + commitHookEffectListUnmount(8, deletions, deletions.return); + recursivelyTraverseDisconnectPassiveEffects(deletions); + break; + case 22: + i = deletions.stateNode; + i._visibility & 4 && + ((i._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(deletions)); + break; + default: + recursivelyTraverseDisconnectPassiveEffects(deletions); } - while (1); - lanes && root.shellSuspendCounter++; - resetContextDependencies(); - executionContext = prevExecutionContext; - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - throw Error( - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; -} -function workLoopSync() { - for (; null !== workInProgress; ) performUnitOfWork(workInProgress); + parentFiber = parentFiber.sibling; + } } -function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) - (workInProgressTransitions = null), - (workInProgressRootRenderTargetTime = now() + 500), - prepareFreshStack(root, lanes); - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - lanes = workInProgress; - var thrownValue = workInProgressThrownValue; - b: switch (workInProgressSuspendedReason) { - case 1: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 2: - if (isThenableResolved(thrownValue)) { - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(lanes); - break; - } - lanes = function () { - 2 === workInProgressSuspendedReason && - workInProgressRoot === root && - (workInProgressSuspendedReason = 7); - ensureRootIsScheduled(root); - }; - thrownValue.then(lanes, lanes); - break a; - case 3: - workInProgressSuspendedReason = 7; - break a; - case 4: - workInProgressSuspendedReason = 5; - break a; - case 7: - isThenableResolved(thrownValue) - ? ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - replaySuspendedUnitOfWork(lanes)) - : ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, lanes, thrownValue)); - break; - case 5: - switch (workInProgress.tag) { - case 5: - case 26: - case 27: - lanes = workInProgress; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - var sibling = lanes.sibling; - if (null !== sibling) workInProgress = sibling; - else { - var returnFiber = lanes.return; - null !== returnFiber - ? ((workInProgress = returnFiber), - completeUnitOfWork(returnFiber)) - : (workInProgress = null); - } - break b; - } - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 6: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - default: - throw Error("Unexpected SuspendedReason. This is a bug in React."); +function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + deletedSubtreeRoot, + nearestMountedAncestor +) { + for (; null !== nextEffect; ) { + var fiber = nextEffect; + switch (fiber.tag) { + case 0: + case 11: + case 15: + commitHookEffectListUnmount(8, fiber, nearestMountedAncestor); + } + var child = fiber.child; + if (null !== child) (child.return = fiber), (nextEffect = child); + else + a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { + child = nextEffect; + var sibling = child.sibling, + returnFiber = child.return; + detachFiberAfterEffects(child); + if (child === fiber) { + nextEffect = null; + break a; + } + if (null !== sibling) { + sibling.return = returnFiber; + nextEffect = sibling; + break a; } + nextEffect = returnFiber; } - workLoopConcurrent(); - break; - } catch (thrownValue$91) { - handleThrow(root, thrownValue$91); - } - while (1); - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - executionContext = prevExecutionContext; - if (null !== workInProgress) return 0; - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; -} -function workLoopConcurrent() { - for (; null !== workInProgress && !shouldYield(); ) - performUnitOfWork(workInProgress); + } } -function performUnitOfWork(unitOfWork) { - var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next); - ReactCurrentOwner.current = null; +var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, + executionContext = 0, + workInProgressRoot = null, + workInProgress = null, + workInProgressRootRenderLanes = 0, + workInProgressSuspendedReason = 0, + workInProgressThrownValue = null, + workInProgressRootDidAttachPingListener = !1, + entangledRenderLanes = 0, + workInProgressRootExitStatus = 0, + workInProgressRootFatalError = null, + workInProgressRootSkippedLanes = 0, + workInProgressRootInterleavedUpdatedLanes = 0, + workInProgressRootPingedLanes = 0, + workInProgressDeferredLane = 0, + workInProgressRootConcurrentErrors = null, + workInProgressRootRecoverableErrors = null, + workInProgressRootDidIncludeRecursiveRenderUpdate = !1, + globalMostRecentFallbackTime = 0, + workInProgressRootRenderTargetTime = Infinity, + workInProgressTransitions = null, + hasUncaughtError = !1, + firstUncaughtError = null, + legacyErrorBoundariesThatAlreadyFailed = null, + rootDoesHavePassiveEffects = !1, + rootWithPendingPassiveEffects = null, + pendingPassiveEffectsLanes = 0, + nestedUpdateCount = 0, + rootWithNestedUpdates = null; +function requestUpdateLane(fiber) { + if (0 === (fiber.mode & 1)) return 2; + if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) + return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; + fiber = ReactCurrentBatchConfig$1.transition; + null !== fiber && fiber._callbacks.add(handleAsyncAction); + if (null !== fiber) + return ( + 0 === currentEventTransitionLane && + (currentEventTransitionLane = claimNextTransitionLane()), + currentEventTransitionLane + ); + fiber = currentUpdatePriority; + if (0 === fiber) + a: { + fiber = fabricGetCurrentEventPriority + ? fabricGetCurrentEventPriority() + : null; + if (null != fiber) + switch (fiber) { + case FabricDiscretePriority: + fiber = 2; + break a; + } + fiber = 32; + } + return fiber; } -function replaySuspendedUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate; - switch (unitOfWork.tag) { - case 2: - unitOfWork.tag = 0; - case 15: - case 0: - var Component = unitOfWork.type, - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(unitOfWork, context); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - context, - workInProgressRootRenderLanes - ); - break; - case 11: - Component = unitOfWork.type.render; - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - unitOfWork.ref, - workInProgressRootRenderLanes - ); - break; - case 5: - resetHooksOnUnwind(unitOfWork); - default: - unwindInterruptedWork(current, unitOfWork), - (unitOfWork = workInProgress = - resetWorkInProgress(unitOfWork, entangledRenderLanes)), - (current = beginWork(current, unitOfWork, entangledRenderLanes)); - } - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; +function requestDeferredLane() { + 0 === workInProgressDeferredLane && + (workInProgressDeferredLane = + 0 !== (workInProgressRootRenderLanes & 536870912) + ? 536870912 + : claimNextTransitionLane()); + var suspenseHandler = suspenseHandlerStackCursor.current; + null !== suspenseHandler && (suspenseHandler.flags |= 32); + return workInProgressDeferredLane; } -function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { - resetContextDependencies(); - resetHooksOnUnwind(unitOfWork); - thenableState$1 = null; - thenableIndexCounter$1 = 0; - var returnFiber = unitOfWork.return; - try { - if ( - throwException( +function scheduleUpdateOnFiber(root, fiber, lane) { + if ( + (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || + null !== root.cancelPendingCommit + ) + prepareFreshStack(root, 0), + markRootSuspended( root, - returnFiber, - unitOfWork, - thrownValue, - workInProgressRootRenderLanes - ) - ) { - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - } catch (error) { - if (null !== returnFiber) throw ((workInProgress = returnFiber), error); - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - if (unitOfWork.flags & 32768) - a: { - root = unitOfWork; - do { - unitOfWork = unwindWork(root.alternate, root); - if (null !== unitOfWork) { - unitOfWork.flags &= 32767; - workInProgress = unitOfWork; - break a; - } - root = root.return; - null !== root && - ((root.flags |= 32768), - (root.subtreeFlags = 0), - (root.deletions = null)); - workInProgress = root; - } while (null !== root); - workInProgressRootExitStatus = 6; - workInProgress = null; - } - else completeUnitOfWork(unitOfWork); + workInProgressRootRenderLanes, + workInProgressDeferredLane + ); + markRootUpdated$1(root, lane); + if (0 === (executionContext & 2) || root !== workInProgressRoot) + root === workInProgressRoot && + (0 === (executionContext & 2) && + (workInProgressRootInterleavedUpdatedLanes |= lane), + 4 === workInProgressRootExitStatus && + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane + )), + ensureRootIsScheduled(root), + 2 === lane && + 0 === executionContext && + 0 === (fiber.mode & 1) && + ((workInProgressRootRenderTargetTime = now() + 500), + flushSyncWorkAcrossRoots_impl(!0)); } -function completeUnitOfWork(unitOfWork) { - var completedWork = unitOfWork; - do { - unitOfWork = completedWork.return; - var next = completeWork( - completedWork.alternate, - completedWork, - entangledRenderLanes - ); - if (null !== next) { - workInProgress = next; - return; - } - completedWork = completedWork.sibling; - if (null !== completedWork) { - workInProgress = completedWork; - return; - } - workInProgress = completedWork = unitOfWork; - } while (null !== completedWork); - 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +function performConcurrentWorkOnRoot(root, didTimeout) { + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + var originalCallbackNode = root.callbackNode; + if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) + return null; + var lanes = getNextLanes( + root, + root === workInProgressRoot ? workInProgressRootRenderLanes : 0 + ); + if (0 === lanes) return null; + var exitStatus = (didTimeout = + 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) + ? renderRootConcurrent(root, lanes) + : renderRootSync(root, lanes); + if (0 !== exitStatus) { + var renderWasConcurrent = didTimeout; + do { + if (6 === exitStatus) markRootSuspended(root, lanes, 0); + else { + didTimeout = root.current.alternate; + if ( + renderWasConcurrent && + !isRenderConsistentWithExternalStores(didTimeout) + ) { + exitStatus = renderRootSync(root, lanes); + renderWasConcurrent = !1; + continue; + } + if (2 === exitStatus) { + renderWasConcurrent = lanes; + var errorRetryLanes = getLanesToRetrySynchronouslyOnError( + root, + renderWasConcurrent + ); + 0 !== errorRetryLanes && + ((lanes = errorRetryLanes), + (exitStatus = recoverFromConcurrentError( + root, + renderWasConcurrent, + errorRetryLanes + ))); + } + if (1 === exitStatus) + throw ( + ((originalCallbackNode = workInProgressRootFatalError), + prepareFreshStack(root, 0), + markRootSuspended(root, lanes, 0), + ensureRootIsScheduled(root), + originalCallbackNode) + ); + root.finishedWork = didTimeout; + root.finishedLanes = lanes; + a: { + renderWasConcurrent = root; + switch (exitStatus) { + case 0: + case 1: + throw Error("Root did not complete. This is a bug in React."); + case 4: + if ((lanes & 4194176) === lanes) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + break a; + } + break; + case 2: + case 3: + case 5: + break; + default: + throw Error("Unknown root exit status."); + } + if ( + (lanes & 62914560) === lanes && + 3 === exitStatus && + ((exitStatus = globalMostRecentFallbackTime + 300 - now()), + 10 < exitStatus) + ) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; + renderWasConcurrent.timeoutHandle = scheduleTimeout( + commitRootWhenReady.bind( + null, + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ), + exitStatus + ); + break a; + } + commitRootWhenReady( + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ); + } + } + break; + } while (1); + } + ensureRootIsScheduled(root); + scheduleTaskForRootDuringMicrotask(root, now()); + root = + root.callbackNode === originalCallbackNode + ? performConcurrentWorkOnRoot.bind(null, root) + : null; + return root; } -function commitRoot(root, recoverableErrors, transitions, spawnedLane) { - var previousUpdateLanePriority = currentUpdatePriority, - prevTransition = ReactCurrentBatchConfig.transition; - try { - (ReactCurrentBatchConfig.transition = null), - (currentUpdatePriority = 2), - commitRootImpl( - root, - recoverableErrors, - transitions, - previousUpdateLanePriority, - spawnedLane +function recoverFromConcurrentError( + root, + originallyAttemptedLanes, + errorRetryLanes +) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, + JSCompiler_inline_result; + (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && + (prepareFreshStack(root, errorRetryLanes).flags |= 256); + errorRetryLanes = renderRootSync(root, errorRetryLanes); + if (2 !== errorRetryLanes) { + if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) + return ( + (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), + (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), + 4 ); - } finally { - (ReactCurrentBatchConfig.transition = prevTransition), - (currentUpdatePriority = previousUpdateLanePriority); + root = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + null !== root && queueRecoverableErrors(root); } - return null; + return errorRetryLanes; } -function commitRootImpl( +function queueRecoverableErrors(errors) { + null === workInProgressRootRecoverableErrors + ? (workInProgressRootRecoverableErrors = errors) + : workInProgressRootRecoverableErrors.push.apply( + workInProgressRootRecoverableErrors, + errors + ); +} +function commitRootWhenReady( root, + finishedWork, recoverableErrors, transitions, - renderPriorityLevel, + didIncludeRenderPhaseUpdate, + lanes, spawnedLane ) { - do flushPassiveEffects(); - while (null !== rootWithPendingPassiveEffects); - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var finishedWork = root.finishedWork; - transitions = root.finishedLanes; - if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedLanes = 0; - if (finishedWork === root.current) - throw Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ); - root.callbackNode = null; - root.callbackPriority = 0; - root.cancelPendingCommit = null; - var remainingLanes = finishedWork.lanes | finishedWork.childLanes; - remainingLanes |= concurrentlyUpdatedLanes; - markRootFinished(root, remainingLanes, spawnedLane); - root === workInProgressRoot && - ((workInProgress = workInProgressRoot = null), - (workInProgressRootRenderLanes = 0)); - (0 === (finishedWork.subtreeFlags & 10256) && - 0 === (finishedWork.flags & 10256)) || - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); - spawnedLane = 0 !== (finishedWork.flags & 15990); - if (0 !== (finishedWork.subtreeFlags & 15990) || spawnedLane) { - spawnedLane = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = null; - remainingLanes = currentUpdatePriority; - currentUpdatePriority = 2; - var prevExecutionContext = executionContext; - executionContext |= 4; - ReactCurrentOwner.current = null; - commitBeforeMutationEffects(root, finishedWork); - commitMutationEffectsOnFiber(finishedWork, root); - root.current = finishedWork; - commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); - requestPaint(); - executionContext = prevExecutionContext; - currentUpdatePriority = remainingLanes; - ReactCurrentBatchConfig.transition = spawnedLane; - } else root.current = finishedWork; - rootDoesHavePassiveEffects && - ((rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsLanes = transitions)); - remainingLanes = root.pendingLanes; - 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - ensureRootIsScheduled(root); - if (null !== recoverableErrors) - for ( - renderPriorityLevel = root.onRecoverableError, finishedWork = 0; - finishedWork < recoverableErrors.length; - finishedWork++ - ) - (spawnedLane = recoverableErrors[finishedWork]), - (remainingLanes = { - digest: spawnedLane.digest, - componentStack: spawnedLane.stack - }), - renderPriorityLevel(spawnedLane.value, remainingLanes); - if (hasUncaughtError) - throw ( - ((hasUncaughtError = !1), - (root = firstUncaughtError), - (firstUncaughtError = null), - root) - ); - 0 !== (pendingPassiveEffectsLanes & 3) && - 0 !== root.tag && - flushPassiveEffects(); - remainingLanes = root.pendingLanes; - 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) - ? root === rootWithNestedUpdates - ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) - : (nestedUpdateCount = 0); - flushSyncWorkAcrossRoots_impl(!1); - return null; + 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); } -function flushPassiveEffects() { - if (null !== rootWithPendingPassiveEffects) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), - prevTransition = ReactCurrentBatchConfig.transition, - previousPriority = currentUpdatePriority; - try { - ReactCurrentBatchConfig.transition = null; - currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; - if (null === rootWithPendingPassiveEffects) - var JSCompiler_inline_result = !1; - else { - renderPriority = rootWithPendingPassiveEffects; - rootWithPendingPassiveEffects = null; - pendingPassiveEffectsLanes = 0; - if (0 !== (executionContext & 6)) - throw Error("Cannot flush passive effects while already rendering."); - var prevExecutionContext = executionContext; - executionContext |= 4; - commitPassiveUnmountOnFiber(renderPriority.current); - commitPassiveMountOnFiber(renderPriority, renderPriority.current); - executionContext = prevExecutionContext; - flushSyncWorkAcrossRoots_impl(!1); - if ( - injectedHook && - "function" === typeof injectedHook.onPostCommitFiberRoot - ) +function isRenderConsistentWithExternalStores(finishedWork) { + for (var node = finishedWork; ; ) { + if (node.flags & 16384) { + var updateQueue = node.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.stores), null !== updateQueue) + ) + for (var i = 0; i < updateQueue.length; i++) { + var check = updateQueue[i], + getSnapshot = check.getSnapshot; + check = check.value; try { - injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); - } catch (err) {} - JSCompiler_inline_result = !0; + if (!objectIs(getSnapshot(), check)) return !1; + } catch (error) { + return !1; + } + } + } + updateQueue = node.child; + if (node.subtreeFlags & 16384 && null !== updateQueue) + (updateQueue.return = node), (node = updateQueue); + else { + if (node === finishedWork) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return !0; + node = node.return; } - return JSCompiler_inline_result; - } finally { - (currentUpdatePriority = previousPriority), - (ReactCurrentBatchConfig.transition = prevTransition); + node.sibling.return = node.return; + node = node.sibling; } } - return !1; + return !0; } -function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); - rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); - null !== rootFiber && - (markRootUpdated(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +function markRootSuspended(root, suspendedLanes, spawnedLane) { + suspendedLanes &= ~workInProgressRootPingedLanes; + suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; + for ( + var expirationTimes = root.expirationTimes, lanes = suspendedLanes; + 0 < lanes; + + ) { + var index$4 = 31 - clz32(lanes), + lane = 1 << index$4; + expirationTimes[index$4] = -1; + lanes &= ~lane; + } + 0 !== spawnedLane && + markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); } -function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { - if (3 === sourceFiber.tag) - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); - else - for (; null !== nearestMountedAncestor; ) { - if (3 === nearestMountedAncestor.tag) { - captureCommitPhaseErrorOnRoot( - nearestMountedAncestor, - sourceFiber, - error - ); - break; - } else if (1 === nearestMountedAncestor.tag) { - var instance = nearestMountedAncestor.stateNode; - if ( - "function" === - typeof nearestMountedAncestor.type.getDerivedStateFromError || - ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) - ) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createClassErrorUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - nearestMountedAncestor = enqueueUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - null !== nearestMountedAncestor && - (markRootUpdated(nearestMountedAncestor, 2), - ensureRootIsScheduled(nearestMountedAncestor)); - break; - } - } - nearestMountedAncestor = nearestMountedAncestor.return; - } +function resetWorkInProgressStack() { + if (null !== workInProgress) { + if (0 === workInProgressSuspendedReason) + var interruptedWork = workInProgress.return; + else + (interruptedWork = workInProgress), + resetContextDependencies(), + resetHooksOnUnwind(interruptedWork), + (thenableState$1 = null), + (thenableIndexCounter$1 = 0), + (interruptedWork = workInProgress); + for (; null !== interruptedWork; ) + unwindInterruptedWork(interruptedWork.alternate, interruptedWork), + (interruptedWork = interruptedWork.return); + workInProgress = null; + } } -function attachPingListener(root, wakeable, lanes) { - var pingCache = root.pingCache; - if (null === pingCache) { - pingCache = root.pingCache = new PossiblyWeakMap(); - var threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else - (threadIDs = pingCache.get(wakeable)), - void 0 === threadIDs && - ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); - threadIDs.has(lanes) || - ((workInProgressRootDidAttachPingListener = !0), - threadIDs.add(lanes), - (root = pingSuspendedRoot.bind(null, root, wakeable, lanes)), - wakeable.then(root, root)); +function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = 0; + var timeoutHandle = root.timeoutHandle; + -1 !== timeoutHandle && + ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); + timeoutHandle = root.cancelPendingCommit; + null !== timeoutHandle && + ((root.cancelPendingCommit = null), timeoutHandle()); + resetWorkInProgressStack(); + workInProgressRoot = root; + workInProgress = timeoutHandle = createWorkInProgress(root.current, null); + workInProgressRootRenderLanes = lanes; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + workInProgressRootDidAttachPingListener = !1; + workInProgressRootExitStatus = 0; + workInProgressRootFatalError = null; + workInProgressDeferredLane = + workInProgressRootPingedLanes = + workInProgressRootInterleavedUpdatedLanes = + workInProgressRootSkippedLanes = + 0; + workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = + null; + workInProgressRootDidIncludeRecursiveRenderUpdate = !1; + 0 !== (lanes & 8) && (lanes |= lanes & 32); + var allEntangledLanes = root.entangledLanes; + if (0 !== allEntangledLanes) + for ( + root = root.entanglements, allEntangledLanes &= lanes; + 0 < allEntangledLanes; + + ) { + var index$2 = 31 - clz32(allEntangledLanes), + lane = 1 << index$2; + lanes |= root[index$2]; + allEntangledLanes &= ~lane; + } + entangledRenderLanes = lanes; + finishQueueingConcurrentUpdates(); + return timeoutHandle; } -function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(wakeable); - root.pingedLanes |= root.suspendedLanes & pingedLanes; - workInProgressRoot === root && - (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && - (4 === workInProgressRootExitStatus || - (3 === workInProgressRootExitStatus && - (workInProgressRootRenderLanes & 62914560) === - workInProgressRootRenderLanes && - 300 > now() - globalMostRecentFallbackTime) - ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) - : (workInProgressRootPingedLanes |= pingedLanes)); - ensureRootIsScheduled(root); +function handleThrow(root, thrownValue) { + currentlyRenderingFiber$1 = null; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentOwner.current = null; + thrownValue === SuspenseException + ? ((thrownValue = getSuspendedThenable()), + (root = suspenseHandlerStackCursor.current), + (workInProgressSuspendedReason = + (null !== root && + ((workInProgressRootRenderLanes & 4194176) === + workInProgressRootRenderLanes + ? null !== shellBoundary + : ((workInProgressRootRenderLanes & 62914560) !== + workInProgressRootRenderLanes && + 0 === (workInProgressRootRenderLanes & 536870912)) || + root !== shellBoundary)) || + 0 !== (workInProgressRootSkippedLanes & 134217727) || + 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) + ? 3 + : 2)) + : thrownValue === SuspenseyCommitException + ? ((thrownValue = getSuspendedThenable()), + (workInProgressSuspendedReason = 4)) + : (workInProgressSuspendedReason = + thrownValue === SelectiveHydrationException + ? 8 + : null !== thrownValue && + "object" === typeof thrownValue && + "function" === typeof thrownValue.then + ? 6 + : 1); + workInProgressThrownValue = thrownValue; + null === workInProgress && + ((workInProgressRootExitStatus = 1), + (workInProgressRootFatalError = thrownValue)); } -function retryTimedOutBoundary(boundaryFiber, retryLane) { - 0 === retryLane && - (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); - boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - null !== boundaryFiber && - (markRootUpdated(boundaryFiber, retryLane), - ensureRootIsScheduled(boundaryFiber)); +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } -function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState, - retryLane = 0; - null !== suspenseState && (retryLane = suspenseState.retryLane); - retryTimedOutBoundary(boundaryFiber, retryLane); +function renderDidSuspendDelayIfPossible() { + workInProgressRootExitStatus = 4; + (0 === (workInProgressRootSkippedLanes & 134217727) && + 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || + null === workInProgressRoot || + markRootSuspended( + workInProgressRoot, + workInProgressRootRenderLanes, + workInProgressDeferredLane + ); } -function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = 0; - switch (boundaryFiber.tag) { - case 13: - var retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - null !== suspenseState && (retryLane = suspenseState.retryLane); - break; - case 19: - retryCache = boundaryFiber.stateNode; - break; - case 22: - retryCache = boundaryFiber.stateNode._retryCache; +function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) + (workInProgressTransitions = null), prepareFreshStack(root, lanes); + lanes = !1; + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + var unitOfWork = workInProgress, + thrownValue = workInProgressThrownValue; + switch (workInProgressSuspendedReason) { + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; + break a; + case 3: + case 2: + lanes || + null !== suspenseHandlerStackCursor.current || + (lanes = !0); + default: + (workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, unitOfWork, thrownValue); + } + } + workLoopSync(); break; - default: - throw Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ); - } - null !== retryCache && retryCache.delete(wakeable); - retryTimedOutBoundary(boundaryFiber, retryLane); -} -var beginWork; -beginWork = function (current, workInProgress, renderLanes) { - if (null !== current) - if ( - current.memoizedProps !== workInProgress.pendingProps || - didPerformWorkStackCursor.current - ) - didReceiveUpdate = !0; - else { - if ( - 0 === (current.lanes & renderLanes) && - 0 === (workInProgress.flags & 128) - ) - return ( - (didReceiveUpdate = !1), - attemptEarlyBailoutIfNoScheduledUpdate( - current, - workInProgress, - renderLanes - ) - ); - didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; + } catch (thrownValue$88) { + handleThrow(root, thrownValue$88); } - else didReceiveUpdate = !1; - workInProgress.lanes = 0; - switch (workInProgress.tag) { - case 2: - var Component = workInProgress.type; - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - var context = getMaskedContext( - workInProgress, - contextStackCursor$1.current - ); - prepareToReadContext(workInProgress, renderLanes); - context = renderWithHooks( - null, - workInProgress, - Component, - current, - context, - renderLanes - ); - workInProgress.flags |= 1; - if ( - "object" === typeof context && - null !== context && - "function" === typeof context.render && - void 0 === context.$$typeof - ) { - workInProgress.tag = 1; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; - workInProgress.memoizedState = - null !== context.state && void 0 !== context.state - ? context.state - : null; - initializeUpdateQueue(workInProgress); - context.updater = classComponentUpdater; - workInProgress.stateNode = context; - context._reactInternals = workInProgress; - mountClassInstance(workInProgress, Component, current, renderLanes); - workInProgress = finishClassComponent( - null, - workInProgress, - Component, - !0, - hasContext, - renderLanes - ); - } else - (workInProgress.tag = 0), - reconcileChildren(null, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child); - return workInProgress; - case 16: - Component = workInProgress.elementType; - a: { - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - context = Component._init; - Component = context(Component._payload); - workInProgress.type = Component; - context = workInProgress.tag = resolveLazyComponentTag(Component); - current = resolveDefaultProps(Component, current); - switch (context) { - case 0: - workInProgress = updateFunctionComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; + while (1); + lanes && root.shellSuspendCounter++; + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopSync() { + for (; null !== workInProgress; ) performUnitOfWork(workInProgress); +} +function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) + (workInProgressTransitions = null), + (workInProgressRootRenderTargetTime = now() + 500), + prepareFreshStack(root, lanes); + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + lanes = workInProgress; + var thrownValue = workInProgressThrownValue; + b: switch (workInProgressSuspendedReason) { case 1: - workInProgress = updateClassComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 2: + if (isThenableResolved(thrownValue)) { + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + replaySuspendedUnitOfWork(lanes); + break; + } + lanes = function () { + 2 === workInProgressSuspendedReason && + workInProgressRoot === root && + (workInProgressSuspendedReason = 7); + ensureRootIsScheduled(root); + }; + thrownValue.then(lanes, lanes); break a; - case 11: - workInProgress = updateForwardRef( - null, - workInProgress, - Component, - current, - renderLanes - ); + case 3: + workInProgressSuspendedReason = 7; break a; - case 14: - workInProgress = updateMemoComponent( - null, - workInProgress, - Component, - resolveDefaultProps(Component.type, current), - renderLanes - ); + case 4: + workInProgressSuspendedReason = 5; + break a; + case 7: + isThenableResolved(thrownValue) + ? ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + replaySuspendedUnitOfWork(lanes)) + : ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, lanes, thrownValue)); + break; + case 5: + switch (workInProgress.tag) { + case 5: + case 26: + case 27: + lanes = workInProgress; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + var sibling = lanes.sibling; + if (null !== sibling) workInProgress = sibling; + else { + var returnFiber = lanes.return; + null !== returnFiber + ? ((workInProgress = returnFiber), + completeUnitOfWork(returnFiber)) + : (workInProgress = null); + } + break b; + } + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 6: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; break a; + default: + throw Error("Unexpected SuspendedReason. This is a bug in React."); } - throw Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." - ); } - return workInProgress; + workLoopConcurrent(); + break; + } catch (thrownValue$90) { + handleThrow(root, thrownValue$90); + } + while (1); + resetContextDependencies(); + ReactCurrentDispatcher.current = prevDispatcher; + executionContext = prevExecutionContext; + if (null !== workInProgress) return 0; + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopConcurrent() { + for (; null !== workInProgress && !shouldYield(); ) + performUnitOfWork(workInProgress); +} +function performUnitOfWork(unitOfWork) { + var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next); + ReactCurrentOwner.current = null; +} +function replaySuspendedUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate; + switch (unitOfWork.tag) { + case 2: + unitOfWork.tag = 0; + case 15: case 0: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateFunctionComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) + var Component = unitOfWork.type, + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + void 0, + workInProgressRootRenderLanes ); - case 1: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateClassComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) + break; + case 11: + Component = unitOfWork.type.render; + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + unitOfWork.ref, + workInProgressRootRenderLanes ); - case 3: - pushHostRootContext(workInProgress); - if (null === current) - throw Error("Should have a current fiber. This is a bug in React."); - context = workInProgress.pendingProps; - Component = workInProgress.memoizedState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, context, null, renderLanes); - context = workInProgress.memoizedState.element; - context === Component - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - )) - : (reconcileChildren(current, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child)); - return workInProgress; - case 26: - case 27: + break; case 5: - return ( - pushHostContext(workInProgress), - (Component = workInProgress.pendingProps.children), - markRef$1(current, workInProgress), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child + resetHooksOnUnwind(unitOfWork); + default: + unwindInterruptedWork(current, unitOfWork), + (unitOfWork = workInProgress = + resetWorkInProgress(unitOfWork, entangledRenderLanes)), + (current = beginWork(current, unitOfWork, entangledRenderLanes)); + } + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; +} +function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { + resetContextDependencies(); + resetHooksOnUnwind(unitOfWork); + thenableState$1 = null; + thenableIndexCounter$1 = 0; + var returnFiber = unitOfWork.return; + try { + if ( + throwException( + root, + returnFiber, + unitOfWork, + thrownValue, + workInProgressRootRenderLanes + ) + ) { + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + } catch (error) { + if (null !== returnFiber) throw ((workInProgress = returnFiber), error); + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (unitOfWork.flags & 32768) + a: { + root = unitOfWork; + do { + unitOfWork = unwindWork(root.alternate, root); + if (null !== unitOfWork) { + unitOfWork.flags &= 32767; + workInProgress = unitOfWork; + break a; + } + root = root.return; + null !== root && + ((root.flags |= 32768), + (root.subtreeFlags = 0), + (root.deletions = null)); + workInProgress = root; + } while (null !== root); + workInProgressRootExitStatus = 6; + workInProgress = null; + } + else completeUnitOfWork(unitOfWork); +} +function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + unitOfWork = completedWork.return; + var next = completeWork( + completedWork.alternate, + completedWork, + entangledRenderLanes + ); + if (null !== next) { + workInProgress = next; + return; + } + completedWork = completedWork.sibling; + if (null !== completedWork) { + workInProgress = completedWork; + return; + } + workInProgress = completedWork = unitOfWork; + } while (null !== completedWork); + 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +} +function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane +) { + var previousUpdateLanePriority = currentUpdatePriority, + prevTransition = ReactCurrentBatchConfig.transition; + try { + (ReactCurrentBatchConfig.transition = null), + (currentUpdatePriority = 2), + commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + previousUpdateLanePriority, + spawnedLane ); - case 6: + } finally { + (ReactCurrentBatchConfig.transition = prevTransition), + (currentUpdatePriority = previousUpdateLanePriority); + } + return null; +} +function commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + renderPriorityLevel, + spawnedLane +) { + do flushPassiveEffects(); + while (null !== rootWithPendingPassiveEffects); + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + didIncludeRenderPhaseUpdate = root.finishedWork; + transitions = root.finishedLanes; + if (null === didIncludeRenderPhaseUpdate) return null; + root.finishedWork = null; + root.finishedLanes = 0; + if (didIncludeRenderPhaseUpdate === root.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + root.callbackNode = null; + root.callbackPriority = 0; + root.cancelPendingCommit = null; + var remainingLanes = + didIncludeRenderPhaseUpdate.lanes | didIncludeRenderPhaseUpdate.childLanes; + remainingLanes |= concurrentlyUpdatedLanes; + markRootFinished(root, remainingLanes, spawnedLane); + root === workInProgressRoot && + ((workInProgress = workInProgressRoot = null), + (workInProgressRootRenderLanes = 0)); + (0 === (didIncludeRenderPhaseUpdate.subtreeFlags & 10256) && + 0 === (didIncludeRenderPhaseUpdate.flags & 10256)) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); return null; - case 13: - return updateSuspenseComponent(current, workInProgress, renderLanes); - case 4: - return ( - pushHostContainer( - workInProgress, - workInProgress.stateNode.containerInfo - ), - (Component = workInProgress.pendingProps), - null === current - ? (workInProgress.child = reconcileChildFibers( - workInProgress, - null, - Component, - renderLanes - )) - : reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 11: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateForwardRef( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 7: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps, - renderLanes - ), - workInProgress.child - ); - case 8: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child - ); - case 12: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child - ); - case 10: - a: { - Component = workInProgress.type._context; - context = workInProgress.pendingProps; - hasContext = workInProgress.memoizedProps; - var newValue = context.value; - push(valueCursor, Component._currentValue2); - Component._currentValue2 = newValue; - if (null !== hasContext) - if (objectIs(hasContext.value, newValue)) { - if ( - hasContext.children === context.children && - !didPerformWorkStackCursor.current - ) { - workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - ); - break a; - } - } else - for ( - hasContext = workInProgress.child, - null !== hasContext && (hasContext.return = workInProgress); - null !== hasContext; - - ) { - var list = hasContext.dependencies; - if (null !== list) { - newValue = hasContext.child; - for ( - var dependency = list.firstContext; - null !== dependency; - - ) { - if (dependency.context === Component) { - if (1 === hasContext.tag) { - dependency = createUpdate(renderLanes & -renderLanes); - dependency.tag = 2; - var updateQueue = hasContext.updateQueue; - if (null !== updateQueue) { - updateQueue = updateQueue.shared; - var pending = updateQueue.pending; - null === pending - ? (dependency.next = dependency) - : ((dependency.next = pending.next), - (pending.next = dependency)); - updateQueue.pending = dependency; - } - } - hasContext.lanes |= renderLanes; - dependency = hasContext.alternate; - null !== dependency && (dependency.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - hasContext.return, - renderLanes, - workInProgress - ); - list.lanes |= renderLanes; - break; - } - dependency = dependency.next; - } - } else if (10 === hasContext.tag) - newValue = - hasContext.type === workInProgress.type - ? null - : hasContext.child; - else if (18 === hasContext.tag) { - newValue = hasContext.return; - if (null === newValue) - throw Error( - "We just came from a parent so we must have had a parent. This is a bug in React." - ); - newValue.lanes |= renderLanes; - list = newValue.alternate; - null !== list && (list.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - newValue, - renderLanes, - workInProgress - ); - newValue = hasContext.sibling; - } else newValue = hasContext.child; - if (null !== newValue) newValue.return = hasContext; - else - for (newValue = hasContext; null !== newValue; ) { - if (newValue === workInProgress) { - newValue = null; - break; - } - hasContext = newValue.sibling; - if (null !== hasContext) { - hasContext.return = newValue.return; - newValue = hasContext; - break; - } - newValue = newValue.return; - } - hasContext = newValue; - } - reconcileChildren( - current, - workInProgress, - context.children, - renderLanes + })); + spawnedLane = 0 !== (didIncludeRenderPhaseUpdate.flags & 15990); + if (0 !== (didIncludeRenderPhaseUpdate.subtreeFlags & 15990) || spawnedLane) { + spawnedLane = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + remainingLanes = currentUpdatePriority; + currentUpdatePriority = 2; + var prevExecutionContext = executionContext; + executionContext |= 4; + ReactCurrentOwner.current = null; + commitBeforeMutationEffects(root, didIncludeRenderPhaseUpdate); + commitMutationEffectsOnFiber(didIncludeRenderPhaseUpdate, root); + root.current = didIncludeRenderPhaseUpdate; + commitLayoutEffectOnFiber( + root, + didIncludeRenderPhaseUpdate.alternate, + didIncludeRenderPhaseUpdate + ); + requestPaint(); + executionContext = prevExecutionContext; + currentUpdatePriority = remainingLanes; + ReactCurrentBatchConfig.transition = spawnedLane; + } else root.current = didIncludeRenderPhaseUpdate; + rootDoesHavePassiveEffects && + ((rootDoesHavePassiveEffects = !1), + (rootWithPendingPassiveEffects = root), + (pendingPassiveEffectsLanes = transitions)); + remainingLanes = root.pendingLanes; + 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); + onCommitRoot(didIncludeRenderPhaseUpdate.stateNode, renderPriorityLevel); + ensureRootIsScheduled(root); + if (null !== recoverableErrors) + for ( + renderPriorityLevel = root.onRecoverableError, + didIncludeRenderPhaseUpdate = 0; + didIncludeRenderPhaseUpdate < recoverableErrors.length; + didIncludeRenderPhaseUpdate++ + ) + (spawnedLane = recoverableErrors[didIncludeRenderPhaseUpdate]), + (remainingLanes = { + digest: spawnedLane.digest, + componentStack: spawnedLane.stack + }), + renderPriorityLevel(spawnedLane.value, remainingLanes); + if (hasUncaughtError) + throw ( + ((hasUncaughtError = !1), + (root = firstUncaughtError), + (firstUncaughtError = null), + root) + ); + 0 !== (pendingPassiveEffectsLanes & 3) && + 0 !== root.tag && + flushPassiveEffects(); + remainingLanes = root.pendingLanes; + 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) + ? root === rootWithNestedUpdates + ? nestedUpdateCount++ + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : (nestedUpdateCount = 0); + flushSyncWorkAcrossRoots_impl(!1); + return null; +} +function flushPassiveEffects() { + if (null !== rootWithPendingPassiveEffects) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), + prevTransition = ReactCurrentBatchConfig.transition, + previousPriority = currentUpdatePriority; + try { + ReactCurrentBatchConfig.transition = null; + currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; + if (null === rootWithPendingPassiveEffects) + var JSCompiler_inline_result = !1; + else { + renderPriority = rootWithPendingPassiveEffects; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = 0; + if (0 !== (executionContext & 6)) + throw Error("Cannot flush passive effects while already rendering."); + var prevExecutionContext = executionContext; + executionContext |= 4; + commitPassiveUnmountOnFiber(renderPriority.current); + commitPassiveMountOnFiber(renderPriority, renderPriority.current); + executionContext = prevExecutionContext; + flushSyncWorkAcrossRoots_impl(!1); + if ( + injectedHook && + "function" === typeof injectedHook.onPostCommitFiberRoot + ) + try { + injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); + } catch (err) {} + JSCompiler_inline_result = !0; + } + return JSCompiler_inline_result; + } finally { + (currentUpdatePriority = previousPriority), + (ReactCurrentBatchConfig.transition = prevTransition); + } + } + return !1; +} +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); + rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); + null !== rootFiber && + (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +} +function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { + if (3 === sourceFiber.tag) + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + else + for (; null !== nearestMountedAncestor; ) { + if (3 === nearestMountedAncestor.tag) { + captureCommitPhaseErrorOnRoot( + nearestMountedAncestor, + sourceFiber, + error ); - workInProgress = workInProgress.child; + break; + } else if (1 === nearestMountedAncestor.tag) { + var instance = nearestMountedAncestor.stateNode; + if ( + "function" === + typeof nearestMountedAncestor.type.getDerivedStateFromError || + ("function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + ) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createClassErrorUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + nearestMountedAncestor = enqueueUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + null !== nearestMountedAncestor && + (markRootUpdated$1(nearestMountedAncestor, 2), + ensureRootIsScheduled(nearestMountedAncestor)); + break; + } } - return workInProgress; - case 9: - return ( - (context = workInProgress.type), - (Component = workInProgress.pendingProps.children), - prepareToReadContext(workInProgress, renderLanes), - (context = readContext(context)), - (Component = Component(context)), - (workInProgress.flags |= 1), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 14: - return ( - (Component = workInProgress.type), - (context = resolveDefaultProps(Component, workInProgress.pendingProps)), - (context = resolveDefaultProps(Component.type, context)), - updateMemoComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 15: - return updateSimpleMemoComponent( - current, - workInProgress, - workInProgress.type, - workInProgress.pendingProps, - renderLanes - ); - case 17: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), - (workInProgress.tag = 1), - isContextProvider(Component) - ? ((current = !0), pushContextProvider(workInProgress)) - : (current = !1), - prepareToReadContext(workInProgress, renderLanes), - constructClassInstance(workInProgress, Component, context), - mountClassInstance(workInProgress, Component, context, renderLanes), - finishClassComponent( - null, - workInProgress, - Component, - !0, - current, - renderLanes - ) - ); + nearestMountedAncestor = nearestMountedAncestor.return; + } +} +function attachPingListener(root, wakeable, lanes) { + var pingCache = root.pingCache; + if (null === pingCache) { + pingCache = root.pingCache = new PossiblyWeakMap(); + var threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else + (threadIDs = pingCache.get(wakeable)), + void 0 === threadIDs && + ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); + threadIDs.has(lanes) || + ((workInProgressRootDidAttachPingListener = !0), + threadIDs.add(lanes), + (root = pingSuspendedRoot.bind(null, root, wakeable, lanes)), + wakeable.then(root, root)); +} +function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(wakeable); + root.pingedLanes |= root.suspendedLanes & pingedLanes; + workInProgressRoot === root && + (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && + (4 === workInProgressRootExitStatus || + (3 === workInProgressRootExitStatus && + (workInProgressRootRenderLanes & 62914560) === + workInProgressRootRenderLanes && + 300 > now() - globalMostRecentFallbackTime) + ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) + : (workInProgressRootPingedLanes |= pingedLanes)); + ensureRootIsScheduled(root); +} +function retryTimedOutBoundary(boundaryFiber, retryLane) { + 0 === retryLane && + (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); + boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + null !== boundaryFiber && + (markRootUpdated$1(boundaryFiber, retryLane), + ensureRootIsScheduled(boundaryFiber)); +} +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState, + retryLane = 0; + null !== suspenseState && (retryLane = suspenseState.retryLane); + retryTimedOutBoundary(boundaryFiber, retryLane); +} +function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = 0; + switch (boundaryFiber.tag) { + case 13: + var retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + null !== suspenseState && (retryLane = suspenseState.retryLane); + break; case 19: - return updateSuspenseListComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode; + break; case 22: - return updateOffscreenComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode._retryCache; + break; + default: + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -}; + null !== retryCache && retryCache.delete(wakeable); + retryTimedOutBoundary(boundaryFiber, retryLane); +} function scheduleCallback(priorityLevel, callback) { return scheduleCallback$2(priorityLevel, callback); } @@ -9061,6 +8760,7 @@ function createFiberFromTypeAndProps( case REACT_CONTEXT_TYPE: fiberTag = 9; break a; + case REACT_CONSUMER_TYPE: case REACT_FORWARD_REF_TYPE: fiberTag = 11; break a; @@ -9214,63 +8914,19 @@ function findHostInstance(component) { return null === component ? null : getPublicInstance(component.stateNode); } function updateContainer(element, container, parentComponent, callback) { - var current = container.current, - lane = requestUpdateLane(current); - a: if (parentComponent) { - parentComponent = parentComponent._reactInternals; - b: { - if ( - getNearestMountedFiber(parentComponent) !== parentComponent || - 1 !== parentComponent.tag - ) - throw Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); - var JSCompiler_inline_result = parentComponent; - do { - switch (JSCompiler_inline_result.tag) { - case 3: - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode.context; - break b; - case 1: - if (isContextProvider(JSCompiler_inline_result.type)) { - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode - .__reactInternalMemoizedMergedChildContext; - break b; - } - } - JSCompiler_inline_result = JSCompiler_inline_result.return; - } while (null !== JSCompiler_inline_result); - throw Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - if (1 === parentComponent.tag) { - var Component = parentComponent.type; - if (isContextProvider(Component)) { - parentComponent = processChildContext( - parentComponent, - Component, - JSCompiler_inline_result - ); - break a; - } - } - parentComponent = JSCompiler_inline_result; - } else parentComponent = emptyContextObject; + parentComponent = container.current; + var lane = requestUpdateLane(parentComponent); null === container.context - ? (container.context = parentComponent) - : (container.pendingContext = parentComponent); + ? (container.context = emptyContextObject) + : (container.pendingContext = emptyContextObject); container = createUpdate(lane); container.payload = { element: element }; callback = void 0 === callback ? null : callback; null !== callback && (container.callback = callback); - element = enqueueUpdate(current, container, lane); + element = enqueueUpdate(parentComponent, container, lane); null !== element && - (scheduleUpdateOnFiber(element, current, lane), - entangleTransitions(element, current, lane)); + (scheduleUpdateOnFiber(element, parentComponent, lane), + entangleTransitions(element, parentComponent, lane)); return lane; } function emptyFindFiberByHostInstance() { @@ -9318,10 +8974,10 @@ batchedUpdatesImpl = function (fn, a) { } }; var roots = new Map(), - devToolsConfig$jscomp$inline_1055 = { + devToolsConfig$jscomp$inline_1031 = { findFiberByHostInstance: getInstanceFromNode, bundleType: 0, - version: "18.3.0-canary-03d6f7cf0-20240209", + version: "18.3.0-canary-9372c6311-20240315", rendererPackageName: "react-native-renderer", rendererConfig: { getInspectorDataForInstance: getInspectorDataForInstance, @@ -9337,11 +8993,11 @@ var roots = new Map(), }.bind(null, findNodeHandle) } }; -var internals$jscomp$inline_1280 = { - bundleType: devToolsConfig$jscomp$inline_1055.bundleType, - version: devToolsConfig$jscomp$inline_1055.version, - rendererPackageName: devToolsConfig$jscomp$inline_1055.rendererPackageName, - rendererConfig: devToolsConfig$jscomp$inline_1055.rendererConfig, +var internals$jscomp$inline_1259 = { + bundleType: devToolsConfig$jscomp$inline_1031.bundleType, + version: devToolsConfig$jscomp$inline_1031.version, + rendererPackageName: devToolsConfig$jscomp$inline_1031.rendererPackageName, + rendererConfig: devToolsConfig$jscomp$inline_1031.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, @@ -9357,26 +9013,26 @@ var internals$jscomp$inline_1280 = { return null === fiber ? null : fiber.stateNode; }, findFiberByHostInstance: - devToolsConfig$jscomp$inline_1055.findFiberByHostInstance || + devToolsConfig$jscomp$inline_1031.findFiberByHostInstance || emptyFindFiberByHostInstance, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-canary-03d6f7cf0-20240209" + reconcilerVersion: "18.3.0-canary-9372c6311-20240315" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { - var hook$jscomp$inline_1281 = __REACT_DEVTOOLS_GLOBAL_HOOK__; + var hook$jscomp$inline_1260 = __REACT_DEVTOOLS_GLOBAL_HOOK__; if ( - !hook$jscomp$inline_1281.isDisabled && - hook$jscomp$inline_1281.supportsFiber + !hook$jscomp$inline_1260.isDisabled && + hook$jscomp$inline_1260.supportsFiber ) try { - (rendererID = hook$jscomp$inline_1281.inject( - internals$jscomp$inline_1280 + (rendererID = hook$jscomp$inline_1260.inject( + internals$jscomp$inline_1259 )), - (injectedHook = hook$jscomp$inline_1281); + (injectedHook = hook$jscomp$inline_1260); } catch (err) {} } exports.createPortal = function (children, containerTag) { diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js index 25d43a4a918176..0f5fab5c9e1422 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js @@ -8,7 +8,7 @@ * @nolint * @providesModule ReactFabric-profiling * @preventMunge - * @generated SignedSource<<51d6b522792ab4b6c4d286b5e09bbfcd>> + * @generated SignedSource<> */ "use strict"; @@ -19,69 +19,26 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), Scheduler = require("scheduler"), - React = require("react"); -function invokeGuardedCallbackImpl(name, func, context) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } -} -var hasError = !1, + React = require("react"), + isArrayImpl = Array.isArray, + hasError = !1, caughtError = null, - hasRethrowError = !1, - rethrowError = null, - reporter = { - onError: function (error) { - hasError = !0; - caughtError = error; - } - }; -function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = !1; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); -} -function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f -) { - invokeGuardedCallback.apply(this, arguments); - if (hasError) { - if (hasError) { - var error = caughtError; - hasError = !1; - caughtError = null; - } else - throw Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ); - hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); - } -} -var isArrayImpl = Array.isArray, getFiberCurrentPropsFromNode$1 = null, getInstanceFromNode$1 = null, getNodeFromInstance$1 = null; function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance$1(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event); + try { + listener(event); + } catch (error) { + hasError || ((hasError = !0), (caughtError = error)); + } event.currentTarget = null; } function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - if (isArrayImpl(dispatchListener)) - throw Error("executeDirectDispatch(...): Invalid `event`."); + if (isArrayImpl(dispatchListener)) throw Error("Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance$1(dispatchInstance) : null; @@ -340,9 +297,7 @@ var instrumentationCallback, }; function accumulate(current, next) { if (null == next) - throw Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); return null == current ? next : isArrayImpl(current) @@ -353,9 +308,7 @@ function accumulate(current, next) { } function accumulateInto(current, next) { if (null == next) - throw Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); if (null == current) return next; if (isArrayImpl(current)) { if (isArrayImpl(next)) return current.push.apply(current, next), current; @@ -944,7 +897,7 @@ eventPluginOrder = Array.prototype.slice.call([ "ReactNativeBridgeEventPlugin" ]); recomputePluginOrdering(); -var injectedNamesToPlugins$jscomp$inline_251 = { +var injectedNamesToPlugins$jscomp$inline_246 = { ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: { eventTypes: {}, @@ -990,32 +943,32 @@ var injectedNamesToPlugins$jscomp$inline_251 = { } } }, - isOrderingDirty$jscomp$inline_252 = !1, - pluginName$jscomp$inline_253; -for (pluginName$jscomp$inline_253 in injectedNamesToPlugins$jscomp$inline_251) + isOrderingDirty$jscomp$inline_247 = !1, + pluginName$jscomp$inline_248; +for (pluginName$jscomp$inline_248 in injectedNamesToPlugins$jscomp$inline_246) if ( - injectedNamesToPlugins$jscomp$inline_251.hasOwnProperty( - pluginName$jscomp$inline_253 + injectedNamesToPlugins$jscomp$inline_246.hasOwnProperty( + pluginName$jscomp$inline_248 ) ) { - var pluginModule$jscomp$inline_254 = - injectedNamesToPlugins$jscomp$inline_251[pluginName$jscomp$inline_253]; + var pluginModule$jscomp$inline_249 = + injectedNamesToPlugins$jscomp$inline_246[pluginName$jscomp$inline_248]; if ( - !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_253) || - namesToPlugins[pluginName$jscomp$inline_253] !== - pluginModule$jscomp$inline_254 + !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_248) || + namesToPlugins[pluginName$jscomp$inline_248] !== + pluginModule$jscomp$inline_249 ) { - if (namesToPlugins[pluginName$jscomp$inline_253]) + if (namesToPlugins[pluginName$jscomp$inline_248]) throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - (pluginName$jscomp$inline_253 + "`.") + (pluginName$jscomp$inline_248 + "`.") ); - namesToPlugins[pluginName$jscomp$inline_253] = - pluginModule$jscomp$inline_254; - isOrderingDirty$jscomp$inline_252 = !0; + namesToPlugins[pluginName$jscomp$inline_248] = + pluginModule$jscomp$inline_249; + isOrderingDirty$jscomp$inline_247 = !0; } } -isOrderingDirty$jscomp$inline_252 && recomputePluginOrdering(); +isOrderingDirty$jscomp$inline_247 && recomputePluginOrdering(); var emptyObject = {}, removedKeys = null, removedKeyCount = 0, @@ -1308,12 +1261,9 @@ function dispatchEvent(target, topLevelType, nativeEvent) { throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); - if (hasRethrowError) + if (hasError) throw ( - ((event = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - event) + ((event = caughtError), (hasError = !1), (caughtError = null), event) ); } }); @@ -1513,7 +1463,7 @@ function createLaneMap(initial) { for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial); return laneMap; } -function markRootUpdated(root, updateLane) { +function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; 268435456 !== updateLane && ((root.suspendedLanes = 0), (root.pingedLanes = 0)); @@ -1676,6 +1626,11 @@ function cloneHiddenInstance(instance) { canonical: instance.canonical }; } +var supportsMicrotasks = + "undefined" !== typeof RN$enableMicrotasksInReact && + !!RN$enableMicrotasksInReact, + scheduleMicrotask = + "function" === typeof queueMicrotask ? queueMicrotask : scheduleTimeout; function getInstanceFromNode(node) { return null != node.canonical && null != node.canonical.internalInstanceHandle ? node.canonical.internalInstanceHandle @@ -1714,6 +1669,7 @@ var REACT_ELEMENT_TYPE = Symbol.for("react.element"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), @@ -1734,115 +1690,7 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } -var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); -function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE - ? null - : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if ("object" === typeof type) - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - return (type.displayName || "Context") + ".Consumer"; - case REACT_PROVIDER_TYPE: - return (type._context.displayName || "Context") + ".Provider"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || - ((type = innerType.displayName || innerType.name || ""), - (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); - return type; - case REACT_MEMO_TYPE: - return ( - (innerType = type.displayName || null), - null !== innerType - ? innerType - : getComponentNameFromType(type.type) || "Memo" - ); - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) {} - } - return null; -} -function getComponentNameFromFiber(fiber) { - var type = fiber.type; - switch (fiber.tag) { - case 24: - return "Cache"; - case 9: - return (type.displayName || "Context") + ".Consumer"; - case 10: - return (type._context.displayName || "Context") + ".Provider"; - case 18: - return "DehydratedFragment"; - case 11: - return ( - (fiber = type.render), - (fiber = fiber.displayName || fiber.name || ""), - type.displayName || - ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef") - ); - case 7: - return "Fragment"; - case 26: - case 27: - case 5: - return type; - case 4: - return "Portal"; - case 3: - return "Root"; - case 6: - return "Text"; - case 16: - return getComponentNameFromType(type); - case 8: - return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode"; - case 22: - return "Offscreen"; - case 12: - return "Profiler"; - case 21: - return "Scope"; - case 13: - return "Suspense"; - case 19: - return "SuspenseList"; - case 25: - return "TracingMarker"; - case 1: - case 0: - case 17: - case 2: - case 14: - case 15: - if ("function" === typeof type) - return type.displayName || type.name || null; - if ("string" === typeof type) return type; - } - return null; -} +Symbol.for("react.client.reference"); function getNearestMountedFiber(fiber) { var node = fiber, nearestMounted = fiber; @@ -1951,18 +1799,7 @@ function findCurrentHostFiberImpl(node) { } return null; } -function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - ownerName && (sourceInfo = " (created by " + ownerName + ")"); - return "\n in " + (name || "Unknown") + sourceInfo; -} -function describeFunctionComponentFrame(fn) { - return fn - ? describeComponentFrame(fn.displayName || fn.name || null, null) - : ""; -} -var hasOwnProperty = Object.prototype.hasOwnProperty, - valueStack = [], +var valueStack = [], index = -1; function createCursor(defaultValue) { return { current: defaultValue }; @@ -1976,89 +1813,7 @@ function push(cursor, value) { valueStack[index] = cursor.current; cursor.current = value; } -var emptyContextObject = {}, - contextStackCursor$1 = createCursor(emptyContextObject), - didPerformWorkStackCursor = createCursor(!1), - previousContext = emptyContextObject; -function getMaskedContext(workInProgress, unmaskedContext) { - var contextTypes = workInProgress.type.contextTypes; - if (!contextTypes) return emptyContextObject; - var instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) - return instance.__reactInternalMemoizedMaskedChildContext; - var context = {}, - key; - for (key in contextTypes) context[key] = unmaskedContext[key]; - instance && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); - return context; -} -function isContextProvider(type) { - type = type.childContextTypes; - return null !== type && void 0 !== type; -} -function popContext() { - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); -} -function pushTopLevelContextObject(fiber, context, didChange) { - if (contextStackCursor$1.current !== emptyContextObject) - throw Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); - push(contextStackCursor$1, context); - push(didPerformWorkStackCursor, didChange); -} -function processChildContext(fiber, type, parentContext) { - var instance = fiber.stateNode; - type = type.childContextTypes; - if ("function" !== typeof instance.getChildContext) return parentContext; - instance = instance.getChildContext(); - for (var contextKey in instance) - if (!(contextKey in type)) - throw Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - return assign({}, parentContext, instance); -} -function pushContextProvider(workInProgress) { - workInProgress = - ((workInProgress = workInProgress.stateNode) && - workInProgress.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current); - return !0; -} -function invalidateContextProvider(workInProgress, type, didChange) { - var instance = workInProgress.stateNode; - if (!instance) - throw Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ); - didChange - ? ((workInProgress = processChildContext( - workInProgress, - type, - previousContext - )), - (instance.__reactInternalMemoizedMergedChildContext = workInProgress), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - push(contextStackCursor$1, workInProgress)) - : pop(didPerformWorkStackCursor); - push(didPerformWorkStackCursor, didChange); -} +var emptyContextObject = {}; function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } @@ -2195,7 +1950,7 @@ function ensureRootIsScheduled(root) { mightHavePendingSyncWork = !0; didScheduleMicrotask || ((didScheduleMicrotask = !0), - scheduleCallback$2(ImmediatePriority, processRootScheduleInMicrotask)); + scheduleImmediateTask(processRootScheduleInMicrotask)); scheduleTaskForRootDuringMicrotask(root, now$1()); } function flushSyncWorkAcrossRoots_impl(onlyLegacy) { @@ -2267,6 +2022,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { workInProgressRootRenderLanes$11, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane )); } @@ -2284,8 +2040,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { if ("function" === typeof AggregateError) throw new AggregateError(errors); for (onlyLegacy = 1; onlyLegacy < errors.length; onlyLegacy++) - (didPerformSomeWork = throwError.bind(null, errors[onlyLegacy])), - scheduleCallback$2(ImmediatePriority, didPerformSomeWork); + scheduleImmediateTask(throwError.bind(null, errors[onlyLegacy])); } throw errors[0]; } @@ -2385,6 +2140,15 @@ function scheduleTaskForRootDuringMicrotask(root, currentTime) { root.callbackNode = suspendedLanes; return currentTime; } +function scheduleImmediateTask(cb) { + supportsMicrotasks + ? scheduleMicrotask(function () { + 0 !== (executionContext & 6) + ? scheduleCallback$2(ImmediatePriority, cb) + : cb(); + }) + : scheduleCallback$2(ImmediatePriority, cb); +} var hasForceUpdate = !1; function initializeUpdateQueue(fiber) { fiber.updateQueue = { @@ -2621,6 +2385,7 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { if (objectIs(objA, objB)) return !0; if ( @@ -2643,6 +2408,16 @@ function shallowEqual(objA, objB) { } return !0; } +function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + ownerName && (sourceInfo = " (created by " + ownerName + ")"); + return "\n in " + (name || "Unknown") + sourceInfo; +} +function describeFunctionComponentFrame(fn) { + return fn + ? describeComponentFrame(fn.displayName || fn.name || null, null) + : ""; +} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -2667,6 +2442,18 @@ function describeFiber(fiber) { return ""; } } +function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ""; + do + (info += describeFiber(workInProgress)), + (workInProgress = workInProgress.return); + while (workInProgress); + return info; + } catch (x) { + return "\nError generating stack: " + x.message + "\n" + x.stack; + } +} var SuspenseException = Error( "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`" ), @@ -2719,16 +2506,16 @@ function trackUsedThenable(thenableState, thenable, index) { } } ); - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw ( - ((thenableState = thenable.reason), - checkIfUseWrappedInAsyncCatch(thenableState), - thenableState) - ); - } + } + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw ( + ((thenableState = thenable.reason), + checkIfUseWrappedInAsyncCatch(thenableState), + thenableState) + ); } suspendedThenable = thenable; throw SuspenseException; @@ -2758,56 +2545,54 @@ function unwrapThenable(thenable) { null === thenableState$1 && (thenableState$1 = []); return trackUsedThenable(thenableState$1, thenable, index); } -function coerceRef(returnFiber, current, element) { - returnFiber = element.ref; - if ( - null !== returnFiber && - "function" !== typeof returnFiber && - "object" !== typeof returnFiber - ) { - if (element._owner) { - element = element._owner; - if (element) { - if (1 !== element.tag) - throw Error( - "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref" - ); - var inst = element.stateNode; - } - if (!inst) - throw Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ); - var resolvedInst = inst, - stringRef = "" + returnFiber; - if ( - null !== current && - null !== current.ref && - "function" === typeof current.ref && - current.ref._stringRef === stringRef - ) - return current.ref; - current = function (value) { - var refs = resolvedInst.refs; - null === value ? delete refs[stringRef] : (refs[stringRef] = value); - }; - current._stringRef = stringRef; - return current; - } - if ("string" !== typeof returnFiber) - throw Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - if (!element._owner) - throw Error( - "Element ref was specified as a string (" + - returnFiber + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information." - ); +function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef +) { + function ref(value) { + var refs = inst.refs; + null === value ? delete refs[stringRef] : (refs[stringRef] = value); } - return returnFiber; + var stringRef = "" + mixedRef; + returnFiber = element._owner; + if (!returnFiber) + throw Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://react.dev/link/refs-must-have-owner for more information." + ); + if (1 !== returnFiber.tag) + throw Error( + "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://react.dev/link/strict-mode-string-ref" + ); + var inst = returnFiber.stateNode; + if (!inst) + throw Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + if ( + null !== current && + null !== current.ref && + "function" === typeof current.ref && + current.ref._stringRef === stringRef + ) + return current.ref; + ref._stringRef = stringRef; + return ref; +} +function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef = element.ref; + returnFiber = + "string" === typeof mixedRef || + "number" === typeof mixedRef || + "boolean" === typeof mixedRef + ? convertStringRefToCallbackRef(returnFiber, current, element, mixedRef) + : mixedRef; + workInProgress.ref = returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { returnFiber = Object.prototype.toString.call(newChild); @@ -2839,13 +2624,13 @@ function createChildReconciler(shouldTrackSideEffects) { (currentFirstChild = currentFirstChild.sibling); return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { - for (returnFiber = new Map(); null !== currentFirstChild; ) + function mapRemainingChildren(currentFirstChild) { + for (var existingChildren = new Map(); null !== currentFirstChild; ) null !== currentFirstChild.key - ? returnFiber.set(currentFirstChild.key, currentFirstChild) - : returnFiber.set(currentFirstChild.index, currentFirstChild), + ? existingChildren.set(currentFirstChild.key, currentFirstChild) + : existingChildren.set(currentFirstChild.index, currentFirstChild), (currentFirstChild = currentFirstChild.sibling); - return returnFiber; + return existingChildren; } function useFiber(fiber, pendingProps) { fiber = createWorkInProgress(fiber, pendingProps); @@ -2905,7 +2690,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) return ( (lanes = useFiber(current, element.props)), - (lanes.ref = coerceRef(returnFiber, current, element)), + coerceRef(returnFiber, current, lanes, element), (lanes.return = returnFiber), lanes ); @@ -2917,7 +2702,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes ); - lanes.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, lanes, element); lanes.return = returnFiber; return lanes; } @@ -2979,7 +2764,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef(returnFiber, null, newChild)), + coerceRef(returnFiber, null, lanes, newChild), (lanes.return = returnFiber), lanes ); @@ -3013,7 +2798,7 @@ function createChildReconciler(shouldTrackSideEffects) { if (newChild.$$typeof === REACT_CONTEXT_TYPE) return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3060,7 +2845,7 @@ function createChildReconciler(shouldTrackSideEffects) { return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3128,7 +2913,7 @@ function createChildReconciler(shouldTrackSideEffects) { existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3194,7 +2979,7 @@ function createChildReconciler(shouldTrackSideEffects) { return resultingFirstChild; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++ ) @@ -3282,7 +3067,7 @@ function createChildReconciler(shouldTrackSideEffects) { return iteratorFn; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildrenIterable.next() ) @@ -3344,11 +3129,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) { deleteRemainingChildren(returnFiber, child.sibling); currentFirstChild = useFiber(child, newChild.props); - currentFirstChild.ref = coerceRef( - returnFiber, - child, - newChild - ); + coerceRef(returnFiber, child, currentFirstChild, newChild); currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; @@ -3375,11 +3156,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef( - returnFiber, - currentFirstChild, - newChild - )), + coerceRef(returnFiber, currentFirstChild, lanes, newChild), (lanes.return = returnFiber), (returnFiber = lanes)); } @@ -3425,7 +3202,7 @@ function createChildReconciler(shouldTrackSideEffects) { case REACT_LAZY_TYPE: return ( (child = newChild._init), - reconcileChildFibers( + reconcileChildFibersImpl( returnFiber, currentFirstChild, child(newChild._payload), @@ -3458,7 +3235,7 @@ function createChildReconciler(shouldTrackSideEffects) { return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3482,12 +3259,7 @@ function createChildReconciler(shouldTrackSideEffects) { placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild); } - function reconcileChildFibers( - returnFiber, - currentFirstChild, - newChild, - lanes - ) { + return function (returnFiber, currentFirstChild, newChild, lanes) { thenableIndexCounter$1 = 0; returnFiber = reconcileChildFibersImpl( returnFiber, @@ -3497,8 +3269,7 @@ function createChildReconciler(shouldTrackSideEffects) { ); thenableState$1 = null; return returnFiber; - } - return reconcileChildFibers; + }; } var reconcileChildFibers = createChildReconciler(!0), mountChildFibers = createChildReconciler(!1), @@ -3591,7 +3362,7 @@ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, globalClientIdCounter = 0; function throwInvalidHookError() { throw Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } function areHookInputsEqual(nextDeps, prevDeps) { @@ -4530,30 +4301,17 @@ function checkShouldComponentUpdate( : !0; } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = !1, - unmaskedContext = emptyContextObject; - var context = ctor.contextType; - "object" === typeof context && null !== context - ? (context = readContext(context)) - : ((unmaskedContext = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (isLegacyContextConsumer = ctor.contextTypes), - (context = (isLegacyContextConsumer = - null !== isLegacyContextConsumer && void 0 !== isLegacyContextConsumer) - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject)); + var context = emptyContextObject, + contextType = ctor.contextType; + "object" === typeof contextType && + null !== contextType && + (context = readContext(contextType)); ctor = new ctor(props, context); workInProgress.memoizedState = null !== ctor.state && void 0 !== ctor.state ? ctor.state : null; ctor.updater = classComponentUpdater; workInProgress.stateNode = ctor; ctor._reactInternals = workInProgress; - isLegacyContextConsumer && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); return ctor; } function callComponentWillReceiveProps( @@ -4577,12 +4335,10 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { instance.refs = {}; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; - "object" === typeof contextType && null !== contextType - ? (instance.context = readContext(contextType)) - : ((contextType = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (instance.context = getMaskedContext(workInProgress, contextType))); + instance.context = + "object" === typeof contextType && null !== contextType + ? readContext(contextType) + : emptyContextObject; instance.state = workInProgress.memoizedState; contextType = ctor.getDerivedStateFromProps; "function" === typeof contextType && @@ -4604,22 +4360,23 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { "function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308); } +var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { - try { - var info = "", - node = source; - do (info += describeFiber(node)), (node = node.return); - while (node); - var JSCompiler_inline_result = info; - } catch (x) { - JSCompiler_inline_result = - "\nError generating stack: " + x.message + "\n" + x.stack; - } + if ("object" === typeof value && null !== value) { + var stack = CapturedStacks.get(value); + "string" !== typeof stack && + ((stack = getStackByFiberInDevAndProd(source)), + CapturedStacks.set(value, stack)); + } else stack = getStackByFiberInDevAndProd(source); + return { value: value, source: source, stack: stack, digest: null }; +} +function createCapturedValueFromError(value, digest, stack) { + "string" === typeof stack && CapturedStacks.set(value, stack); return { value: value, - source: source, - stack: JSCompiler_inline_result, - digest: null + source: null, + stack: null != stack ? stack : null, + digest: null != digest ? digest : null }; } if ( @@ -4966,7 +4723,7 @@ function updateOffscreenComponent(current, workInProgress, renderLanes) { nextChildren = nextProps.children, nextIsDetached = 0 !== (workInProgress.stateNode._pendingVisibility & 2), prevState = null !== current ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if ("hidden" === nextProps.mode || nextIsDetached) { if (0 !== (workInProgress.flags & 128)) { renderLanes = @@ -5020,13 +4777,20 @@ function deferHiddenOffscreenComponent(current, workInProgress, nextBaseLanes) { pushOffscreenSuspenseHandler(workInProgress); return null; } -function markRef$1(current, workInProgress) { +function markRef(current, workInProgress) { var ref = workInProgress.ref; - if ( - (null === current && null !== ref) || - (null !== current && current.ref !== ref) - ) - (workInProgress.flags |= 512), (workInProgress.flags |= 2097152); + if (null === ref) + null !== current && + null !== current.ref && + (workInProgress.flags |= 2097664); + else { + if ("function" !== typeof ref && "object" !== typeof ref) + throw Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + if (null === current || current.ref !== ref) + workInProgress.flags |= 2097664; + } } function updateFunctionComponent( current, @@ -5035,17 +4799,13 @@ function updateFunctionComponent( nextProps, renderLanes ) { - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(workInProgress, context); prepareToReadContext(workInProgress, renderLanes); Component = renderWithHooks( current, workInProgress, Component, nextProps, - context, + void 0, renderLanes ); if (null !== current && !didReceiveUpdate) @@ -5089,10 +4849,6 @@ function updateClassComponent( nextProps, renderLanes ) { - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; prepareToReadContext(workInProgress, renderLanes); if (null === workInProgress.stateNode) resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), @@ -5104,36 +4860,30 @@ function updateClassComponent( oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context, - contextType = Component.contextType; - "object" === typeof contextType && null !== contextType - ? (contextType = readContext(contextType)) - : ((contextType = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (contextType = getMaskedContext(workInProgress, contextType))); - var getDerivedStateFromProps = Component.getDerivedStateFromProps, - hasNewLifecycles = - "function" === typeof getDerivedStateFromProps || - "function" === typeof instance.getSnapshotBeforeUpdate; - hasNewLifecycles || + contextType = Component.contextType, + nextContext = emptyContextObject; + "object" === typeof contextType && + null !== contextType && + (nextContext = readContext(contextType)); + var getDerivedStateFromProps = Component.getDerivedStateFromProps; + (contextType = + "function" === typeof getDerivedStateFromProps || + "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== nextProps || oldContext !== contextType) && + ((oldProps !== nextProps || oldContext !== nextContext) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - contextType + nextContext )); hasForceUpdate = !1; var oldState = workInProgress.memoizedState; instance.state = oldState; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); oldContext = workInProgress.memoizedState; - oldProps !== nextProps || - oldState !== oldContext || - didPerformWorkStackCursor.current || - hasForceUpdate + oldProps !== nextProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps( workInProgress, @@ -5151,9 +4901,9 @@ function updateClassComponent( nextProps, oldState, oldContext, - contextType + nextContext )) - ? (hasNewLifecycles || + ? (contextType || ("function" !== typeof instance.UNSAFE_componentWillMount && "function" !== typeof instance.componentWillMount) || ("function" === typeof instance.componentWillMount && @@ -5168,7 +4918,7 @@ function updateClassComponent( (workInProgress.memoizedState = oldContext)), (instance.props = nextProps), (instance.state = oldContext), - (instance.context = contextType), + (instance.context = nextContext), (nextProps = oldProps)) : ("function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308), @@ -5176,48 +4926,46 @@ function updateClassComponent( } else { instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); - oldProps = workInProgress.memoizedProps; + nextContext = workInProgress.memoizedProps; contextType = workInProgress.type === workInProgress.elementType - ? oldProps - : resolveDefaultProps(workInProgress.type, oldProps); + ? nextContext + : resolveDefaultProps(workInProgress.type, nextContext); instance.props = contextType; - hasNewLifecycles = workInProgress.pendingProps; - oldState = instance.context; + getDerivedStateFromProps = workInProgress.pendingProps; + var oldContext$jscomp$0 = instance.context; oldContext = Component.contextType; - "object" === typeof oldContext && null !== oldContext - ? (oldContext = readContext(oldContext)) - : ((oldContext = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (oldContext = getMaskedContext(workInProgress, oldContext))); - var getDerivedStateFromProps$jscomp$0 = Component.getDerivedStateFromProps; - (getDerivedStateFromProps = - "function" === typeof getDerivedStateFromProps$jscomp$0 || + oldProps = emptyContextObject; + "object" === typeof oldContext && + null !== oldContext && + (oldProps = readContext(oldContext)); + oldState = Component.getDerivedStateFromProps; + (oldContext = + "function" === typeof oldState || "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== hasNewLifecycles || oldState !== oldContext) && + ((nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== oldProps) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - oldContext + oldProps )); hasForceUpdate = !1; - oldState = workInProgress.memoizedState; - instance.state = oldState; + oldContext$jscomp$0 = workInProgress.memoizedState; + instance.state = oldContext$jscomp$0; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); var newState = workInProgress.memoizedState; - oldProps !== hasNewLifecycles || - oldState !== newState || - didPerformWorkStackCursor.current || + nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== newState || hasForceUpdate - ? ("function" === typeof getDerivedStateFromProps$jscomp$0 && + ? ("function" === typeof oldState && (applyDerivedStateFromProps( workInProgress, Component, - getDerivedStateFromProps$jscomp$0, + oldState, nextProps ), (newState = workInProgress.memoizedState)), @@ -5228,47 +4976,47 @@ function updateClassComponent( Component, contextType, nextProps, - oldState, + oldContext$jscomp$0, newState, - oldContext + oldProps ) || !1) - ? (getDerivedStateFromProps || + ? (oldContext || ("function" !== typeof instance.UNSAFE_componentWillUpdate && "function" !== typeof instance.componentWillUpdate) || ("function" === typeof instance.componentWillUpdate && - instance.componentWillUpdate(nextProps, newState, oldContext), + instance.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof instance.UNSAFE_componentWillUpdate && instance.UNSAFE_componentWillUpdate( nextProps, newState, - oldContext + oldProps )), "function" === typeof instance.componentDidUpdate && (workInProgress.flags |= 4), "function" === typeof instance.getSnapshotBeforeUpdate && (workInProgress.flags |= 1024)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (workInProgress.memoizedProps = nextProps), (workInProgress.memoizedState = newState)), (instance.props = nextProps), (instance.state = newState), - (instance.context = oldContext), + (instance.context = oldProps), (nextProps = contextType)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (nextProps = !1)); } @@ -5277,7 +5025,7 @@ function updateClassComponent( workInProgress, Component, nextProps, - hasContext, + !1, renderLanes ); } @@ -5289,26 +5037,18 @@ function finishClassComponent( hasContext, renderLanes ) { - markRef$1(current, workInProgress); - var didCaptureError = 0 !== (workInProgress.flags & 128); - if (!shouldUpdate && !didCaptureError) - return ( - hasContext && invalidateContextProvider(workInProgress, Component, !1), - bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) - ); + markRef(current, workInProgress); + hasContext = 0 !== (workInProgress.flags & 128); + if (!shouldUpdate && !hasContext) + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); shouldUpdate = workInProgress.stateNode; ReactCurrentOwner$1.current = workInProgress; - if ( - didCaptureError && - "function" !== typeof Component.getDerivedStateFromError - ) { - var nextChildren = null; - profilerStartTime = -1; - } else nextChildren = shouldUpdate.render(); + hasContext && "function" !== typeof Component.getDerivedStateFromError + ? ((Component = null), (profilerStartTime = -1)) + : (Component = shouldUpdate.render()); workInProgress.flags |= 1; - null !== current && didCaptureError - ? ((didCaptureError = nextChildren), - (workInProgress.child = reconcileChildFibers( + null !== current && hasContext + ? ((workInProgress.child = reconcileChildFibers( workInProgress, current.child, null, @@ -5317,26 +5057,13 @@ function finishClassComponent( (workInProgress.child = reconcileChildFibers( workInProgress, null, - didCaptureError, + Component, renderLanes ))) - : reconcileChildren(current, workInProgress, nextChildren, renderLanes); + : reconcileChildren(current, workInProgress, Component, renderLanes); workInProgress.memoizedState = shouldUpdate.state; - hasContext && invalidateContextProvider(workInProgress, Component, !0); return workInProgress.child; } -function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - root.pendingContext - ? pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ) - : root.context && - pushTopLevelContextObject(workInProgress, root.context, !1); - pushHostContainer(workInProgress, root.containerInfo); -} var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: null }; @@ -5540,18 +5267,16 @@ function updateDehydratedSuspenseComponent( return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags &= -257), + (didPrimaryChildrenDefer = createCapturedValueFromError( + Error( + "There was an error while hydrating this Suspense boundary. Switched to client rendering." + ) + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: Error( - "There was an error while hydrating this Suspense boundary. Switched to client rendering." - ), - source: null, - stack: null, - digest: null - } + didPrimaryChildrenDefer ) ); if (null !== workInProgress.memoizedState) @@ -5608,17 +5333,16 @@ function updateDehydratedSuspenseComponent( "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering." )), (suspenseState.digest = didPrimaryChildrenDefer), + (didPrimaryChildrenDefer = createCapturedValueFromError( + suspenseState, + didPrimaryChildrenDefer, + void 0 + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: suspenseState, - source: null, - stack: null, - digest: - null != didPrimaryChildrenDefer ? didPrimaryChildrenDefer : null - } + didPrimaryChildrenDefer ) ); didPrimaryChildrenDefer = 0 !== (renderLanes & current.childLanes); @@ -5849,36 +5573,32 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ) { switch (workInProgress.tag) { case 3: - pushHostRootContext(workInProgress); + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 27: case 5: pushHostContext(workInProgress); break; - case 1: - isContextProvider(workInProgress.type) && - pushContextProvider(workInProgress); - break; case 4: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 10: - var context = workInProgress.type._context, - nextValue = workInProgress.memoizedProps.value; + var newValue = workInProgress.memoizedProps.value, + context = workInProgress.type._context; push(valueCursor, context._currentValue2); - context._currentValue2 = nextValue; + context._currentValue2 = newValue; break; case 12: 0 !== (renderLanes & workInProgress.childLanes) && (workInProgress.flags |= 4); - context = workInProgress.stateNode; - context.effectDuration = 0; - context.passiveEffectDuration = 0; + newValue = workInProgress.stateNode; + newValue.effectDuration = 0; + newValue.passiveEffectDuration = 0; break; case 13: - context = workInProgress.memoizedState; - if (null !== context) { - if (null !== context.dehydrated) + newValue = workInProgress.memoizedState; + if (null !== newValue) { + if (null !== newValue.dehydrated) return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags |= 128), @@ -5897,9 +5617,9 @@ function attemptEarlyBailoutIfNoScheduledUpdate( pushPrimaryTreeSuspenseHandler(workInProgress); break; case 19: - context = 0 !== (renderLanes & workInProgress.childLanes); + newValue = 0 !== (renderLanes & workInProgress.childLanes); if (0 !== (current.flags & 128)) { - if (context) + if (newValue) return updateSuspenseListComponent( current, workInProgress, @@ -5907,13 +5627,13 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ); workInProgress.flags |= 128; } - nextValue = workInProgress.memoizedState; - null !== nextValue && - ((nextValue.rendering = null), - (nextValue.tail = null), - (nextValue.lastEffect = null)); + context = workInProgress.memoizedState; + null !== context && + ((context.rendering = null), + (context.tail = null), + (context.lastEffect = null)); push(suspenseStackCursor, suspenseStackCursor.current); - if (context) break; + if (newValue) break; else return null; case 22: case 23: @@ -5924,601 +5644,409 @@ function attemptEarlyBailoutIfNoScheduledUpdate( } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } -var valueCursor = createCursor(null), - currentlyRenderingFiber = null, - lastContextDependency = null, - lastFullyObservedContext = null; -function resetContextDependencies() { - lastFullyObservedContext = - lastContextDependency = - currentlyRenderingFiber = - null; -} -function popProvider(context) { - context._currentValue2 = valueCursor.current; - pop(valueCursor); -} -function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - for (; null !== parent; ) { - var alternate = parent.alternate; - (parent.childLanes & renderLanes) !== renderLanes - ? ((parent.childLanes |= renderLanes), - null !== alternate && (alternate.childLanes |= renderLanes)) - : null !== alternate && - (alternate.childLanes & renderLanes) !== renderLanes && - (alternate.childLanes |= renderLanes); - if (parent === propagationRoot) break; - parent = parent.return; - } -} -function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastFullyObservedContext = lastContextDependency = null; - workInProgress = workInProgress.dependencies; - null !== workInProgress && - null !== workInProgress.firstContext && - (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), - (workInProgress.firstContext = null)); -} -function readContext(context) { - return readContextForConsumer(currentlyRenderingFiber, context); -} -function readContextDuringReconcilation(consumer, context, renderLanes) { - null === currentlyRenderingFiber && - prepareToReadContext(consumer, renderLanes); - return readContextForConsumer(consumer, context); -} -function readContextForConsumer(consumer, context) { - var value = context._currentValue2; - if (lastFullyObservedContext !== context) - if ( - ((context = { context: context, memoizedValue: value, next: null }), - null === lastContextDependency) - ) { - if (null === consumer) - throw Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." +function beginWork(current, workInProgress, renderLanes) { + if (null !== current) + if (current.memoizedProps !== workInProgress.pendingProps) + didReceiveUpdate = !0; + else { + if ( + 0 === (current.lanes & renderLanes) && + 0 === (workInProgress.flags & 128) + ) + return ( + (didReceiveUpdate = !1), + attemptEarlyBailoutIfNoScheduledUpdate( + current, + workInProgress, + renderLanes + ) ); - lastContextDependency = context; - consumer.dependencies = { lanes: 0, firstContext: context }; - } else lastContextDependency = lastContextDependency.next = context; - return value; -} -var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; -function handleAsyncAction() {} -function doesRequireClone(current, completedWork) { - if (null !== current && current.child === completedWork.child) return !1; - if (0 !== (completedWork.flags & 16)) return !0; - for (current = completedWork.child; null !== current; ) { - if (0 !== (current.flags & 12854) || 0 !== (current.subtreeFlags & 12854)) - return !0; - current = current.sibling; - } - return !1; -} -function appendAllChildren( - parent, - workInProgress, - needsVisibilityToggle, - isHidden -) { - for (var node = workInProgress.child; null !== node; ) { - if (5 === node.tag) { - var instance = node.stateNode; - needsVisibilityToggle && - isHidden && - (instance = cloneHiddenInstance(instance)); - appendChildNode(parent.node, instance.node); - } else if (6 === node.tag) { - instance = node.stateNode; - if (needsVisibilityToggle && isHidden) - throw Error("Not yet implemented."); - appendChildNode(parent.node, instance.node); - } else if (4 !== node.tag) - if (22 === node.tag && null !== node.memoizedState) - (instance = node.child), - null !== instance && (instance.return = node), - appendAllChildren(parent, node, !0, !0); - else if (null !== node.child) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === workInProgress) return; - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } -} -function appendAllChildrenToContainer( - containerChildSet, - workInProgress, - needsVisibilityToggle, - isHidden -) { - for (var node = workInProgress.child; null !== node; ) { - if (5 === node.tag) { - var instance = node.stateNode; - needsVisibilityToggle && - isHidden && - (instance = cloneHiddenInstance(instance)); - appendChildNodeToSet(containerChildSet, instance.node); - } else if (6 === node.tag) { - instance = node.stateNode; - if (needsVisibilityToggle && isHidden) - throw Error("Not yet implemented."); - appendChildNodeToSet(containerChildSet, instance.node); - } else if (4 !== node.tag) - if (22 === node.tag && null !== node.memoizedState) - (instance = node.child), - null !== instance && (instance.return = node), - appendAllChildrenToContainer( - containerChildSet, - node, - !( - null !== node.memoizedProps && - "manual" === node.memoizedProps.mode - ), - !0 - ); - else if (null !== node.child) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === workInProgress) return; - node = node.return; + didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; } - node.sibling.return = node.return; - node = node.sibling; - } -} -function updateHostContainer(current, workInProgress) { - if (doesRequireClone(current, workInProgress)) { - current = workInProgress.stateNode; - var container = current.containerInfo, - newChildSet = createChildNodeSet(); - appendAllChildrenToContainer(newChildSet, workInProgress, !1, !1); - current.pendingChildren = newChildSet; - workInProgress.flags |= 4; - completeRoot(container, newChildSet); - } -} -function scheduleRetryEffect(workInProgress, retryQueue) { - null !== retryQueue - ? (workInProgress.flags |= 4) - : workInProgress.flags & 16384 && - ((retryQueue = - 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), - (workInProgress.lanes |= retryQueue)); -} -function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - switch (renderState.tailMode) { - case "hidden": - hasRenderedATailFallback = renderState.tail; - for (var lastTailNode = null; null !== hasRenderedATailFallback; ) - null !== hasRenderedATailFallback.alternate && - (lastTailNode = hasRenderedATailFallback), - (hasRenderedATailFallback = hasRenderedATailFallback.sibling); - null === lastTailNode - ? (renderState.tail = null) - : (lastTailNode.sibling = null); - break; - case "collapsed": - lastTailNode = renderState.tail; - for (var lastTailNode$64 = null; null !== lastTailNode; ) - null !== lastTailNode.alternate && (lastTailNode$64 = lastTailNode), - (lastTailNode = lastTailNode.sibling); - null === lastTailNode$64 - ? hasRenderedATailFallback || null === renderState.tail - ? (renderState.tail = null) - : (renderState.tail.sibling = null) - : (lastTailNode$64.sibling = null); - } -} -function bubbleProperties(completedWork) { - var didBailout = - null !== completedWork.alternate && - completedWork.alternate.child === completedWork.child, - newChildLanes = 0, - subtreeFlags = 0; - if (didBailout) - if (0 !== (completedWork.mode & 2)) { - for ( - var treeBaseDuration$66 = completedWork.selfBaseDuration, - child$67 = completedWork.child; - null !== child$67; - - ) - (newChildLanes |= child$67.lanes | child$67.childLanes), - (subtreeFlags |= child$67.subtreeFlags & 31457280), - (subtreeFlags |= child$67.flags & 31457280), - (treeBaseDuration$66 += child$67.treeBaseDuration), - (child$67 = child$67.sibling); - completedWork.treeBaseDuration = treeBaseDuration$66; - } else - for ( - treeBaseDuration$66 = completedWork.child; - null !== treeBaseDuration$66; - - ) - (newChildLanes |= - treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), - (subtreeFlags |= treeBaseDuration$66.subtreeFlags & 31457280), - (subtreeFlags |= treeBaseDuration$66.flags & 31457280), - (treeBaseDuration$66.return = completedWork), - (treeBaseDuration$66 = treeBaseDuration$66.sibling); - else if (0 !== (completedWork.mode & 2)) { - treeBaseDuration$66 = completedWork.actualDuration; - child$67 = completedWork.selfBaseDuration; - for (var child = completedWork.child; null !== child; ) - (newChildLanes |= child.lanes | child.childLanes), - (subtreeFlags |= child.subtreeFlags), - (subtreeFlags |= child.flags), - (treeBaseDuration$66 += child.actualDuration), - (child$67 += child.treeBaseDuration), - (child = child.sibling); - completedWork.actualDuration = treeBaseDuration$66; - completedWork.treeBaseDuration = child$67; - } else - for ( - treeBaseDuration$66 = completedWork.child; - null !== treeBaseDuration$66; - - ) - (newChildLanes |= - treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), - (subtreeFlags |= treeBaseDuration$66.subtreeFlags), - (subtreeFlags |= treeBaseDuration$66.flags), - (treeBaseDuration$66.return = completedWork), - (treeBaseDuration$66 = treeBaseDuration$66.sibling); - completedWork.subtreeFlags |= subtreeFlags; - completedWork.childLanes = newChildLanes; - return didBailout; -} -function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; + else didReceiveUpdate = !1; + workInProgress.lanes = 0; switch (workInProgress.tag) { case 2: - case 16: - case 15: - case 0: - case 11: - case 7: - case 8: - case 12: - case 9: - case 14: - return bubbleProperties(workInProgress), null; - case 1: - return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null - ); - case 3: - return ( - (renderLanes = workInProgress.stateNode), - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - renderLanes.pendingContext && - ((renderLanes.context = renderLanes.pendingContext), - (renderLanes.pendingContext = null)), - (null !== current && null !== current.child) || - null === current || - (current.memoizedState.isDehydrated && - 0 === (workInProgress.flags & 256)) || - ((workInProgress.flags |= 1024), - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), - (hydrationErrors = null))), - updateHostContainer(current, workInProgress), - bubbleProperties(workInProgress), - null + var Component = workInProgress.type; + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + prepareToReadContext(workInProgress, renderLanes); + var value = renderWithHooks( + null, + workInProgress, + Component, + current, + void 0, + renderLanes ); - case 26: - case 27: - case 5: - popHostContext(workInProgress); - renderLanes = workInProgress.type; - if (null !== current && null != workInProgress.stateNode) { - renderLanes = current.stateNode; - var oldProps = current.memoizedProps, - requiresClone = doesRequireClone(current, workInProgress); - if (requiresClone || oldProps !== newProps) { - b: { - oldProps = diffProperties( - null, - oldProps, - newProps, - renderLanes.canonical.viewConfig.validAttributes - ); - renderLanes.canonical.currentProps = newProps; - newProps = renderLanes.node; - if (requiresClone) - newProps = - null !== oldProps - ? cloneNodeWithNewChildrenAndProps(newProps, oldProps) - : cloneNodeWithNewChildren(newProps); - else if (null !== oldProps) - newProps = cloneNodeWithNewProps(newProps, oldProps); - else { - newProps = renderLanes; - break b; - } - newProps = { node: newProps, canonical: renderLanes.canonical }; - } - newProps === renderLanes - ? (workInProgress.stateNode = renderLanes) - : ((workInProgress.stateNode = newProps), - requiresClone - ? appendAllChildren(newProps, workInProgress, !1, !1) - : (workInProgress.flags |= 4)); - } else workInProgress.stateNode = renderLanes; - current.ref !== workInProgress.ref && (workInProgress.flags |= 2097664); - } else { - if (!newProps) { - if (null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + workInProgress.flags |= 1; + "object" === typeof value && + null !== value && + "function" === typeof value.render && + void 0 === value.$$typeof + ? ((workInProgress.tag = 1), + (workInProgress.memoizedState = null), + (workInProgress.updateQueue = null), + (workInProgress.memoizedState = + null !== value.state && void 0 !== value.state + ? value.state + : null), + initializeUpdateQueue(workInProgress), + (value.updater = classComponentUpdater), + (workInProgress.stateNode = value), + (value._reactInternals = workInProgress), + mountClassInstance(workInProgress, Component, current, renderLanes), + (workInProgress = finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ))) + : ((workInProgress.tag = 0), + reconcileChildren(null, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; + case 16: + Component = workInProgress.elementType; + a: { + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + value = Component._init; + Component = value(Component._payload); + workInProgress.type = Component; + value = workInProgress.tag = resolveLazyComponentTag(Component); + current = resolveDefaultProps(Component, current); + switch (value) { + case 0: + workInProgress = updateFunctionComponent( + null, + workInProgress, + Component, + current, + renderLanes ); - bubbleProperties(workInProgress); - return null; + break a; + case 1: + workInProgress = updateClassComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 11: + workInProgress = updateForwardRef( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 14: + workInProgress = updateMemoComponent( + null, + workInProgress, + Component, + resolveDefaultProps(Component.type, current), + renderLanes + ); + break a; } - requiresClone = rootInstanceStackCursor.current; - current = nextReactTag; - nextReactTag += 2; - renderLanes = getViewConfigForType(renderLanes); - oldProps = diffProperties( - null, - emptyObject, - newProps, - renderLanes.validAttributes + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." ); - requiresClone = createNode( + } + return workInProgress; + case 0: + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateFunctionComponent( current, - renderLanes.uiViewClassName, - requiresClone, - oldProps, - workInProgress - ); - oldProps = ReactNativePrivateInterface.createPublicInstance( + workInProgress, + Component, + value, + renderLanes + ) + ); + case 1: + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateClassComponent( current, - renderLanes, - workInProgress - ); - current = { - node: requiresClone, - canonical: { - nativeTag: current, - viewConfig: renderLanes, - currentProps: newProps, - internalInstanceHandle: workInProgress, - publicInstance: oldProps - } - }; - appendAllChildren(current, workInProgress, !1, !1); - workInProgress.stateNode = current; - null !== workInProgress.ref && (workInProgress.flags |= 2097664); - } - bubbleProperties(workInProgress); - workInProgress.flags &= -16777217; - return null; + workInProgress, + Component, + value, + renderLanes + ) + ); + case 3: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + if (null === current) + throw Error("Should have a current fiber. This is a bug in React."); + value = workInProgress.pendingProps; + Component = workInProgress.memoizedState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, value, null, renderLanes); + value = workInProgress.memoizedState.element; + value === Component + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + )) + : (reconcileChildren(current, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; + case 26: + case 27: + case 5: + return ( + pushHostContext(workInProgress), + (Component = workInProgress.pendingProps.children), + markRef(current, workInProgress), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); case 6: - if (current && null != workInProgress.stateNode) - current.memoizedProps !== newProps - ? ((workInProgress.stateNode = createTextInstance( - newProps, - rootInstanceStackCursor.current, - contextStackCursor.current, - workInProgress - )), - (workInProgress.flags |= 4)) - : (workInProgress.stateNode = current.stateNode); - else { - if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgress.stateNode = createTextInstance( - newProps, - rootInstanceStackCursor.current, - contextStackCursor.current, - workInProgress - ); - } - bubbleProperties(workInProgress); return null; case 13: - popSuspenseHandler(workInProgress); - newProps = workInProgress.memoizedState; - if ( - null === current || - (null !== current.memoizedState && - null !== current.memoizedState.dehydrated) - ) { - if (null !== newProps && null !== newProps.dehydrated) { - if (null === current) { - throw Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ); - throw Error( - "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ); - } - 0 === (workInProgress.flags & 128) && - (workInProgress.memoizedState = null); - workInProgress.flags |= 4; - bubbleProperties(workInProgress); - 0 !== (workInProgress.mode & 2) && - null !== newProps && - ((requiresClone = workInProgress.child), - null !== requiresClone && - (workInProgress.treeBaseDuration -= - requiresClone.treeBaseDuration)); - requiresClone = !1; - } else - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), - (requiresClone = !0); - if (!requiresClone) - return workInProgress.flags & 256 ? workInProgress : null; - } - if (0 !== (workInProgress.flags & 128)) - return ( - (workInProgress.lanes = renderLanes), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress - ); - renderLanes = null !== newProps; - renderLanes !== (null !== current && null !== current.memoizedState) && - renderLanes && - (workInProgress.child.flags |= 8192); - scheduleRetryEffect(workInProgress, workInProgress.updateQueue); - bubbleProperties(workInProgress); - 0 !== (workInProgress.mode & 2) && - renderLanes && - ((current = workInProgress.child), - null !== current && - (workInProgress.treeBaseDuration -= current.treeBaseDuration)); - return null; + return updateSuspenseComponent(current, workInProgress, renderLanes); case 4: return ( - popHostContainer(), - updateHostContainer(current, workInProgress), - bubbleProperties(workInProgress), - null + pushHostContainer( + workInProgress, + workInProgress.stateNode.containerInfo + ), + (Component = workInProgress.pendingProps), + null === current + ? (workInProgress.child = reconcileChildFibers( + workInProgress, + null, + Component, + renderLanes + )) + : reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 10: + case 11: return ( - popProvider(workInProgress.type._context), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateForwardRef(current, workInProgress, Component, value, renderLanes) ); - case 17: + case 7: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps, + renderLanes + ), + workInProgress.child ); - case 19: - pop(suspenseStackCursor); - requiresClone = workInProgress.memoizedState; - if (null === requiresClone) return bubbleProperties(workInProgress), null; - newProps = 0 !== (workInProgress.flags & 128); - oldProps = requiresClone.rendering; - if (null === oldProps) - if (newProps) cutOffTailIfNeeded(requiresClone, !1); - else { - if ( - 0 !== workInProgressRootExitStatus || - (null !== current && 0 !== (current.flags & 128)) - ) - for (current = workInProgress.child; null !== current; ) { - oldProps = findFirstSuspended(current); - if (null !== oldProps) { - workInProgress.flags |= 128; - cutOffTailIfNeeded(requiresClone, !1); - current = oldProps.updateQueue; - workInProgress.updateQueue = current; - scheduleRetryEffect(workInProgress, current); - workInProgress.subtreeFlags = 0; - current = renderLanes; - for (renderLanes = workInProgress.child; null !== renderLanes; ) - resetWorkInProgress(renderLanes, current), - (renderLanes = renderLanes.sibling); - push( - suspenseStackCursor, - (suspenseStackCursor.current & 1) | 2 - ); - return workInProgress.child; - } - current = current.sibling; + case 8: + return ( + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child + ); + case 12: + return ( + (workInProgress.flags |= 4), + (Component = workInProgress.stateNode), + (Component.effectDuration = 0), + (Component.passiveEffectDuration = 0), + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child + ); + case 10: + a: { + Component = workInProgress.type._context; + value = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps, + newValue = value.value; + push(valueCursor, Component._currentValue2); + Component._currentValue2 = newValue; + if (null !== oldProps) + if (objectIs(oldProps.value, newValue)) { + if (oldProps.children === value.children) { + workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + ); + break a; } - null !== requiresClone.tail && - now$1() > workInProgressRootRenderTargetTime && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(requiresClone, !1), - (workInProgress.lanes = 4194304)); - } - else { - if (!newProps) - if (((current = findFirstSuspended(oldProps)), null !== current)) { - if ( - ((workInProgress.flags |= 128), - (newProps = !0), - (current = current.updateQueue), - (workInProgress.updateQueue = current), - scheduleRetryEffect(workInProgress, current), - cutOffTailIfNeeded(requiresClone, !0), - null === requiresClone.tail && - "hidden" === requiresClone.tailMode && - !oldProps.alternate) - ) - return bubbleProperties(workInProgress), null; } else - 2 * now$1() - requiresClone.renderingStartTime > - workInProgressRootRenderTargetTime && - 536870912 !== renderLanes && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(requiresClone, !1), - (workInProgress.lanes = 4194304)); - requiresClone.isBackwards - ? ((oldProps.sibling = workInProgress.child), - (workInProgress.child = oldProps)) - : ((current = requiresClone.last), - null !== current - ? (current.sibling = oldProps) - : (workInProgress.child = oldProps), - (requiresClone.last = oldProps)); + for ( + oldProps = workInProgress.child, + null !== oldProps && (oldProps.return = workInProgress); + null !== oldProps; + + ) { + var list = oldProps.dependencies; + if (null !== list) { + newValue = oldProps.child; + for ( + var dependency = list.firstContext; + null !== dependency; + + ) { + if (dependency.context === Component) { + if (1 === oldProps.tag) { + dependency = createUpdate(renderLanes & -renderLanes); + dependency.tag = 2; + var updateQueue = oldProps.updateQueue; + if (null !== updateQueue) { + updateQueue = updateQueue.shared; + var pending = updateQueue.pending; + null === pending + ? (dependency.next = dependency) + : ((dependency.next = pending.next), + (pending.next = dependency)); + updateQueue.pending = dependency; + } + } + oldProps.lanes |= renderLanes; + dependency = oldProps.alternate; + null !== dependency && (dependency.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + oldProps.return, + renderLanes, + workInProgress + ); + list.lanes |= renderLanes; + break; + } + dependency = dependency.next; + } + } else if (10 === oldProps.tag) + newValue = + oldProps.type === workInProgress.type ? null : oldProps.child; + else if (18 === oldProps.tag) { + newValue = oldProps.return; + if (null === newValue) + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + newValue.lanes |= renderLanes; + list = newValue.alternate; + null !== list && (list.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + newValue, + renderLanes, + workInProgress + ); + newValue = oldProps.sibling; + } else newValue = oldProps.child; + if (null !== newValue) newValue.return = oldProps; + else + for (newValue = oldProps; null !== newValue; ) { + if (newValue === workInProgress) { + newValue = null; + break; + } + oldProps = newValue.sibling; + if (null !== oldProps) { + oldProps.return = newValue.return; + newValue = oldProps; + break; + } + newValue = newValue.return; + } + oldProps = newValue; + } + reconcileChildren(current, workInProgress, value.children, renderLanes); + workInProgress = workInProgress.child; } - if (null !== requiresClone.tail) - return ( - (workInProgress = requiresClone.tail), - (requiresClone.rendering = workInProgress), - (requiresClone.tail = workInProgress.sibling), - (requiresClone.renderingStartTime = now$1()), - (workInProgress.sibling = null), - (current = suspenseStackCursor.current), - push(suspenseStackCursor, newProps ? (current & 1) | 2 : current & 1), - workInProgress - ); - bubbleProperties(workInProgress); - return null; - case 22: - case 23: + return workInProgress; + case 9: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (newProps = null !== workInProgress.memoizedState), - null !== current - ? (null !== current.memoizedState) !== newProps && - (workInProgress.flags |= 8192) - : newProps && (workInProgress.flags |= 8192), - newProps && 0 !== (workInProgress.mode & 1) - ? 0 !== (renderLanes & 536870912) && - 0 === (workInProgress.flags & 128) && - (bubbleProperties(workInProgress), - workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) - : bubbleProperties(workInProgress), - (current = workInProgress.updateQueue), - null !== current && - scheduleRetryEffect(workInProgress, current.retryQueue), - null + (value = workInProgress.type), + (Component = workInProgress.pendingProps.children), + prepareToReadContext(workInProgress, renderLanes), + (value = readContext(value)), + (Component = Component(value)), + (workInProgress.flags |= 1), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 24: - return null; - case 25: - return null; + case 14: + return ( + (Component = workInProgress.type), + (value = resolveDefaultProps(Component, workInProgress.pendingProps)), + (value = resolveDefaultProps(Component.type, value)), + updateMemoComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) + ); + case 15: + return updateSimpleMemoComponent( + current, + workInProgress, + workInProgress.type, + workInProgress.pendingProps, + renderLanes + ); + case 17: + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), + (workInProgress.tag = 1), + prepareToReadContext(workInProgress, renderLanes), + constructClassInstance(workInProgress, Component, value), + mountClassInstance(workInProgress, Component, value, renderLanes), + finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ) + ); + case 19: + return updateSuspenseListComponent(current, workInProgress, renderLanes); + case 22: + return updateOffscreenComponent(current, workInProgress, renderLanes); } throw Error( "Unknown unit of work tag (" + @@ -6526,2847 +6054,3008 @@ function completeWork(current, workInProgress, renderLanes) { "). This error is likely caused by a bug in React. Please file an issue." ); } -function unwindWork(current, workInProgress) { - switch (workInProgress.tag) { - case 1: - return ( - isContextProvider(workInProgress.type) && popContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null - ); - case 3: - return ( - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - (current = workInProgress.flags), - 0 !== (current & 65536) && 0 === (current & 128) - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null - ); - case 26: - case 27: - case 5: - return popHostContext(workInProgress), null; - case 13: - popSuspenseHandler(workInProgress); - current = workInProgress.memoizedState; - if ( - null !== current && - null !== current.dehydrated && - null === workInProgress.alternate - ) - throw Error( - "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." - ); - current = workInProgress.flags; - return current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null; - case 19: - return pop(suspenseStackCursor), null; - case 4: - return popHostContainer(), null; - case 10: - return popProvider(workInProgress.type._context), null; - case 22: - case 23: - return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null - ); - case 24: - return null; - case 25: - return null; - default: - return null; - } +var valueCursor = createCursor(null), + currentlyRenderingFiber = null, + lastContextDependency = null, + lastFullyObservedContext = null; +function resetContextDependencies() { + lastFullyObservedContext = + lastContextDependency = + currentlyRenderingFiber = + null; } -function unwindInterruptedWork(current, interruptedWork) { - switch (interruptedWork.tag) { - case 1: - current = interruptedWork.type.childContextTypes; - null !== current && void 0 !== current && popContext(); - break; - case 3: - popHostContainer(); - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); - break; - case 26: - case 27: - case 5: - popHostContext(interruptedWork); - break; - case 4: - popHostContainer(); - break; - case 13: - popSuspenseHandler(interruptedWork); - break; - case 19: - pop(suspenseStackCursor); - break; - case 10: - popProvider(interruptedWork.type._context); - break; - case 22: - case 23: - popSuspenseHandler(interruptedWork), popHiddenContext(); +function popProvider(context) { + context._currentValue2 = valueCursor.current; + pop(valueCursor); +} +function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + for (; null !== parent; ) { + var alternate = parent.alternate; + (parent.childLanes & renderLanes) !== renderLanes + ? ((parent.childLanes |= renderLanes), + null !== alternate && (alternate.childLanes |= renderLanes)) + : null !== alternate && + (alternate.childLanes & renderLanes) !== renderLanes && + (alternate.childLanes |= renderLanes); + if (parent === propagationRoot) break; + parent = parent.return; } } -var offscreenSubtreeIsHidden = !1, - offscreenSubtreeWasHidden = !1, - PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, - nextEffect = null, - inProgressLanes = null, - inProgressRoot = null; -function shouldProfile(current) { - return 0 !== (current.mode & 2) && 0 !== (executionContext & 4); +function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastFullyObservedContext = lastContextDependency = null; + workInProgress = workInProgress.dependencies; + null !== workInProgress && + null !== workInProgress.firstContext && + (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), + (workInProgress.firstContext = null)); } -function callComponentWillUnmountWithTimer(current, instance) { - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current); - } - else instance.componentWillUnmount(); +function readContext(context) { + return readContextForConsumer(currentlyRenderingFiber, context); } -function safelyAttachRef(current, nearestMountedAncestor) { - try { - var ref = current.ref; - if (null !== ref) { - var instance = current.stateNode; - switch (current.tag) { - case 26: - case 27: - case 5: - var instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - if ("function" === typeof ref) - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), (current.refCleanup = ref(instanceToUse)); - } finally { - recordLayoutEffectDuration(current); - } - else current.refCleanup = ref(instanceToUse); - else ref.current = instanceToUse; - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); +function readContextDuringReconciliation(consumer, context, renderLanes) { + null === currentlyRenderingFiber && + prepareToReadContext(consumer, renderLanes); + return readContextForConsumer(consumer, context); +} +function readContextForConsumer(consumer, context) { + var value = context._currentValue2; + if (lastFullyObservedContext !== context) + if ( + ((context = { context: context, memoizedValue: value, next: null }), + null === lastContextDependency) + ) { + if (null === consumer) + throw Error( + "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." + ); + lastContextDependency = context; + consumer.dependencies = { lanes: 0, firstContext: context }; + } else lastContextDependency = lastContextDependency.next = context; + return value; +} +var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; +function handleAsyncAction() {} +function doesRequireClone(current, completedWork) { + if (null !== current && current.child === completedWork.child) return !1; + if (0 !== (completedWork.flags & 16)) return !0; + for (current = completedWork.child; null !== current; ) { + if (0 !== (current.flags & 12854) || 0 !== (current.subtreeFlags & 12854)) + return !0; + current = current.sibling; } + return !1; } -function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref, - refCleanup = current.refCleanup; - if (null !== ref) - if ("function" === typeof refCleanup) - try { - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), refCleanup(); - } finally { - recordLayoutEffectDuration(current); - } - else refCleanup(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } finally { - (current.refCleanup = null), - (current = current.alternate), - null != current && (current.refCleanup = null); - } - else if ("function" === typeof ref) - try { - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), ref(null); - } finally { - recordLayoutEffectDuration(current); - } - else ref(null); - } catch (error$85) { - captureCommitPhaseError(current, nearestMountedAncestor, error$85); +function appendAllChildren( + parent, + workInProgress, + needsVisibilityToggle, + isHidden +) { + for (var node = workInProgress.child; null !== node; ) { + if (5 === node.tag) { + var instance = node.stateNode; + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance(instance)); + appendChildNode(parent.node, instance.node); + } else if (6 === node.tag) { + instance = node.stateNode; + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); + appendChildNode(parent.node, instance.node); + } else if (4 !== node.tag) + if (22 === node.tag && null !== node.memoizedState) + (instance = node.child), + null !== instance && (instance.return = node), + appendAllChildren(parent, node, !0, !0); + else if (null !== node.child) { + node.child.return = node; + node = node.child; + continue; } - else ref.current = null; -} -function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); + if (node === workInProgress) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; } } -var shouldFireAfterActiveInstanceBlur = !1; -function commitBeforeMutationEffects(root, firstChild) { - for (nextEffect = firstChild; null !== nextEffect; ) - if ( - ((root = nextEffect), - (firstChild = root.child), - 0 !== (root.subtreeFlags & 1028) && null !== firstChild) - ) - (firstChild.return = root), (nextEffect = firstChild); - else - for (; null !== nextEffect; ) { - root = nextEffect; - try { - var current = root.alternate, - flags = root.flags; - switch (root.tag) { - case 0: - break; - case 11: - case 15: - break; - case 1: - if (0 !== (flags & 1024) && null !== current) { - var prevProps = current.memoizedProps, - prevState = current.memoizedState, - instance = root.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - root.elementType === root.type - ? prevProps - : resolveDefaultProps(root.type, prevProps), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - break; - case 5: - case 26: - case 27: - case 6: - case 4: - case 17: - break; - default: - if (0 !== (flags & 1024)) - throw Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ); - } - } catch (error) { - captureCommitPhaseError(root, root.return, error); - } - firstChild = root.sibling; - if (null !== firstChild) { - firstChild.return = root.return; - nextEffect = firstChild; - break; - } - nextEffect = root.return; - } - current = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = !1; - return current; -} -function commitHookEffectListUnmount( - flags, - finishedWork, - nearestMountedAncestor +function appendAllChildrenToContainer( + containerChildSet, + workInProgress, + needsVisibilityToggle, + isHidden ) { - var updateQueue = finishedWork.updateQueue; - updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; - if (null !== updateQueue) { - var effect = (updateQueue = updateQueue.next); - do { - if ((effect.tag & flags) === flags) { - var inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - ((inst.destroy = void 0), - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); + for (var node = workInProgress.child; null !== node; ) { + if (5 === node.tag) { + var instance = node.stateNode; + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance(instance)); + appendChildNodeToSet(containerChildSet, instance.node); + } else if (6 === node.tag) { + instance = node.stateNode; + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); + appendChildNodeToSet(containerChildSet, instance.node); + } else if (4 !== node.tag) + if (22 === node.tag && null !== node.memoizedState) + (instance = node.child), + null !== instance && (instance.return = node), + appendAllChildrenToContainer( + containerChildSet, + node, + !( + null !== node.memoizedProps && + "manual" === node.memoizedProps.mode + ), + !0 + ); + else if (null !== node.child) { + node.child.return = node; + node = node.child; + continue; } - effect = effect.next; - } while (effect !== updateQueue); + if (node === workInProgress) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; } } -function commitHookEffectListMount(flags, finishedWork) { - finishedWork = finishedWork.updateQueue; - finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; - if (null !== finishedWork) { - var effect = (finishedWork = finishedWork.next); - do { - if ((effect.tag & flags) === flags) { - var create$86 = effect.create, - inst = effect.inst; - create$86 = create$86(); - inst.destroy = create$86; - } - effect = effect.next; - } while (effect !== finishedWork); +function updateHostContainer(current, workInProgress) { + if (doesRequireClone(current, workInProgress)) { + current = workInProgress.stateNode; + var container = current.containerInfo, + newChildSet = createChildNodeSet(); + appendAllChildrenToContainer(newChildSet, workInProgress, !1, !1); + current.pendingChildren = newChildSet; + workInProgress.flags |= 4; + completeRoot(container, newChildSet); } } -function commitHookLayoutEffects(finishedWork, hookFlags) { - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error$88) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$88); - } +function scheduleRetryEffect(workInProgress, retryQueue) { + null !== retryQueue + ? (workInProgress.flags |= 4) + : workInProgress.flags & 16384 && + ((retryQueue = + 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), + (workInProgress.lanes |= retryQueue)); } -function commitClassCallbacks(finishedWork) { - var updateQueue = finishedWork.updateQueue; - if (null !== updateQueue) { - var instance = finishedWork.stateNode; - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + switch (renderState.tailMode) { + case "hidden": + hasRenderedATailFallback = renderState.tail; + for (var lastTailNode = null; null !== hasRenderedATailFallback; ) + null !== hasRenderedATailFallback.alternate && + (lastTailNode = hasRenderedATailFallback), + (hasRenderedATailFallback = hasRenderedATailFallback.sibling); + null === lastTailNode + ? (renderState.tail = null) + : (lastTailNode.sibling = null); + break; + case "collapsed": + lastTailNode = renderState.tail; + for (var lastTailNode$64 = null; null !== lastTailNode; ) + null !== lastTailNode.alternate && (lastTailNode$64 = lastTailNode), + (lastTailNode = lastTailNode.sibling); + null === lastTailNode$64 + ? hasRenderedATailFallback || null === renderState.tail + ? (renderState.tail = null) + : (renderState.tail.sibling = null) + : (lastTailNode$64.sibling = null); } } -function commitHostComponentMount(finishedWork) { - try { - throw Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function bubbleProperties(completedWork) { + var didBailout = + null !== completedWork.alternate && + completedWork.alternate.child === completedWork.child, + newChildLanes = 0, + subtreeFlags = 0; + if (didBailout) + if (0 !== (completedWork.mode & 2)) { + for ( + var treeBaseDuration$66 = completedWork.selfBaseDuration, + child$67 = completedWork.child; + null !== child$67; + + ) + (newChildLanes |= child$67.lanes | child$67.childLanes), + (subtreeFlags |= child$67.subtreeFlags & 31457280), + (subtreeFlags |= child$67.flags & 31457280), + (treeBaseDuration$66 += child$67.treeBaseDuration), + (child$67 = child$67.sibling); + completedWork.treeBaseDuration = treeBaseDuration$66; + } else + for ( + treeBaseDuration$66 = completedWork.child; + null !== treeBaseDuration$66; + + ) + (newChildLanes |= + treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), + (subtreeFlags |= treeBaseDuration$66.subtreeFlags & 31457280), + (subtreeFlags |= treeBaseDuration$66.flags & 31457280), + (treeBaseDuration$66.return = completedWork), + (treeBaseDuration$66 = treeBaseDuration$66.sibling); + else if (0 !== (completedWork.mode & 2)) { + treeBaseDuration$66 = completedWork.actualDuration; + child$67 = completedWork.selfBaseDuration; + for (var child = completedWork.child; null !== child; ) + (newChildLanes |= child.lanes | child.childLanes), + (subtreeFlags |= child.subtreeFlags), + (subtreeFlags |= child.flags), + (treeBaseDuration$66 += child.actualDuration), + (child$67 += child.treeBaseDuration), + (child = child.sibling); + completedWork.actualDuration = treeBaseDuration$66; + completedWork.treeBaseDuration = child$67; + } else + for ( + treeBaseDuration$66 = completedWork.child; + null !== treeBaseDuration$66; + + ) + (newChildLanes |= + treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), + (subtreeFlags |= treeBaseDuration$66.subtreeFlags), + (subtreeFlags |= treeBaseDuration$66.flags), + (treeBaseDuration$66.return = completedWork), + (treeBaseDuration$66 = treeBaseDuration$66.sibling); + completedWork.subtreeFlags |= subtreeFlags; + completedWork.childLanes = newChildLanes; + return didBailout; } -function commitProfilerUpdate(finishedWork, current) { - if (executionContext & 4) - try { - var _finishedWork$memoize2 = finishedWork.memoizedProps, - onCommit = _finishedWork$memoize2.onCommit, - onRender = _finishedWork$memoize2.onRender, - effectDuration = finishedWork.stateNode.effectDuration; - _finishedWork$memoize2 = commitTime; - current = null === current ? "mount" : "update"; - currentUpdateIsNested && (current = "nested-update"); - "function" === typeof onRender && - onRender( - finishedWork.memoizedProps.id, - current, - finishedWork.actualDuration, - finishedWork.treeBaseDuration, - finishedWork.actualStartTime, - _finishedWork$memoize2 - ); - "function" === typeof onCommit && - onCommit( - finishedWork.memoizedProps.id, - current, - effectDuration, - _finishedWork$memoize2 - ); - enqueuePendingPassiveProfilerEffect(finishedWork); - var parentFiber = finishedWork.return; - a: for (; null !== parentFiber; ) { - switch (parentFiber.tag) { - case 3: - parentFiber.stateNode.effectDuration += effectDuration; - break a; - case 12: - parentFiber.stateNode.effectDuration += effectDuration; - break a; - } - parentFiber = parentFiber.return; - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } -} -function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { - var flags = finishedWork.flags; - switch (finishedWork.tag) { +function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; + switch (workInProgress.tag) { + case 2: + case 16: + case 15: case 0: case 11: - case 15: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitHookLayoutEffects(finishedWork, 5); - break; + case 7: + case 8: + case 12: + case 9: + case 14: + return bubbleProperties(workInProgress), null; case 1: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 4) - if (((finishedRoot = finishedWork.stateNode), null === current)) - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - finishedRoot.componentDidMount(); - } catch (error$89) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$89 - ); - } - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current.memoizedProps - : resolveDefaultProps(finishedWork.type, current.memoizedProps); - current = current.memoizedState; - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$90) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$90 - ); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$91) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$91 - ); - } - } - flags & 64 && commitClassCallbacks(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; + return bubbleProperties(workInProgress), null; case 3: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { - finishedRoot = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 27: - case 5: - finishedRoot = getPublicInstance(finishedWork.child.stateNode); - break; - case 1: - finishedRoot = finishedWork.child.stateNode; - } - try { - commitCallbacks(flags, finishedRoot); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - break; + return ( + (renderLanes = workInProgress.stateNode), + popHostContainer(), + renderLanes.pendingContext && + ((renderLanes.context = renderLanes.pendingContext), + (renderLanes.pendingContext = null)), + (null !== current && null !== current.child) || + null === current || + (current.memoizedState.isDehydrated && + 0 === (workInProgress.flags & 256)) || + ((workInProgress.flags |= 1024), + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), + (hydrationErrors = null))), + updateHostContainer(current, workInProgress), + bubbleProperties(workInProgress), + null + ); case 26: case 27: case 5: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - null === current && flags & 4 && commitHostComponentMount(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitProfilerUpdate(finishedWork, current); - break; - case 13: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 22: - if (0 !== (finishedWork.mode & 1)) { + popHostContext(workInProgress); + renderLanes = workInProgress.type; + if (null !== current && null != workInProgress.stateNode) { + renderLanes = current.stateNode; + var oldProps = current.memoizedProps; if ( - ((prevProps = - null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), - !prevProps) + (current = doesRequireClone(current, workInProgress)) || + oldProps !== newProps ) { - current = - (null !== current && null !== current.memoizedState) || - offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevProps; - (offscreenSubtreeWasHidden = current) && - !prevOffscreenSubtreeWasHidden - ? recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - 0 !== (finishedWork.subtreeFlags & 8772) - ) - : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + b: { + oldProps = diffProperties( + null, + oldProps, + newProps, + renderLanes.canonical.viewConfig.validAttributes + ); + renderLanes.canonical.currentProps = newProps; + newProps = renderLanes.node; + if (current) + newProps = + null !== oldProps + ? cloneNodeWithNewChildrenAndProps(newProps, oldProps) + : cloneNodeWithNewChildren(newProps); + else if (null !== oldProps) + newProps = cloneNodeWithNewProps(newProps, oldProps); + else { + newProps = renderLanes; + break b; + } + newProps = { node: newProps, canonical: renderLanes.canonical }; + } + newProps === renderLanes + ? (workInProgress.stateNode = renderLanes) + : ((workInProgress.stateNode = newProps), + current + ? appendAllChildren(newProps, workInProgress, !1, !1) + : (workInProgress.flags |= 4)); + } else workInProgress.stateNode = renderLanes; + } else { + if (!newProps) { + if (null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + bubbleProperties(workInProgress); + return null; } - } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && - ("manual" === finishedWork.memoizedProps.mode - ? safelyAttachRef(finishedWork, finishedWork.return) - : safelyDetachRef(finishedWork, finishedWork.return)); - break; - default: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - } -} -function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - null !== alternate && - ((fiber.alternate = null), detachFiberAfterEffects(alternate)); - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - fiber.stateNode = null; - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - fiber.updateQueue = null; -} -function recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - parent -) { - for (parent = parent.child; null !== parent; ) - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), - (parent = parent.sibling); -} -function commitDeletionEffectsOnFiber( - finishedRoot, - nearestMountedAncestor, - deletedFiber -) { - if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) - try { - injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); - } catch (err) {} - switch (deletedFiber.tag) { - case 26: - case 27: - case 5: - offscreenSubtreeWasHidden || - safelyDetachRef(deletedFiber, nearestMountedAncestor); + oldProps = rootInstanceStackCursor.current; + current = nextReactTag; + nextReactTag += 2; + renderLanes = getViewConfigForType(renderLanes); + var updatePayload = diffProperties( + null, + emptyObject, + newProps, + renderLanes.validAttributes + ); + oldProps = createNode( + current, + renderLanes.uiViewClassName, + oldProps, + updatePayload, + workInProgress + ); + updatePayload = ReactNativePrivateInterface.createPublicInstance( + current, + renderLanes, + workInProgress + ); + current = { + node: oldProps, + canonical: { + nativeTag: current, + viewConfig: renderLanes, + currentProps: newProps, + internalInstanceHandle: workInProgress, + publicInstance: updatePayload + } + }; + appendAllChildren(current, workInProgress, !1, !1); + workInProgress.stateNode = current; + } + bubbleProperties(workInProgress); + workInProgress.flags &= -16777217; + return null; case 6: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 18: - break; - case 4: - createChildNodeSet(); - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 0: - case 11: - case 14: - case 15: - if (!offscreenSubtreeWasHidden) { - var updateQueue = deletedFiber.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) - ) { - var effect = (updateQueue = updateQueue.next); - do { - var tag = effect.tag, - inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - (0 !== (tag & 2) - ? ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )) - : 0 !== (tag & 4) && - (shouldProfile(deletedFiber) - ? (startLayoutEffectTimer(), - (inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - ), - recordLayoutEffectDuration(deletedFiber)) - : ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )))); - effect = effect.next; - } while (effect !== updateQueue); - } + if (current && null != workInProgress.stateNode) + current.memoizedProps !== newProps + ? ((workInProgress.stateNode = createTextInstance( + newProps, + rootInstanceStackCursor.current, + contextStackCursor.current, + workInProgress + )), + (workInProgress.flags |= 4)) + : (workInProgress.stateNode = current.stateNode); + else { + if ("string" !== typeof newProps && null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgress.stateNode = createTextInstance( + newProps, + rootInstanceStackCursor.current, + contextStackCursor.current, + workInProgress + ); } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 1: + bubbleProperties(workInProgress); + return null; + case 13: + newProps = workInProgress.memoizedState; if ( - !offscreenSubtreeWasHidden && - (safelyDetachRef(deletedFiber, nearestMountedAncestor), - (updateQueue = deletedFiber.stateNode), - "function" === typeof updateQueue.componentWillUnmount) - ) - try { - callComponentWillUnmountWithTimer(deletedFiber, updateQueue); - } catch (error) { - captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + null === current || + (null !== current.memoizedState && + null !== current.memoizedState.dehydrated) + ) { + if (null !== newProps && null !== newProps.dehydrated) { + if (null === current) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + 0 === (workInProgress.flags & 128) && + (workInProgress.memoizedState = null); + workInProgress.flags |= 4; + bubbleProperties(workInProgress); + 0 !== (workInProgress.mode & 2) && + null !== newProps && + ((oldProps = workInProgress.child), + null !== oldProps && + (workInProgress.treeBaseDuration -= oldProps.treeBaseDuration)); + oldProps = !1; + } else + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), + (oldProps = !0); + if (!oldProps) { + if (workInProgress.flags & 256) + return popSuspenseHandler(workInProgress), workInProgress; + popSuspenseHandler(workInProgress); + return null; } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 21: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 22: - safelyDetachRef(deletedFiber, nearestMountedAncestor); - deletedFiber.mode & 1 - ? ((offscreenSubtreeWasHidden = - (updateQueue = offscreenSubtreeWasHidden) || - null !== deletedFiber.memoizedState), - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ), - (offscreenSubtreeWasHidden = updateQueue)) - : recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - default: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - } -} -function getRetryCache(finishedWork) { - switch (finishedWork.tag) { - case 13: - case 19: - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); - return retryCache; - case 22: + } + popSuspenseHandler(workInProgress); + if (0 !== (workInProgress.flags & 128)) + return ( + (workInProgress.lanes = renderLanes), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress + ); + renderLanes = null !== newProps; + renderLanes !== (null !== current && null !== current.memoizedState) && + renderLanes && + (workInProgress.child.flags |= 8192); + scheduleRetryEffect(workInProgress, workInProgress.updateQueue); + bubbleProperties(workInProgress); + 0 !== (workInProgress.mode & 2) && + renderLanes && + ((current = workInProgress.child), + null !== current && + (workInProgress.treeBaseDuration -= current.treeBaseDuration)); + return null; + case 4: return ( - (finishedWork = finishedWork.stateNode), - (retryCache = finishedWork._retryCache), - null === retryCache && - (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), - retryCache + popHostContainer(), + updateHostContainer(current, workInProgress), + bubbleProperties(workInProgress), + null ); - default: - throw Error( - "Unexpected Suspense handler tag (" + - finishedWork.tag + - "). This is a bug in React." + case 10: + return ( + popProvider(workInProgress.type._context), + bubbleProperties(workInProgress), + null ); - } -} -function attachSuspenseRetryListeners(finishedWork, wakeables) { - var retryCache = getRetryCache(finishedWork); - wakeables.forEach(function (wakeable) { - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - if (isDevToolsPresent) - if (null !== inProgressLanes && null !== inProgressRoot) - restorePendingUpdaters(inProgressRoot, inProgressLanes); - else - throw Error( - "Expected finished root and lanes to be set. This is a bug in React." - ); - wakeable.then(retry, retry); - } - }); -} -function commitMutationEffects(root, finishedWork, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - commitMutationEffectsOnFiber(finishedWork, root); - inProgressRoot = inProgressLanes = null; -} -function recursivelyTraverseMutationEffects(root, parentFiber) { - var deletions = parentFiber.deletions; - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - try { - commitDeletionEffectsOnFiber(root, parentFiber, childToDelete); - var alternate = childToDelete.alternate; - null !== alternate && (alternate.return = null); - childToDelete.return = null; - } catch (error) { - captureCommitPhaseError(childToDelete, parentFiber, error); - } - } - if (parentFiber.subtreeFlags & 12854) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitMutationEffectsOnFiber(parentFiber, root), - (parentFiber = parentFiber.sibling); -} -function commitMutationEffectsOnFiber(finishedWork, root) { - var current = finishedWork.alternate, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - try { - commitHookEffectListUnmount(3, finishedWork, finishedWork.return), - commitHookEffectListMount(3, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); + case 17: + return bubbleProperties(workInProgress), null; + case 19: + pop(suspenseStackCursor); + oldProps = workInProgress.memoizedState; + if (null === oldProps) return bubbleProperties(workInProgress), null; + newProps = 0 !== (workInProgress.flags & 128); + updatePayload = oldProps.rendering; + if (null === updatePayload) + if (newProps) cutOffTailIfNeeded(oldProps, !1); + else { + if ( + 0 !== workInProgressRootExitStatus || + (null !== current && 0 !== (current.flags & 128)) + ) + for (current = workInProgress.child; null !== current; ) { + updatePayload = findFirstSuspended(current); + if (null !== updatePayload) { + workInProgress.flags |= 128; + cutOffTailIfNeeded(oldProps, !1); + current = updatePayload.updateQueue; + workInProgress.updateQueue = current; + scheduleRetryEffect(workInProgress, current); + workInProgress.subtreeFlags = 0; + current = renderLanes; + for (renderLanes = workInProgress.child; null !== renderLanes; ) + resetWorkInProgress(renderLanes, current), + (renderLanes = renderLanes.sibling); + push( + suspenseStackCursor, + (suspenseStackCursor.current & 1) | 2 + ); + return workInProgress.child; + } + current = current.sibling; + } + null !== oldProps.tail && + now$1() > workInProgressRootRenderTargetTime && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(oldProps, !1), + (workInProgress.lanes = 4194304)); } - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$94) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$94 - ); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$95) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$95 - ); - } + else { + if (!newProps) + if ( + ((current = findFirstSuspended(updatePayload)), null !== current) + ) { + if ( + ((workInProgress.flags |= 128), + (newProps = !0), + (current = current.updateQueue), + (workInProgress.updateQueue = current), + scheduleRetryEffect(workInProgress, current), + cutOffTailIfNeeded(oldProps, !0), + null === oldProps.tail && + "hidden" === oldProps.tailMode && + !updatePayload.alternate) + ) + return bubbleProperties(workInProgress), null; + } else + 2 * now$1() - oldProps.renderingStartTime > + workInProgressRootRenderTargetTime && + 536870912 !== renderLanes && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(oldProps, !1), + (workInProgress.lanes = 4194304)); + oldProps.isBackwards + ? ((updatePayload.sibling = workInProgress.child), + (workInProgress.child = updatePayload)) + : ((current = oldProps.last), + null !== current + ? (current.sibling = updatePayload) + : (workInProgress.child = updatePayload), + (oldProps.last = updatePayload)); } - break; - case 1: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && + if (null !== oldProps.tail) + return ( + (workInProgress = oldProps.tail), + (oldProps.rendering = workInProgress), + (oldProps.tail = workInProgress.sibling), + (oldProps.renderingStartTime = now$1()), + (workInProgress.sibling = null), + (current = suspenseStackCursor.current), + push(suspenseStackCursor, newProps ? (current & 1) | 2 : current & 1), + workInProgress + ); + bubbleProperties(workInProgress); + return null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (newProps = null !== workInProgress.memoizedState), + null !== current + ? (null !== current.memoizedState) !== newProps && + (workInProgress.flags |= 8192) + : newProps && (workInProgress.flags |= 8192), + newProps && 0 !== (workInProgress.mode & 1) + ? 0 !== (renderLanes & 536870912) && + 0 === (workInProgress.flags & 128) && + (bubbleProperties(workInProgress), + workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) + : bubbleProperties(workInProgress), + (current = workInProgress.updateQueue), null !== current && - safelyDetachRef(current, current.return); - flags & 64 && - offscreenSubtreeIsHidden && - ((finishedWork = finishedWork.updateQueue), - null !== finishedWork && - ((flags = finishedWork.callbacks), - null !== flags && - ((current = finishedWork.shared.hiddenCallbacks), - (finishedWork.shared.hiddenCallbacks = - null === current ? flags : current.concat(flags))))); - break; + scheduleRetryEffect(workInProgress, current.retryQueue), + null + ); + case 24: + return null; + case 25: + return null; + } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); +} +function unwindWork(current, workInProgress) { + switch (workInProgress.tag) { + case 1: + return ( + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null + ); + case 3: + return ( + popHostContainer(), + (current = workInProgress.flags), + 0 !== (current & 65536) && 0 === (current & 128) + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); case 26: case 27: case 5: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && + return popHostContext(workInProgress), null; + case 13: + popSuspenseHandler(workInProgress); + current = workInProgress.memoizedState; + if ( null !== current && - safelyDetachRef(current, current.return); - break; - case 6: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - break; + null !== current.dehydrated && + null === workInProgress.alternate + ) + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + current = workInProgress.flags; + return current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null; + case 19: + return pop(suspenseStackCursor), null; + case 4: + return popHostContainer(), null; + case 10: + return popProvider(workInProgress.type._context), null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null + ); + case 24: + return null; + case 25: + return null; + default: + return null; + } +} +function unwindInterruptedWork(current, interruptedWork) { + switch (interruptedWork.tag) { case 3: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); + break; + case 26: + case 27: + case 5: + popHostContext(interruptedWork); break; case 4: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); break; case 13: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - finishedWork.child.flags & 8192 && - ((current = null !== current && null !== current.memoizedState), - null === finishedWork.memoizedState || - current || - (globalMostRecentFallbackTime = now$1())); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); - break; - case 22: - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - var isHidden = null !== finishedWork.memoizedState, - wasHidden = null !== current && null !== current.memoizedState; - if (finishedWork.mode & 1) { - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; - recursivelyTraverseMutationEffects(root, finishedWork); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - } else recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - root = finishedWork.stateNode; - root._current = finishedWork; - root._visibility &= -3; - root._visibility |= root._pendingVisibility & 2; - flags & 8192 && - ((root._visibility = isHidden - ? root._visibility & -2 - : root._visibility | 1), - isHidden && - ((isHidden = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), - null === current || - wasHidden || - isHidden || - (0 !== (finishedWork.mode & 1) && - recursivelyTraverseDisappearLayoutEffects(finishedWork)))); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((current = flags.retryQueue), - null !== current && - ((flags.retryQueue = null), - attachSuspenseRetryListeners(finishedWork, current)))); + popSuspenseHandler(interruptedWork); break; case 19: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); + pop(suspenseStackCursor); break; - case 21: + case 10: + popProvider(interruptedWork.type._context); break; - default: - recursivelyTraverseMutationEffects(root, finishedWork), - commitReconciliationEffects(finishedWork); + case 22: + case 23: + popSuspenseHandler(interruptedWork), popHiddenContext(); } } -function commitReconciliationEffects(finishedWork) { - var flags = finishedWork.flags; - flags & 2 && (finishedWork.flags &= -3); - flags & 4096 && (finishedWork.flags &= -4097); -} -function commitLayoutEffects(finishedWork, root, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); - inProgressRoot = inProgressLanes = null; +var offscreenSubtreeIsHidden = !1, + offscreenSubtreeWasHidden = !1, + PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, + nextEffect = null, + inProgressLanes = null, + inProgressRoot = null; +function shouldProfile(current) { + return 0 !== (current.mode & 2) && 0 !== (executionContext & 4); } -function recursivelyTraverseLayoutEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 8772) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), - (parentFiber = parentFiber.sibling); +function callComponentWillUnmountWithTimer(current, instance) { + instance.props = current.memoizedProps; + instance.state = current.memoizedState; + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current); + } + else instance.componentWillUnmount(); } -function recursivelyTraverseDisappearLayoutEffects(parentFiber) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - if (shouldProfile(finishedWork)) +function safelyAttachRef(current, nearestMountedAncestor) { + try { + var ref = current.ref; + if (null !== ref) { + var instance = current.stateNode; + switch (current.tag) { + case 26: + case 27: + case 5: + var instanceToUse = getPublicInstance(instance); + break; + default: + instanceToUse = instance; + } + if ("function" === typeof ref) + if (shouldProfile(current)) try { - startLayoutEffectTimer(), - commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + startLayoutEffectTimer(), (current.refCleanup = ref(instanceToUse)); } finally { - recordLayoutEffectDuration(finishedWork); - } - else commitHookEffectListUnmount(4, finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 1: - safelyDetachRef(finishedWork, finishedWork.return); - var instance = finishedWork.stateNode; - if ("function" === typeof instance.componentWillUnmount) { - var current = finishedWork, - nearestMountedAncestor = finishedWork.return; - try { - callComponentWillUnmountWithTimer(current, instance); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); + recordLayoutEffectDuration(current); } - } - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 26: - case 27: - case 5: - safelyDetachRef(finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 22: - safelyDetachRef(finishedWork, finishedWork.return); - null === finishedWork.memoizedState && - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - default: - recursivelyTraverseDisappearLayoutEffects(finishedWork); + else current.refCleanup = ref(instanceToUse); + else ref.current = instanceToUse; } - parentFiber = parentFiber.sibling; + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); } } -function recursivelyTraverseReappearLayoutEffects( - finishedRoot$jscomp$0, - parentFiber, - includeWorkInProgressEffects -) { - includeWorkInProgressEffects = - includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var current = parentFiber.alternate, - finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - commitHookLayoutEffects(finishedWork, 4); - break; - case 1: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - finishedRoot = finishedWork.stateNode; - if ("function" === typeof finishedRoot.componentDidMount) +function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref, + refCleanup = current.refCleanup; + if (null !== ref) + if ("function" === typeof refCleanup) + try { + if (shouldProfile(current)) try { - finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); + startLayoutEffectTimer(), refCleanup(); + } finally { + recordLayoutEffectDuration(current); } - current = finishedWork.updateQueue; - if (null !== current) { - var hiddenCallbacks = current.shared.hiddenCallbacks; - if (null !== hiddenCallbacks) - for ( - current.shared.hiddenCallbacks = null, current = 0; - current < hiddenCallbacks.length; - current++ - ) - callCallback(hiddenCallbacks[current], finishedRoot); - } - includeWorkInProgressEffects && - flags & 64 && - commitClassCallbacks(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 26: - case 27: - case 5: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - includeWorkInProgressEffects && - null === current && - flags & 4 && - commitHostComponentMount(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - includeWorkInProgressEffects && - flags & 4 && - commitProfilerUpdate(finishedWork, current); - break; - case 13: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 22: - null === finishedWork.memoizedState && - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - default: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - } - parentFiber = parentFiber.sibling; + else refCleanup(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } finally { + (current.refCleanup = null), + (current = current.alternate), + null != current && (current.refCleanup = null); + } + else if ("function" === typeof ref) + try { + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), ref(null); + } finally { + recordLayoutEffectDuration(current); + } + else ref(null); + } catch (error$84) { + captureCommitPhaseError(current, nearestMountedAncestor, error$84); + } + else ref.current = null; +} +function safelyCallDestroy(current, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); } } -function commitHookPassiveMountEffects(finishedWork, hookFlags) { +var shouldFireAfterActiveInstanceBlur = !1; +function commitBeforeMutationEffects(root, firstChild) { + for (nextEffect = firstChild; null !== nextEffect; ) + if ( + ((root = nextEffect), + (firstChild = root.child), + 0 !== (root.subtreeFlags & 1028) && null !== firstChild) + ) + (firstChild.return = root), (nextEffect = firstChild); + else + for (; null !== nextEffect; ) { + root = nextEffect; + try { + var current = root.alternate, + flags = root.flags; + switch (root.tag) { + case 0: + break; + case 11: + case 15: + break; + case 1: + if (0 !== (flags & 1024) && null !== current) { + var prevProps = current.memoizedProps, + prevState = current.memoizedState, + instance = root.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + root.elementType === root.type + ? prevProps + : resolveDefaultProps(root.type, prevProps), + prevState + ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + case 3: + break; + case 5: + case 26: + case 27: + case 6: + case 4: + case 17: + break; + default: + if (0 !== (flags & 1024)) + throw Error( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + } catch (error) { + captureCommitPhaseError(root, root.return, error); + } + firstChild = root.sibling; + if (null !== firstChild) { + firstChild.return = root.return; + nextEffect = firstChild; + break; + } + nextEffect = root.return; + } + current = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = !1; + return current; +} +function commitHookEffectListUnmount( + flags, + finishedWork, + nearestMountedAncestor +) { + var updateQueue = finishedWork.updateQueue; + updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; + if (null !== updateQueue) { + var effect = (updateQueue = updateQueue.next); + do { + if ((effect.tag & flags) === flags) { + var inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + ((inst.destroy = void 0), + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); + } + effect = effect.next; + } while (effect !== updateQueue); + } +} +function commitHookEffectListMount(flags, finishedWork) { + finishedWork = finishedWork.updateQueue; + finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; + if (null !== finishedWork) { + var effect = (finishedWork = finishedWork.next); + do { + if ((effect.tag & flags) === flags) { + var create$85 = effect.create, + inst = effect.inst; + create$85 = create$85(); + inst.destroy = create$85; + } + effect = effect.next; + } while (effect !== finishedWork); + } +} +function commitHookLayoutEffects(finishedWork, hookFlags) { if (shouldProfile(finishedWork)) { - passiveEffectStartTime = now(); try { - commitHookEffectListMount(hookFlags, finishedWork); + startLayoutEffectTimer(), + commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } - recordPassiveEffectDuration(finishedWork); + recordLayoutEffectDuration(finishedWork); } else try { commitHookEffectListMount(hookFlags, finishedWork); - } catch (error$103) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$103); + } catch (error$87) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$87); } } -function recursivelyTraversePassiveMountEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveMountOnFiber(root, parentFiber), - (parentFiber = parentFiber.sibling); +function commitClassCallbacks(finishedWork) { + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var instance = finishedWork.stateNode; + try { + commitCallbacks(updateQueue, instance); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } } -function commitPassiveMountOnFiber(finishedRoot, finishedWork) { +function commitHostComponentMount(finishedWork) { + try { + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } +} +function commitProfilerUpdate(finishedWork, current) { + if (executionContext & 4) + try { + var _finishedWork$memoize2 = finishedWork.memoizedProps, + onCommit = _finishedWork$memoize2.onCommit, + onRender = _finishedWork$memoize2.onRender, + effectDuration = finishedWork.stateNode.effectDuration; + _finishedWork$memoize2 = commitTime; + current = null === current ? "mount" : "update"; + currentUpdateIsNested && (current = "nested-update"); + "function" === typeof onRender && + onRender( + finishedWork.memoizedProps.id, + current, + finishedWork.actualDuration, + finishedWork.treeBaseDuration, + finishedWork.actualStartTime, + _finishedWork$memoize2 + ); + "function" === typeof onCommit && + onCommit( + finishedWork.memoizedProps.id, + current, + effectDuration, + _finishedWork$memoize2 + ); + enqueuePendingPassiveProfilerEffect(finishedWork); + var parentFiber = finishedWork.return; + a: for (; null !== parentFiber; ) { + switch (parentFiber.tag) { + case 3: + parentFiber.stateNode.effectDuration += effectDuration; + break a; + case 12: + parentFiber.stateNode.effectDuration += effectDuration; + break a; + } + parentFiber = parentFiber.return; + } + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } +} +function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { var flags = finishedWork.flags; switch (finishedWork.tag) { case 0: case 11: case 15: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); - break; - case 3: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - break; - case 23: - break; - case 22: - flags = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : finishedWork.mode & 1 || - ((flags._visibility |= 4), - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) - : flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : ((flags._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitHookLayoutEffects(finishedWork, 5); break; - default: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - } -} -function recursivelyTraverseReconnectPassiveEffects( - finishedRoot$jscomp$0, - parentFiber -) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - commitHookPassiveMountEffects(finishedWork, 8); - break; - case 23: - break; - case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? instance._visibility & 4 - ? recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - ) - : finishedWork.mode & 1 || - ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )) - : ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - break; - default: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - } - parentFiber = parentFiber.sibling; - } -} -var suspenseyCommitFlag = 8192; -function recursivelyAccumulateSuspenseyCommit(parentFiber) { - if (parentFiber.subtreeFlags & suspenseyCommitFlag) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - accumulateSuspenseyCommitOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); -} -function accumulateSuspenseyCommitOnFiber(fiber) { - switch (fiber.tag) { - case 26: - recursivelyAccumulateSuspenseyCommit(fiber); - if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) - throw Error( - "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." - ); + case 1: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 4) + if (((finishedRoot = finishedWork.stateNode), null === current)) + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + finishedRoot.componentDidMount(); + } catch (error$88) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$88 + ); + } + else { + var prevProps = + finishedWork.elementType === finishedWork.type + ? current.memoizedProps + : resolveDefaultProps(finishedWork.type, current.memoizedProps); + current = current.memoizedState; + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$89) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$89 + ); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$90) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$90 + ); + } + } + flags & 64 && commitClassCallbacks(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); + break; + case 3: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { + finishedRoot = null; + if (null !== finishedWork.child) + switch (finishedWork.child.tag) { + case 27: + case 5: + finishedRoot = getPublicInstance(finishedWork.child.stateNode); + break; + case 1: + finishedRoot = finishedWork.child.stateNode; + } + try { + commitCallbacks(flags, finishedRoot); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } break; + case 26: + case 27: case 5: - recursivelyAccumulateSuspenseyCommit(fiber); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + null === current && flags & 4 && commitHostComponentMount(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); break; - case 3: - case 4: - recursivelyAccumulateSuspenseyCommit(fiber); + case 12: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitProfilerUpdate(finishedWork, current); + break; + case 13: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); break; case 22: - if (null === fiber.memoizedState) { - var current = fiber.alternate; - null !== current && null !== current.memoizedState - ? ((current = suspenseyCommitFlag), - (suspenseyCommitFlag = 16777216), - recursivelyAccumulateSuspenseyCommit(fiber), - (suspenseyCommitFlag = current)) - : recursivelyAccumulateSuspenseyCommit(fiber); - } + if (0 !== (finishedWork.mode & 1)) { + if ( + ((prevProps = + null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), + !prevProps) + ) { + current = + (null !== current && null !== current.memoizedState) || + offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevProps; + (offscreenSubtreeWasHidden = current) && + !prevOffscreenSubtreeWasHidden + ? recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + 0 !== (finishedWork.subtreeFlags & 8772) + ) + : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } + } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && + ("manual" === finishedWork.memoizedProps.mode + ? safelyAttachRef(finishedWork, finishedWork.return) + : safelyDetachRef(finishedWork, finishedWork.return)); break; default: - recursivelyAccumulateSuspenseyCommit(fiber); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); } } -function detachAlternateSiblings(parentFiber) { - var previousFiber = parentFiber.alternate; - if ( - null !== previousFiber && - ((parentFiber = previousFiber.child), null !== parentFiber) - ) { - previousFiber.child = null; - do - (previousFiber = parentFiber.sibling), - (parentFiber.sibling = null), - (parentFiber = previousFiber); - while (null !== parentFiber); - } +function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; + null !== alternate && + ((fiber.alternate = null), detachFiberAfterEffects(alternate)); + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + fiber.stateNode = null; + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; } -function commitHookPassiveUnmountEffects( - finishedWork, +function recursivelyTraverseDeletionEffects( + finishedRoot, nearestMountedAncestor, - hookFlags + parent ) { - shouldProfile(finishedWork) - ? ((passiveEffectStartTime = now()), - commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor - ), - recordPassiveEffectDuration(finishedWork)) - : commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor - ); + for (parent = parent.child; null !== parent; ) + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), + (parent = parent.sibling); } -function recursivelyTraversePassiveUnmountEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveUnmountOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); -} -function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { +function commitDeletionEffectsOnFiber( + finishedRoot, + nearestMountedAncestor, + deletedFiber +) { + if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) + try { + injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); + } catch (err) {} + switch (deletedFiber.tag) { + case 26: + case 27: + case 5: + offscreenSubtreeWasHidden || + safelyDetachRef(deletedFiber, nearestMountedAncestor); + case 6: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 18: + break; + case 4: + createChildNodeSet(); + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; case 0: case 11: + case 14: case 15: - recursivelyTraversePassiveUnmountEffects(finishedWork); - finishedWork.flags & 2048 && - commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, 9); + if (!offscreenSubtreeWasHidden) { + var updateQueue = deletedFiber.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + ) { + var effect = (updateQueue = updateQueue.next); + do { + var tag = effect.tag, + inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + (0 !== (tag & 2) + ? ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )) + : 0 !== (tag & 4) && + (shouldProfile(deletedFiber) + ? (startLayoutEffectTimer(), + (inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + ), + recordLayoutEffectDuration(deletedFiber)) + : ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )))); + effect = effect.next; + } while (effect !== updateQueue); + } + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 1: + if ( + !offscreenSubtreeWasHidden && + (safelyDetachRef(deletedFiber, nearestMountedAncestor), + (updateQueue = deletedFiber.stateNode), + "function" === typeof updateQueue.componentWillUnmount) + ) + try { + callComponentWillUnmountWithTimer(deletedFiber, updateQueue); + } catch (error) { + captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 21: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState && - instance._visibility & 4 && - (null === finishedWork.return || 13 !== finishedWork.return.tag) - ? ((instance._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(finishedWork)) - : recursivelyTraversePassiveUnmountEffects(finishedWork); + safelyDetachRef(deletedFiber, nearestMountedAncestor); + deletedFiber.mode & 1 + ? ((offscreenSubtreeWasHidden = + (updateQueue = offscreenSubtreeWasHidden) || + null !== deletedFiber.memoizedState), + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ), + (offscreenSubtreeWasHidden = updateQueue)) + : recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; default: - recursivelyTraversePassiveUnmountEffects(finishedWork); + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); } } -function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - deletions = parentFiber; - switch (deletions.tag) { - case 0: - case 11: - case 15: - commitHookPassiveUnmountEffects(deletions, deletions.return, 8); - recursivelyTraverseDisconnectPassiveEffects(deletions); - break; - case 22: - i = deletions.stateNode; - i._visibility & 4 && - ((i._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(deletions)); - break; - default: - recursivelyTraverseDisconnectPassiveEffects(deletions); - } - parentFiber = parentFiber.sibling; +function getRetryCache(finishedWork) { + switch (finishedWork.tag) { + case 13: + case 19: + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); + return retryCache; + case 22: + return ( + (finishedWork = finishedWork.stateNode), + (retryCache = finishedWork._retryCache), + null === retryCache && + (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), + retryCache + ); + default: + throw Error( + "Unexpected Suspense handler tag (" + + finishedWork.tag + + "). This is a bug in React." + ); } } -function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - deletedSubtreeRoot, - nearestMountedAncestor -) { - for (; null !== nextEffect; ) { - var fiber = nextEffect; - switch (fiber.tag) { - case 0: - case 11: - case 15: - commitHookPassiveUnmountEffects(fiber, nearestMountedAncestor, 8); +function attachSuspenseRetryListeners(finishedWork, wakeables) { + var retryCache = getRetryCache(finishedWork); + wakeables.forEach(function (wakeable) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); + if (isDevToolsPresent) + if (null !== inProgressLanes && null !== inProgressRoot) + restorePendingUpdaters(inProgressRoot, inProgressLanes); + else + throw Error( + "Expected finished root and lanes to be set. This is a bug in React." + ); + wakeable.then(retry, retry); } - var child = fiber.child; - if (null !== child) (child.return = fiber), (nextEffect = child); - else - a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { - child = nextEffect; - var sibling = child.sibling, - returnFiber = child.return; - detachFiberAfterEffects(child); - if (child === fiber) { - nextEffect = null; - break a; - } - if (null !== sibling) { - sibling.return = returnFiber; - nextEffect = sibling; - break a; - } - nextEffect = returnFiber; - } - } + }); } -var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, - executionContext = 0, - workInProgressRoot = null, - workInProgress = null, - workInProgressRootRenderLanes = 0, - workInProgressSuspendedReason = 0, - workInProgressThrownValue = null, - workInProgressRootDidAttachPingListener = !1, - entangledRenderLanes = 0, - workInProgressRootExitStatus = 0, - workInProgressRootFatalError = null, - workInProgressRootSkippedLanes = 0, - workInProgressRootInterleavedUpdatedLanes = 0, - workInProgressRootPingedLanes = 0, - workInProgressDeferredLane = 0, - workInProgressRootConcurrentErrors = null, - workInProgressRootRecoverableErrors = null, - globalMostRecentFallbackTime = 0, - workInProgressRootRenderTargetTime = Infinity, - workInProgressTransitions = null, - hasUncaughtError = !1, - firstUncaughtError = null, - legacyErrorBoundariesThatAlreadyFailed = null, - rootDoesHavePassiveEffects = !1, - rootWithPendingPassiveEffects = null, - pendingPassiveEffectsLanes = 0, - pendingPassiveProfilerEffects = [], - nestedUpdateCount = 0, - rootWithNestedUpdates = null; -function requestUpdateLane(fiber) { - if (0 === (fiber.mode & 1)) return 2; - if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) - return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; - fiber = ReactCurrentBatchConfig$1.transition; - null !== fiber && fiber._callbacks.add(handleAsyncAction); - if (null !== fiber) - return ( - 0 === currentEventTransitionLane && - (currentEventTransitionLane = claimNextTransitionLane()), - currentEventTransitionLane - ); - fiber = currentUpdatePriority; - if (0 === fiber) - a: { - fiber = fabricGetCurrentEventPriority - ? fabricGetCurrentEventPriority() - : null; - if (null != fiber) - switch (fiber) { - case FabricDiscretePriority: - fiber = 2; - break a; - } - fiber = 32; - } - return fiber; +function commitMutationEffects(root, finishedWork, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + commitMutationEffectsOnFiber(finishedWork, root); + inProgressRoot = inProgressLanes = null; } -function scheduleUpdateOnFiber(root, fiber, lane) { - if ( - (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || - null !== root.cancelPendingCommit - ) - prepareFreshStack(root, 0), - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); - markRootUpdated(root, lane); - if (0 === (executionContext & 2) || root !== workInProgressRoot) - isDevToolsPresent && addFiberToLanesMap(root, fiber, lane), - root === workInProgressRoot && - (0 === (executionContext & 2) && - (workInProgressRootInterleavedUpdatedLanes |= lane), - 4 === workInProgressRootExitStatus && - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - )), - ensureRootIsScheduled(root), - 2 === lane && - 0 === executionContext && - 0 === (fiber.mode & 1) && - ((workInProgressRootRenderTargetTime = now$1() + 500), - flushSyncWorkAcrossRoots_impl(!0)); +function recursivelyTraverseMutationEffects(root, parentFiber) { + var deletions = parentFiber.deletions; + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + commitDeletionEffectsOnFiber(root, parentFiber, childToDelete); + var alternate = childToDelete.alternate; + null !== alternate && (alternate.return = null); + childToDelete.return = null; + } catch (error) { + captureCommitPhaseError(childToDelete, parentFiber, error); + } + } + if (parentFiber.subtreeFlags & 12854) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitMutationEffectsOnFiber(parentFiber, root), + (parentFiber = parentFiber.sibling); } -function performConcurrentWorkOnRoot(root, didTimeout) { - nestedUpdateScheduled = currentUpdateIsNested = !1; - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var originalCallbackNode = root.callbackNode; - if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) - return null; - var lanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : 0 - ); - if (0 === lanes) return null; - var exitStatus = (didTimeout = - 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) - ? renderRootConcurrent(root, lanes) - : renderRootSync(root, lanes); - if (0 !== exitStatus) { - var renderWasConcurrent = didTimeout; - do { - if (6 === exitStatus) markRootSuspended(root, lanes, 0); - else { - didTimeout = root.current.alternate; - if ( - renderWasConcurrent && - !isRenderConsistentWithExternalStores(didTimeout) - ) { - exitStatus = renderRootSync(root, lanes); - renderWasConcurrent = !1; - continue; - } - if (2 === exitStatus) { - renderWasConcurrent = lanes; - var errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - renderWasConcurrent - ); - 0 !== errorRetryLanes && - ((lanes = errorRetryLanes), - (exitStatus = recoverFromConcurrentError( - root, - renderWasConcurrent, - errorRetryLanes - ))); +function commitMutationEffectsOnFiber(finishedWork, root) { + var current = finishedWork.alternate, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + try { + commitHookEffectListUnmount(3, finishedWork, finishedWork.return), + commitHookEffectListMount(3, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } - if (1 === exitStatus) - throw ( - ((originalCallbackNode = workInProgressRootFatalError), - prepareFreshStack(root, 0), - markRootSuspended(root, lanes, 0), - ensureRootIsScheduled(root), - originalCallbackNode) - ); - root.finishedWork = didTimeout; - root.finishedLanes = lanes; - a: { - renderWasConcurrent = root; - switch (exitStatus) { - case 0: - case 1: - throw Error("Root did not complete. This is a bug in React."); - case 4: - if ((lanes & 4194176) === lanes) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane - ); - break a; - } - break; - case 2: - case 3: - case 5: - break; - default: - throw Error("Unknown root exit status."); - } - if ( - (lanes & 62914560) === lanes && - 3 === exitStatus && - ((exitStatus = globalMostRecentFallbackTime + 300 - now$1()), - 10 < exitStatus) - ) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$93) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$93 ); - if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; - renderWasConcurrent.timeoutHandle = scheduleTimeout( - commitRootWhenReady.bind( - null, - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ), - exitStatus + } + recordLayoutEffectDuration(finishedWork); + } else + try { + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$94) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$94 ); - break a; } - commitRootWhenReady( - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ); - } } break; - } while (1); - } - ensureRootIsScheduled(root); - scheduleTaskForRootDuringMicrotask(root, now$1()); - root = - root.callbackNode === originalCallbackNode - ? performConcurrentWorkOnRoot.bind(null, root) - : null; - return root; -} -function recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes -) { - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, - JSCompiler_inline_result; - (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && - (prepareFreshStack(root, errorRetryLanes).flags |= 256); - errorRetryLanes = renderRootSync(root, errorRetryLanes); - if (2 !== errorRetryLanes) { - if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) - return ( - (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), - (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), - 4 - ); - root = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - null !== root && queueRecoverableErrors(root); + case 1: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + flags & 64 && + offscreenSubtreeIsHidden && + ((finishedWork = finishedWork.updateQueue), + null !== finishedWork && + ((flags = finishedWork.callbacks), + null !== flags && + ((current = finishedWork.shared.hiddenCallbacks), + (finishedWork.shared.hiddenCallbacks = + null === current ? flags : current.concat(flags))))); + break; + case 26: + case 27: + case 5: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + break; + case 6: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 3: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 4: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 13: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + finishedWork.child.flags & 8192 && + ((current = null !== current && null !== current.memoizedState), + null === finishedWork.memoizedState || + current || + (globalMostRecentFallbackTime = now$1())); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 22: + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + var isHidden = null !== finishedWork.memoizedState, + wasHidden = null !== current && null !== current.memoizedState; + if (finishedWork.mode & 1) { + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; + recursivelyTraverseMutationEffects(root, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + } else recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + root = finishedWork.stateNode; + root._current = finishedWork; + root._visibility &= -3; + root._visibility |= root._pendingVisibility & 2; + flags & 8192 && + ((root._visibility = isHidden + ? root._visibility & -2 + : root._visibility | 1), + isHidden && + ((isHidden = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), + null === current || + wasHidden || + isHidden || + (0 !== (finishedWork.mode & 1) && + recursivelyTraverseDisappearLayoutEffects(finishedWork)))); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((current = flags.retryQueue), + null !== current && + ((flags.retryQueue = null), + attachSuspenseRetryListeners(finishedWork, current)))); + break; + case 19: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 21: + break; + default: + recursivelyTraverseMutationEffects(root, finishedWork), + commitReconciliationEffects(finishedWork); } - return errorRetryLanes; } -function queueRecoverableErrors(errors) { - null === workInProgressRootRecoverableErrors - ? (workInProgressRootRecoverableErrors = errors) - : workInProgressRootRecoverableErrors.push.apply( - workInProgressRootRecoverableErrors, - errors - ); +function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + flags & 2 && (finishedWork.flags &= -3); + flags & 4096 && (finishedWork.flags &= -4097); } -function commitRootWhenReady( - root, - finishedWork, - recoverableErrors, - transitions, - lanes, - spawnedLane -) { - 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); - commitRoot(root, recoverableErrors, transitions, spawnedLane); +function commitLayoutEffects(finishedWork, root, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); + inProgressRoot = inProgressLanes = null; } -function isRenderConsistentWithExternalStores(finishedWork) { - for (var node = finishedWork; ; ) { - if (node.flags & 16384) { - var updateQueue = node.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.stores), null !== updateQueue) - ) - for (var i = 0; i < updateQueue.length; i++) { - var check = updateQueue[i], - getSnapshot = check.getSnapshot; - check = check.value; +function recursivelyTraverseLayoutEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 8772) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), + (parentFiber = parentFiber.sibling); +} +function recursivelyTraverseDisappearLayoutEffects(parentFiber) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + if (shouldProfile(finishedWork)) try { - if (!objectIs(getSnapshot(), check)) return !1; + startLayoutEffectTimer(), + commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + else commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 1: + safelyDetachRef(finishedWork, finishedWork.return); + var instance = finishedWork.stateNode; + if ("function" === typeof instance.componentWillUnmount) { + var current = finishedWork, + nearestMountedAncestor = finishedWork.return; + try { + callComponentWillUnmountWithTimer(current, instance); } catch (error) { - return !1; + captureCommitPhaseError(current, nearestMountedAncestor, error); } } + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 26: + case 27: + case 5: + safelyDetachRef(finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 22: + safelyDetachRef(finishedWork, finishedWork.return); + null === finishedWork.memoizedState && + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + default: + recursivelyTraverseDisappearLayoutEffects(finishedWork); } - updateQueue = node.child; - if (node.subtreeFlags & 16384 && null !== updateQueue) - (updateQueue.return = node), (node = updateQueue); - else { - if (node === finishedWork) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === finishedWork) return !0; - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - return !0; -} -function markRootSuspended(root, suspendedLanes, spawnedLane) { - suspendedLanes &= ~workInProgressRootPingedLanes; - suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - for ( - var expirationTimes = root.expirationTimes, lanes = suspendedLanes; - 0 < lanes; - - ) { - var index$4 = 31 - clz32(lanes), - lane = 1 << index$4; - expirationTimes[index$4] = -1; - lanes &= ~lane; - } - 0 !== spawnedLane && - markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); -} -function resetWorkInProgressStack() { - if (null !== workInProgress) { - if (0 === workInProgressSuspendedReason) - var interruptedWork = workInProgress.return; - else - (interruptedWork = workInProgress), - resetContextDependencies(), - resetHooksOnUnwind(interruptedWork), - (thenableState$1 = null), - (thenableIndexCounter$1 = 0), - (interruptedWork = workInProgress); - for (; null !== interruptedWork; ) - unwindInterruptedWork(interruptedWork.alternate, interruptedWork), - (interruptedWork = interruptedWork.return); - workInProgress = null; + parentFiber = parentFiber.sibling; } } -function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = 0; - var timeoutHandle = root.timeoutHandle; - -1 !== timeoutHandle && - ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); - timeoutHandle = root.cancelPendingCommit; - null !== timeoutHandle && - ((root.cancelPendingCommit = null), timeoutHandle()); - resetWorkInProgressStack(); - workInProgressRoot = root; - workInProgress = timeoutHandle = createWorkInProgress(root.current, null); - workInProgressRootRenderLanes = lanes; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - workInProgressRootDidAttachPingListener = !1; - workInProgressRootExitStatus = 0; - workInProgressRootFatalError = null; - workInProgressDeferredLane = - workInProgressRootPingedLanes = - workInProgressRootInterleavedUpdatedLanes = - workInProgressRootSkippedLanes = - 0; - workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = - null; - 0 !== (lanes & 8) && (lanes |= lanes & 32); - var allEntangledLanes = root.entangledLanes; - if (0 !== allEntangledLanes) - for ( - root = root.entanglements, allEntangledLanes &= lanes; - 0 < allEntangledLanes; - - ) { - var index$2 = 31 - clz32(allEntangledLanes), - lane = 1 << index$2; - lanes |= root[index$2]; - allEntangledLanes &= ~lane; +function recursivelyTraverseReappearLayoutEffects( + finishedRoot$jscomp$0, + parentFiber, + includeWorkInProgressEffects +) { + includeWorkInProgressEffects = + includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var current = parentFiber.alternate, + finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + commitHookLayoutEffects(finishedWork, 4); + break; + case 1: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + finishedRoot = finishedWork.stateNode; + if ("function" === typeof finishedRoot.componentDidMount) + try { + finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + current = finishedWork.updateQueue; + if (null !== current) { + var hiddenCallbacks = current.shared.hiddenCallbacks; + if (null !== hiddenCallbacks) + for ( + current.shared.hiddenCallbacks = null, current = 0; + current < hiddenCallbacks.length; + current++ + ) + callCallback(hiddenCallbacks[current], finishedRoot); + } + includeWorkInProgressEffects && + flags & 64 && + commitClassCallbacks(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 26: + case 27: + case 5: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + includeWorkInProgressEffects && + null === current && + flags & 4 && + commitHostComponentMount(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 12: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + includeWorkInProgressEffects && + flags & 4 && + commitProfilerUpdate(finishedWork, current); + break; + case 13: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 22: + null === finishedWork.memoizedState && + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + default: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); } - entangledRenderLanes = lanes; - finishQueueingConcurrentUpdates(); - return timeoutHandle; -} -function handleThrow(root, thrownValue) { - currentlyRenderingFiber$1 = null; - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - ReactCurrentOwner.current = null; - thrownValue === SuspenseException - ? ((thrownValue = getSuspendedThenable()), - (root = suspenseHandlerStackCursor.current), - (workInProgressSuspendedReason = - (null !== root && - ((workInProgressRootRenderLanes & 4194176) === - workInProgressRootRenderLanes - ? null !== shellBoundary - : ((workInProgressRootRenderLanes & 62914560) !== - workInProgressRootRenderLanes && - 0 === (workInProgressRootRenderLanes & 536870912)) || - root !== shellBoundary)) || - 0 !== (workInProgressRootSkippedLanes & 134217727) || - 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) - ? 3 - : 2)) - : thrownValue === SuspenseyCommitException - ? ((thrownValue = getSuspendedThenable()), - (workInProgressSuspendedReason = 4)) - : (workInProgressSuspendedReason = - thrownValue === SelectiveHydrationException - ? 8 - : null !== thrownValue && - "object" === typeof thrownValue && - "function" === typeof thrownValue.then - ? 6 - : 1); - workInProgressThrownValue = thrownValue; - root = workInProgress; - null === root - ? ((workInProgressRootExitStatus = 1), - (workInProgressRootFatalError = thrownValue)) - : root.mode & 2 && stopProfilerTimerIfRunningAndRecordDelta(root, !0); -} -function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; -} -function renderDidSuspendDelayIfPossible() { - workInProgressRootExitStatus = 4; - (0 === (workInProgressRootSkippedLanes & 134217727) && - 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || - null === workInProgressRoot || - markRootSuspended( - workInProgressRoot, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); + parentFiber = parentFiber.sibling; + } } -function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - 0 < memoizedUpdaters.size && - (restorePendingUpdaters(root, workInProgressRootRenderLanes), - memoizedUpdaters.clear()); - movePendingFibersToMemoized(root, lanes); +function commitHookPassiveMountEffects(finishedWork, hookFlags) { + if (shouldProfile(finishedWork)) { + passiveEffectStartTime = now(); + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } - workInProgressTransitions = null; - prepareFreshStack(root, lanes); - } - lanes = !1; - a: do + recordPassiveEffectDuration(finishedWork); + } else try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - memoizedUpdaters = workInProgress; - var thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - case 3: - case 2: - lanes || - null !== suspenseHandlerStackCursor.current || - (lanes = !0); - default: - (workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, memoizedUpdaters, thrownValue); - } - } - workLoopSync(); - break; - } catch (thrownValue$104) { - handleThrow(root, thrownValue$104); + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error$102) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$102); } - while (1); - lanes && root.shellSuspendCounter++; - resetContextDependencies(); - executionContext = prevExecutionContext; - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - throw Error( - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; } -function workLoopSync() { - for (; null !== workInProgress; ) performUnitOfWork(workInProgress); +function recursivelyTraversePassiveMountEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveMountOnFiber(root, parentFiber), + (parentFiber = parentFiber.sibling); } -function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - 0 < memoizedUpdaters.size && - (restorePendingUpdaters(root, workInProgressRootRenderLanes), - memoizedUpdaters.clear()); - movePendingFibersToMemoized(root, lanes); - } - workInProgressTransitions = null; - workInProgressRootRenderTargetTime = now$1() + 500; - prepareFreshStack(root, lanes); - } - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) - b: switch ( - ((lanes = workInProgress), - (memoizedUpdaters = workInProgressThrownValue), - workInProgressSuspendedReason) - ) { - case 1: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 2: - if (isThenableResolved(memoizedUpdaters)) { - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(lanes); - break; - } - lanes = function () { - 2 === workInProgressSuspendedReason && - workInProgressRoot === root && - (workInProgressSuspendedReason = 7); - ensureRootIsScheduled(root); - }; - memoizedUpdaters.then(lanes, lanes); - break a; - case 3: - workInProgressSuspendedReason = 7; - break a; - case 4: - workInProgressSuspendedReason = 5; - break a; - case 7: - isThenableResolved(memoizedUpdaters) - ? ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - replaySuspendedUnitOfWork(lanes)) - : ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters)); - break; - case 5: - switch (workInProgress.tag) { - case 5: - case 26: - case 27: - lanes = workInProgress; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - var sibling = lanes.sibling; - if (null !== sibling) workInProgress = sibling; - else { - var returnFiber = lanes.return; - null !== returnFiber - ? ((workInProgress = returnFiber), - completeUnitOfWork(returnFiber)) - : (workInProgress = null); - } - break b; - } - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 6: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - default: - throw Error("Unexpected SuspendedReason. This is a bug in React."); - } - workLoopConcurrent(); - break; - } catch (thrownValue$106) { - handleThrow(root, thrownValue$106); - } - while (1); - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - executionContext = prevExecutionContext; - if (null !== workInProgress) return 0; - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; -} -function workLoopConcurrent() { - for (; null !== workInProgress && !shouldYield(); ) - performUnitOfWork(workInProgress); -} -function performUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate; - 0 !== (unitOfWork.mode & 2) - ? (startProfilerTimer(unitOfWork), - (current = beginWork(current, unitOfWork, entangledRenderLanes)), - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0)) - : (current = beginWork(current, unitOfWork, entangledRenderLanes)); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; -} -function replaySuspendedUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate, - isProfilingMode = 0 !== (unitOfWork.mode & 2); - isProfilingMode && startProfilerTimer(unitOfWork); - switch (unitOfWork.tag) { - case 2: - unitOfWork.tag = 0; - case 15: +function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + var flags = finishedWork.flags; + switch (finishedWork.tag) { case 0: - var Component = unitOfWork.type, - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(unitOfWork, context); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - context, - workInProgressRootRenderLanes - ); - break; case 11: - Component = unitOfWork.type.render; - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - unitOfWork.ref, - workInProgressRootRenderLanes - ); + case 15: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + break; + case 3: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + case 23: + break; + case 22: + flags = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : finishedWork.mode & 1 || + ((flags._visibility |= 4), + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) + : flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : ((flags._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); break; - case 5: - resetHooksOnUnwind(unitOfWork); default: - unwindInterruptedWork(current, unitOfWork), - (unitOfWork = workInProgress = - resetWorkInProgress(unitOfWork, entangledRenderLanes)), - (current = beginWork(current, unitOfWork, entangledRenderLanes)); + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); } - isProfilingMode && stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; } -function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { - resetContextDependencies(); - resetHooksOnUnwind(unitOfWork); - thenableState$1 = null; - thenableIndexCounter$1 = 0; - var returnFiber = unitOfWork.return; - try { - if ( - throwException( - root, - returnFiber, - unitOfWork, - thrownValue, - workInProgressRootRenderLanes - ) - ) { - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - } catch (error) { - if (null !== returnFiber) throw ((workInProgress = returnFiber), error); - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - if (unitOfWork.flags & 32768) - a: { - root = unitOfWork; - do { - unitOfWork = unwindWork(root.alternate, root); - if (null !== unitOfWork) { - unitOfWork.flags &= 32767; - workInProgress = unitOfWork; - break a; - } - if (0 !== (root.mode & 2)) { - stopProfilerTimerIfRunningAndRecordDelta(root, !1); - unitOfWork = root.actualDuration; - for (thrownValue = root.child; null !== thrownValue; ) - (unitOfWork += thrownValue.actualDuration), - (thrownValue = thrownValue.sibling); - root.actualDuration = unitOfWork; - } - root = root.return; - null !== root && - ((root.flags |= 32768), - (root.subtreeFlags = 0), - (root.deletions = null)); - workInProgress = root; - } while (null !== root); - workInProgressRootExitStatus = 6; - workInProgress = null; +function recursivelyTraverseReconnectPassiveEffects( + finishedRoot$jscomp$0, + parentFiber +) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + commitHookPassiveMountEffects(finishedWork, 8); + break; + case 23: + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? instance._visibility & 4 + ? recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + ) + : finishedWork.mode & 1 || + ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )) + : ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); } - else completeUnitOfWork(unitOfWork); + parentFiber = parentFiber.sibling; + } } -function completeUnitOfWork(unitOfWork) { - var completedWork = unitOfWork; - do { - var current = completedWork.alternate; - unitOfWork = completedWork.return; - 0 === (completedWork.mode & 2) - ? (current = completeWork(current, completedWork, entangledRenderLanes)) - : (startProfilerTimer(completedWork), - (current = completeWork(current, completedWork, entangledRenderLanes)), - stopProfilerTimerIfRunningAndRecordDelta(completedWork, !1)); - if (null !== current) { - workInProgress = current; - return; - } - completedWork = completedWork.sibling; - if (null !== completedWork) { - workInProgress = completedWork; - return; - } - workInProgress = completedWork = unitOfWork; - } while (null !== completedWork); - 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +var suspenseyCommitFlag = 8192; +function recursivelyAccumulateSuspenseyCommit(parentFiber) { + if (parentFiber.subtreeFlags & suspenseyCommitFlag) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + accumulateSuspenseyCommitOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); } -function commitRoot(root, recoverableErrors, transitions, spawnedLane) { - var previousUpdateLanePriority = currentUpdatePriority, - prevTransition = ReactCurrentBatchConfig.transition; - try { - (ReactCurrentBatchConfig.transition = null), - (currentUpdatePriority = 2), - commitRootImpl( - root, - recoverableErrors, - transitions, - previousUpdateLanePriority, - spawnedLane - ); - } finally { - (ReactCurrentBatchConfig.transition = prevTransition), - (currentUpdatePriority = previousUpdateLanePriority); +function accumulateSuspenseyCommitOnFiber(fiber) { + switch (fiber.tag) { + case 26: + recursivelyAccumulateSuspenseyCommit(fiber); + if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) + throw Error( + "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." + ); + break; + case 5: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 3: + case 4: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 22: + if (null === fiber.memoizedState) { + var current = fiber.alternate; + null !== current && null !== current.memoizedState + ? ((current = suspenseyCommitFlag), + (suspenseyCommitFlag = 16777216), + recursivelyAccumulateSuspenseyCommit(fiber), + (suspenseyCommitFlag = current)) + : recursivelyAccumulateSuspenseyCommit(fiber); + } + break; + default: + recursivelyAccumulateSuspenseyCommit(fiber); } - return null; } -function commitRootImpl( - root, - recoverableErrors, - transitions, - renderPriorityLevel, - spawnedLane +function detachAlternateSiblings(parentFiber) { + var previousFiber = parentFiber.alternate; + if ( + null !== previousFiber && + ((parentFiber = previousFiber.child), null !== parentFiber) + ) { + previousFiber.child = null; + do + (previousFiber = parentFiber.sibling), + (parentFiber.sibling = null), + (parentFiber = previousFiber); + while (null !== parentFiber); + } +} +function commitHookPassiveUnmountEffects( + finishedWork, + nearestMountedAncestor, + hookFlags ) { - do flushPassiveEffects(); - while (null !== rootWithPendingPassiveEffects); - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var finishedWork = root.finishedWork; - transitions = root.finishedLanes; - if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedLanes = 0; - if (finishedWork === root.current) - throw Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ); - root.callbackNode = null; - root.callbackPriority = 0; - root.cancelPendingCommit = null; - var remainingLanes = finishedWork.lanes | finishedWork.childLanes; - remainingLanes |= concurrentlyUpdatedLanes; - markRootFinished(root, remainingLanes, spawnedLane); - root === workInProgressRoot && - ((workInProgress = workInProgressRoot = null), - (workInProgressRootRenderLanes = 0)); - (0 === (finishedWork.subtreeFlags & 10256) && - 0 === (finishedWork.flags & 10256)) || - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); - spawnedLane = 0 !== (finishedWork.flags & 15990); - if (0 !== (finishedWork.subtreeFlags & 15990) || spawnedLane) { - spawnedLane = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = null; - remainingLanes = currentUpdatePriority; - currentUpdatePriority = 2; - var prevExecutionContext = executionContext; - executionContext |= 4; - ReactCurrentOwner.current = null; - commitBeforeMutationEffects(root, finishedWork); - commitTime = now(); - commitMutationEffects(root, finishedWork, transitions); - root.current = finishedWork; - commitLayoutEffects(finishedWork, root, transitions); - requestPaint(); - executionContext = prevExecutionContext; - currentUpdatePriority = remainingLanes; - ReactCurrentBatchConfig.transition = spawnedLane; - } else (root.current = finishedWork), (commitTime = now()); - rootDoesHavePassiveEffects && - ((rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsLanes = transitions)); - remainingLanes = root.pendingLanes; - 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - isDevToolsPresent && root.memoizedUpdaters.clear(); - ensureRootIsScheduled(root); - if (null !== recoverableErrors) - for ( - renderPriorityLevel = root.onRecoverableError, finishedWork = 0; - finishedWork < recoverableErrors.length; - finishedWork++ - ) - (spawnedLane = recoverableErrors[finishedWork]), - (remainingLanes = { - digest: spawnedLane.digest, - componentStack: spawnedLane.stack - }), - renderPriorityLevel(spawnedLane.value, remainingLanes); - if (hasUncaughtError) - throw ( - ((hasUncaughtError = !1), - (root = firstUncaughtError), - (firstUncaughtError = null), - root) - ); - 0 !== (pendingPassiveEffectsLanes & 3) && - 0 !== root.tag && - flushPassiveEffects(); - remainingLanes = root.pendingLanes; - 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) - ? ((nestedUpdateScheduled = !0), - root === rootWithNestedUpdates - ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))) - : (nestedUpdateCount = 0); - flushSyncWorkAcrossRoots_impl(!1); - return null; + shouldProfile(finishedWork) + ? ((passiveEffectStartTime = now()), + commitHookEffectListUnmount( + hookFlags, + finishedWork, + nearestMountedAncestor + ), + recordPassiveEffectDuration(finishedWork)) + : commitHookEffectListUnmount( + hookFlags, + finishedWork, + nearestMountedAncestor + ); } -function flushPassiveEffects() { - if (null !== rootWithPendingPassiveEffects) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), - prevTransition = ReactCurrentBatchConfig.transition, - previousPriority = currentUpdatePriority; - try { - ReactCurrentBatchConfig.transition = null; - currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; - if (null === rootWithPendingPassiveEffects) - var JSCompiler_inline_result = !1; - else { - renderPriority = rootWithPendingPassiveEffects; - rootWithPendingPassiveEffects = null; - pendingPassiveEffectsLanes = 0; - if (0 !== (executionContext & 6)) - throw Error("Cannot flush passive effects while already rendering."); - var prevExecutionContext = executionContext; - executionContext |= 4; - commitPassiveUnmountOnFiber(renderPriority.current); - commitPassiveMountOnFiber(renderPriority, renderPriority.current); - var profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - for (var i = 0; i < profilerEffects.length; i++) { - var finishedWork = profilerEffects[i]; - if (executionContext & 4 && 0 !== (finishedWork.flags & 4)) - switch (finishedWork.tag) { - case 12: - var passiveEffectDuration = - finishedWork.stateNode.passiveEffectDuration, - _finishedWork$memoize = finishedWork.memoizedProps, - id = _finishedWork$memoize.id, - onPostCommit = _finishedWork$memoize.onPostCommit, - commitTime$87 = commitTime, - phase = null === finishedWork.alternate ? "mount" : "update"; - currentUpdateIsNested && (phase = "nested-update"); - "function" === typeof onPostCommit && - onPostCommit(id, phase, passiveEffectDuration, commitTime$87); - var parentFiber = finishedWork.return; - b: for (; null !== parentFiber; ) { - switch (parentFiber.tag) { - case 3: - parentFiber.stateNode.passiveEffectDuration += - passiveEffectDuration; - break b; - case 12: - parentFiber.stateNode.passiveEffectDuration += - passiveEffectDuration; - break b; - } - parentFiber = parentFiber.return; - } - } - } - executionContext = prevExecutionContext; - flushSyncWorkAcrossRoots_impl(!1); - if ( - injectedHook && - "function" === typeof injectedHook.onPostCommitFiberRoot - ) - try { - injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); - } catch (err) {} - var stateNode = renderPriority.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - JSCompiler_inline_result = !0; - } - return JSCompiler_inline_result; - } finally { - (currentUpdatePriority = previousPriority), - (ReactCurrentBatchConfig.transition = prevTransition); - } - } - return !1; -} -function enqueuePendingPassiveProfilerEffect(fiber) { - pendingPassiveProfilerEffects.push(fiber); - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); -} -function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); - rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); - null !== rootFiber && - (markRootUpdated(rootFiber, 2), ensureRootIsScheduled(rootFiber)); -} -function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { - if (3 === sourceFiber.tag) - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); - else - for (; null !== nearestMountedAncestor; ) { - if (3 === nearestMountedAncestor.tag) { - captureCommitPhaseErrorOnRoot( - nearestMountedAncestor, - sourceFiber, - error +function recursivelyTraversePassiveUnmountEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber ); - break; - } else if (1 === nearestMountedAncestor.tag) { - var instance = nearestMountedAncestor.stateNode; - if ( - "function" === - typeof nearestMountedAncestor.type.getDerivedStateFromError || - ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) - ) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createClassErrorUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - nearestMountedAncestor = enqueueUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - null !== nearestMountedAncestor && - (markRootUpdated(nearestMountedAncestor, 2), - ensureRootIsScheduled(nearestMountedAncestor)); - break; - } } - nearestMountedAncestor = nearestMountedAncestor.return; - } -} -function attachPingListener(root, wakeable, lanes) { - var pingCache = root.pingCache; - if (null === pingCache) { - pingCache = root.pingCache = new PossiblyWeakMap(); - var threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else - (threadIDs = pingCache.get(wakeable)), - void 0 === threadIDs && - ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); - threadIDs.has(lanes) || - ((workInProgressRootDidAttachPingListener = !0), - threadIDs.add(lanes), - (pingCache = pingSuspendedRoot.bind(null, root, wakeable, lanes)), - isDevToolsPresent && restorePendingUpdaters(root, lanes), - wakeable.then(pingCache, pingCache)); -} -function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(wakeable); - root.pingedLanes |= root.suspendedLanes & pingedLanes; - workInProgressRoot === root && - (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && - (4 === workInProgressRootExitStatus || - (3 === workInProgressRootExitStatus && - (workInProgressRootRenderLanes & 62914560) === - workInProgressRootRenderLanes && - 300 > now$1() - globalMostRecentFallbackTime) - ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) - : (workInProgressRootPingedLanes |= pingedLanes)); - ensureRootIsScheduled(root); -} -function retryTimedOutBoundary(boundaryFiber, retryLane) { - 0 === retryLane && - (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); - boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - null !== boundaryFiber && - (markRootUpdated(boundaryFiber, retryLane), - ensureRootIsScheduled(boundaryFiber)); -} -function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState, - retryLane = 0; - null !== suspenseState && (retryLane = suspenseState.retryLane); - retryTimedOutBoundary(boundaryFiber, retryLane); + detachAlternateSiblings(parentFiber); + } + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveUnmountOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); } -function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = 0; - switch (boundaryFiber.tag) { - case 13: - var retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - null !== suspenseState && (retryLane = suspenseState.retryLane); - break; - case 19: - retryCache = boundaryFiber.stateNode; +function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveUnmountEffects(finishedWork); + finishedWork.flags & 2048 && + commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, 9); break; case 22: - retryCache = boundaryFiber.stateNode._retryCache; + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState && + instance._visibility & 4 && + (null === finishedWork.return || 13 !== finishedWork.return.tag) + ? ((instance._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(finishedWork)) + : recursivelyTraversePassiveUnmountEffects(finishedWork); break; default: - throw Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ); + recursivelyTraversePassiveUnmountEffects(finishedWork); } - null !== retryCache && retryCache.delete(wakeable); - retryTimedOutBoundary(boundaryFiber, retryLane); } -var beginWork; -beginWork = function (current, workInProgress, renderLanes) { - if (null !== current) - if ( - current.memoizedProps !== workInProgress.pendingProps || - didPerformWorkStackCursor.current - ) - didReceiveUpdate = !0; - else { - if ( - 0 === (current.lanes & renderLanes) && - 0 === (workInProgress.flags & 128) - ) - return ( - (didReceiveUpdate = !1), - attemptEarlyBailoutIfNoScheduledUpdate( - current, - workInProgress, - renderLanes - ) +function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber ); - didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; + } + detachAlternateSiblings(parentFiber); + } + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + deletions = parentFiber; + switch (deletions.tag) { + case 0: + case 11: + case 15: + commitHookPassiveUnmountEffects(deletions, deletions.return, 8); + recursivelyTraverseDisconnectPassiveEffects(deletions); + break; + case 22: + i = deletions.stateNode; + i._visibility & 4 && + ((i._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(deletions)); + break; + default: + recursivelyTraverseDisconnectPassiveEffects(deletions); } - else didReceiveUpdate = !1; - workInProgress.lanes = 0; - switch (workInProgress.tag) { - case 2: - var Component = workInProgress.type; - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - var context = getMaskedContext( - workInProgress, - contextStackCursor$1.current - ); - prepareToReadContext(workInProgress, renderLanes); - context = renderWithHooks( - null, - workInProgress, - Component, - current, - context, - renderLanes - ); - workInProgress.flags |= 1; - if ( - "object" === typeof context && - null !== context && - "function" === typeof context.render && - void 0 === context.$$typeof - ) { - workInProgress.tag = 1; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; - workInProgress.memoizedState = - null !== context.state && void 0 !== context.state - ? context.state - : null; - initializeUpdateQueue(workInProgress); - context.updater = classComponentUpdater; - workInProgress.stateNode = context; - context._reactInternals = workInProgress; - mountClassInstance(workInProgress, Component, current, renderLanes); - workInProgress = finishClassComponent( - null, - workInProgress, - Component, - !0, - hasContext, - renderLanes - ); - } else - (workInProgress.tag = 0), - reconcileChildren(null, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child); - return workInProgress; - case 16: - Component = workInProgress.elementType; - a: { - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - context = Component._init; - Component = context(Component._payload); - workInProgress.type = Component; - context = workInProgress.tag = resolveLazyComponentTag(Component); - current = resolveDefaultProps(Component, current); - switch (context) { - case 0: - workInProgress = updateFunctionComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 1: - workInProgress = updateClassComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 11: - workInProgress = updateForwardRef( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 14: - workInProgress = updateMemoComponent( - null, - workInProgress, - Component, - resolveDefaultProps(Component.type, current), - renderLanes - ); - break a; + parentFiber = parentFiber.sibling; + } +} +function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + deletedSubtreeRoot, + nearestMountedAncestor +) { + for (; null !== nextEffect; ) { + var fiber = nextEffect; + switch (fiber.tag) { + case 0: + case 11: + case 15: + commitHookPassiveUnmountEffects(fiber, nearestMountedAncestor, 8); + } + var child = fiber.child; + if (null !== child) (child.return = fiber), (nextEffect = child); + else + a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { + child = nextEffect; + var sibling = child.sibling, + returnFiber = child.return; + detachFiberAfterEffects(child); + if (child === fiber) { + nextEffect = null; + break a; } - throw Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." - ); + if (null !== sibling) { + sibling.return = returnFiber; + nextEffect = sibling; + break a; + } + nextEffect = returnFiber; } - return workInProgress; - case 0: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateFunctionComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 1: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateClassComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 3: - pushHostRootContext(workInProgress); - if (null === current) - throw Error("Should have a current fiber. This is a bug in React."); - context = workInProgress.pendingProps; - Component = workInProgress.memoizedState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, context, null, renderLanes); - context = workInProgress.memoizedState.element; - context === Component - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - )) - : (reconcileChildren(current, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child)); - return workInProgress; - case 26: - case 27: - case 5: - return ( - pushHostContext(workInProgress), - (Component = workInProgress.pendingProps.children), - markRef$1(current, workInProgress), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 6: - return null; - case 13: - return updateSuspenseComponent(current, workInProgress, renderLanes); - case 4: - return ( - pushHostContainer( - workInProgress, - workInProgress.stateNode.containerInfo - ), - (Component = workInProgress.pendingProps), - null === current - ? (workInProgress.child = reconcileChildFibers( - workInProgress, - null, - Component, - renderLanes - )) - : reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 11: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateForwardRef( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 7: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps, - renderLanes - ), - workInProgress.child - ); - case 8: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child + } +} +var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, + executionContext = 0, + workInProgressRoot = null, + workInProgress = null, + workInProgressRootRenderLanes = 0, + workInProgressSuspendedReason = 0, + workInProgressThrownValue = null, + workInProgressRootDidAttachPingListener = !1, + entangledRenderLanes = 0, + workInProgressRootExitStatus = 0, + workInProgressRootFatalError = null, + workInProgressRootSkippedLanes = 0, + workInProgressRootInterleavedUpdatedLanes = 0, + workInProgressRootPingedLanes = 0, + workInProgressDeferredLane = 0, + workInProgressRootConcurrentErrors = null, + workInProgressRootRecoverableErrors = null, + workInProgressRootDidIncludeRecursiveRenderUpdate = !1, + globalMostRecentFallbackTime = 0, + workInProgressRootRenderTargetTime = Infinity, + workInProgressTransitions = null, + hasUncaughtError = !1, + firstUncaughtError = null, + legacyErrorBoundariesThatAlreadyFailed = null, + rootDoesHavePassiveEffects = !1, + rootWithPendingPassiveEffects = null, + pendingPassiveEffectsLanes = 0, + pendingPassiveProfilerEffects = [], + nestedUpdateCount = 0, + rootWithNestedUpdates = null; +function requestUpdateLane(fiber) { + if (0 === (fiber.mode & 1)) return 2; + if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) + return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; + fiber = ReactCurrentBatchConfig$1.transition; + null !== fiber && fiber._callbacks.add(handleAsyncAction); + if (null !== fiber) + return ( + 0 === currentEventTransitionLane && + (currentEventTransitionLane = claimNextTransitionLane()), + currentEventTransitionLane + ); + fiber = currentUpdatePriority; + if (0 === fiber) + a: { + fiber = fabricGetCurrentEventPriority + ? fabricGetCurrentEventPriority() + : null; + if (null != fiber) + switch (fiber) { + case FabricDiscretePriority: + fiber = 2; + break a; + } + fiber = 32; + } + return fiber; +} +function scheduleUpdateOnFiber(root, fiber, lane) { + if ( + (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || + null !== root.cancelPendingCommit + ) + prepareFreshStack(root, 0), + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane ); - case 12: - return ( - (workInProgress.flags |= 4), - (Component = workInProgress.stateNode), - (Component.effectDuration = 0), - (Component.passiveEffectDuration = 0), - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child + markRootUpdated$1(root, lane); + if (0 === (executionContext & 2) || root !== workInProgressRoot) + isDevToolsPresent && addFiberToLanesMap(root, fiber, lane), + root === workInProgressRoot && + (0 === (executionContext & 2) && + (workInProgressRootInterleavedUpdatedLanes |= lane), + 4 === workInProgressRootExitStatus && + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane + )), + ensureRootIsScheduled(root), + 2 === lane && + 0 === executionContext && + 0 === (fiber.mode & 1) && + ((workInProgressRootRenderTargetTime = now$1() + 500), + flushSyncWorkAcrossRoots_impl(!0)); +} +function performConcurrentWorkOnRoot(root, didTimeout) { + nestedUpdateScheduled = currentUpdateIsNested = !1; + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + var originalCallbackNode = root.callbackNode; + if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) + return null; + var lanes = getNextLanes( + root, + root === workInProgressRoot ? workInProgressRootRenderLanes : 0 + ); + if (0 === lanes) return null; + var exitStatus = (didTimeout = + 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) + ? renderRootConcurrent(root, lanes) + : renderRootSync(root, lanes); + if (0 !== exitStatus) { + var renderWasConcurrent = didTimeout; + do { + if (6 === exitStatus) markRootSuspended(root, lanes, 0); + else { + didTimeout = root.current.alternate; + if ( + renderWasConcurrent && + !isRenderConsistentWithExternalStores(didTimeout) + ) { + exitStatus = renderRootSync(root, lanes); + renderWasConcurrent = !1; + continue; + } + if (2 === exitStatus) { + renderWasConcurrent = lanes; + var errorRetryLanes = getLanesToRetrySynchronouslyOnError( + root, + renderWasConcurrent + ); + 0 !== errorRetryLanes && + ((lanes = errorRetryLanes), + (exitStatus = recoverFromConcurrentError( + root, + renderWasConcurrent, + errorRetryLanes + ))); + } + if (1 === exitStatus) + throw ( + ((originalCallbackNode = workInProgressRootFatalError), + prepareFreshStack(root, 0), + markRootSuspended(root, lanes, 0), + ensureRootIsScheduled(root), + originalCallbackNode) + ); + root.finishedWork = didTimeout; + root.finishedLanes = lanes; + a: { + renderWasConcurrent = root; + switch (exitStatus) { + case 0: + case 1: + throw Error("Root did not complete. This is a bug in React."); + case 4: + if ((lanes & 4194176) === lanes) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + break a; + } + break; + case 2: + case 3: + case 5: + break; + default: + throw Error("Unknown root exit status."); + } + if ( + (lanes & 62914560) === lanes && + 3 === exitStatus && + ((exitStatus = globalMostRecentFallbackTime + 300 - now$1()), + 10 < exitStatus) + ) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; + renderWasConcurrent.timeoutHandle = scheduleTimeout( + commitRootWhenReady.bind( + null, + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ), + exitStatus + ); + break a; + } + commitRootWhenReady( + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ); + } + } + break; + } while (1); + } + ensureRootIsScheduled(root); + scheduleTaskForRootDuringMicrotask(root, now$1()); + root = + root.callbackNode === originalCallbackNode + ? performConcurrentWorkOnRoot.bind(null, root) + : null; + return root; +} +function recoverFromConcurrentError( + root, + originallyAttemptedLanes, + errorRetryLanes +) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, + JSCompiler_inline_result; + (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && + (prepareFreshStack(root, errorRetryLanes).flags |= 256); + errorRetryLanes = renderRootSync(root, errorRetryLanes); + if (2 !== errorRetryLanes) { + if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) + return ( + (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), + (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), + 4 ); - case 10: - a: { - Component = workInProgress.type._context; - context = workInProgress.pendingProps; - hasContext = workInProgress.memoizedProps; - var newValue = context.value; - push(valueCursor, Component._currentValue2); - Component._currentValue2 = newValue; - if (null !== hasContext) - if (objectIs(hasContext.value, newValue)) { - if ( - hasContext.children === context.children && - !didPerformWorkStackCursor.current - ) { - workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - ); - break a; - } - } else - for ( - hasContext = workInProgress.child, - null !== hasContext && (hasContext.return = workInProgress); - null !== hasContext; + root = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + null !== root && queueRecoverableErrors(root); + } + return errorRetryLanes; +} +function queueRecoverableErrors(errors) { + null === workInProgressRootRecoverableErrors + ? (workInProgressRootRecoverableErrors = errors) + : workInProgressRootRecoverableErrors.push.apply( + workInProgressRootRecoverableErrors, + errors + ); +} +function commitRootWhenReady( + root, + finishedWork, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + lanes, + spawnedLane +) { + 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); +} +function isRenderConsistentWithExternalStores(finishedWork) { + for (var node = finishedWork; ; ) { + if (node.flags & 16384) { + var updateQueue = node.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.stores), null !== updateQueue) + ) + for (var i = 0; i < updateQueue.length; i++) { + var check = updateQueue[i], + getSnapshot = check.getSnapshot; + check = check.value; + try { + if (!objectIs(getSnapshot(), check)) return !1; + } catch (error) { + return !1; + } + } + } + updateQueue = node.child; + if (node.subtreeFlags & 16384 && null !== updateQueue) + (updateQueue.return = node), (node = updateQueue); + else { + if (node === finishedWork) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return !0; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + } + return !0; +} +function markRootSuspended(root, suspendedLanes, spawnedLane) { + suspendedLanes &= ~workInProgressRootPingedLanes; + suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; + for ( + var expirationTimes = root.expirationTimes, lanes = suspendedLanes; + 0 < lanes; - ) { - var list = hasContext.dependencies; - if (null !== list) { - newValue = hasContext.child; - for ( - var dependency = list.firstContext; - null !== dependency; + ) { + var index$4 = 31 - clz32(lanes), + lane = 1 << index$4; + expirationTimes[index$4] = -1; + lanes &= ~lane; + } + 0 !== spawnedLane && + markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); +} +function resetWorkInProgressStack() { + if (null !== workInProgress) { + if (0 === workInProgressSuspendedReason) + var interruptedWork = workInProgress.return; + else + (interruptedWork = workInProgress), + resetContextDependencies(), + resetHooksOnUnwind(interruptedWork), + (thenableState$1 = null), + (thenableIndexCounter$1 = 0), + (interruptedWork = workInProgress); + for (; null !== interruptedWork; ) + unwindInterruptedWork(interruptedWork.alternate, interruptedWork), + (interruptedWork = interruptedWork.return); + workInProgress = null; + } +} +function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = 0; + var timeoutHandle = root.timeoutHandle; + -1 !== timeoutHandle && + ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); + timeoutHandle = root.cancelPendingCommit; + null !== timeoutHandle && + ((root.cancelPendingCommit = null), timeoutHandle()); + resetWorkInProgressStack(); + workInProgressRoot = root; + workInProgress = timeoutHandle = createWorkInProgress(root.current, null); + workInProgressRootRenderLanes = lanes; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + workInProgressRootDidAttachPingListener = !1; + workInProgressRootExitStatus = 0; + workInProgressRootFatalError = null; + workInProgressDeferredLane = + workInProgressRootPingedLanes = + workInProgressRootInterleavedUpdatedLanes = + workInProgressRootSkippedLanes = + 0; + workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = + null; + workInProgressRootDidIncludeRecursiveRenderUpdate = !1; + 0 !== (lanes & 8) && (lanes |= lanes & 32); + var allEntangledLanes = root.entangledLanes; + if (0 !== allEntangledLanes) + for ( + root = root.entanglements, allEntangledLanes &= lanes; + 0 < allEntangledLanes; - ) { - if (dependency.context === Component) { - if (1 === hasContext.tag) { - dependency = createUpdate(renderLanes & -renderLanes); - dependency.tag = 2; - var updateQueue = hasContext.updateQueue; - if (null !== updateQueue) { - updateQueue = updateQueue.shared; - var pending = updateQueue.pending; - null === pending - ? (dependency.next = dependency) - : ((dependency.next = pending.next), - (pending.next = dependency)); - updateQueue.pending = dependency; - } - } - hasContext.lanes |= renderLanes; - dependency = hasContext.alternate; - null !== dependency && (dependency.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - hasContext.return, - renderLanes, - workInProgress - ); - list.lanes |= renderLanes; - break; - } - dependency = dependency.next; - } - } else if (10 === hasContext.tag) - newValue = - hasContext.type === workInProgress.type - ? null - : hasContext.child; - else if (18 === hasContext.tag) { - newValue = hasContext.return; - if (null === newValue) - throw Error( - "We just came from a parent so we must have had a parent. This is a bug in React." - ); - newValue.lanes |= renderLanes; - list = newValue.alternate; - null !== list && (list.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - newValue, - renderLanes, - workInProgress - ); - newValue = hasContext.sibling; - } else newValue = hasContext.child; - if (null !== newValue) newValue.return = hasContext; - else - for (newValue = hasContext; null !== newValue; ) { - if (newValue === workInProgress) { - newValue = null; - break; - } - hasContext = newValue.sibling; - if (null !== hasContext) { - hasContext.return = newValue.return; - newValue = hasContext; - break; + ) { + var index$2 = 31 - clz32(allEntangledLanes), + lane = 1 << index$2; + lanes |= root[index$2]; + allEntangledLanes &= ~lane; + } + entangledRenderLanes = lanes; + finishQueueingConcurrentUpdates(); + return timeoutHandle; +} +function handleThrow(root, thrownValue) { + currentlyRenderingFiber$1 = null; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentOwner.current = null; + thrownValue === SuspenseException + ? ((thrownValue = getSuspendedThenable()), + (root = suspenseHandlerStackCursor.current), + (workInProgressSuspendedReason = + (null !== root && + ((workInProgressRootRenderLanes & 4194176) === + workInProgressRootRenderLanes + ? null !== shellBoundary + : ((workInProgressRootRenderLanes & 62914560) !== + workInProgressRootRenderLanes && + 0 === (workInProgressRootRenderLanes & 536870912)) || + root !== shellBoundary)) || + 0 !== (workInProgressRootSkippedLanes & 134217727) || + 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) + ? 3 + : 2)) + : thrownValue === SuspenseyCommitException + ? ((thrownValue = getSuspendedThenable()), + (workInProgressSuspendedReason = 4)) + : (workInProgressSuspendedReason = + thrownValue === SelectiveHydrationException + ? 8 + : null !== thrownValue && + "object" === typeof thrownValue && + "function" === typeof thrownValue.then + ? 6 + : 1); + workInProgressThrownValue = thrownValue; + root = workInProgress; + null === root + ? ((workInProgressRootExitStatus = 1), + (workInProgressRootFatalError = thrownValue)) + : root.mode & 2 && stopProfilerTimerIfRunningAndRecordDelta(root, !0); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function renderDidSuspendDelayIfPossible() { + workInProgressRootExitStatus = 4; + (0 === (workInProgressRootSkippedLanes & 134217727) && + 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || + null === workInProgressRoot || + markRootSuspended( + workInProgressRoot, + workInProgressRootRenderLanes, + workInProgressDeferredLane + ); +} +function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + 0 < memoizedUpdaters.size && + (restorePendingUpdaters(root, workInProgressRootRenderLanes), + memoizedUpdaters.clear()); + movePendingFibersToMemoized(root, lanes); + } + workInProgressTransitions = null; + prepareFreshStack(root, lanes); + } + lanes = !1; + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + memoizedUpdaters = workInProgress; + var thrownValue = workInProgressThrownValue; + switch (workInProgressSuspendedReason) { + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; + break a; + case 3: + case 2: + lanes || + null !== suspenseHandlerStackCursor.current || + (lanes = !0); + default: + (workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, memoizedUpdaters, thrownValue); + } + } + workLoopSync(); + break; + } catch (thrownValue$103) { + handleThrow(root, thrownValue$103); + } + while (1); + lanes && root.shellSuspendCounter++; + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopSync() { + for (; null !== workInProgress; ) performUnitOfWork(workInProgress); +} +function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + 0 < memoizedUpdaters.size && + (restorePendingUpdaters(root, workInProgressRootRenderLanes), + memoizedUpdaters.clear()); + movePendingFibersToMemoized(root, lanes); + } + workInProgressTransitions = null; + workInProgressRootRenderTargetTime = now$1() + 500; + prepareFreshStack(root, lanes); + } + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) + b: switch ( + ((lanes = workInProgress), + (memoizedUpdaters = workInProgressThrownValue), + workInProgressSuspendedReason) + ) { + case 1: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 2: + if (isThenableResolved(memoizedUpdaters)) { + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + replaySuspendedUnitOfWork(lanes); + break; + } + lanes = function () { + 2 === workInProgressSuspendedReason && + workInProgressRoot === root && + (workInProgressSuspendedReason = 7); + ensureRootIsScheduled(root); + }; + memoizedUpdaters.then(lanes, lanes); + break a; + case 3: + workInProgressSuspendedReason = 7; + break a; + case 4: + workInProgressSuspendedReason = 5; + break a; + case 7: + isThenableResolved(memoizedUpdaters) + ? ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + replaySuspendedUnitOfWork(lanes)) + : ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters)); + break; + case 5: + switch (workInProgress.tag) { + case 5: + case 26: + case 27: + lanes = workInProgress; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + var sibling = lanes.sibling; + if (null !== sibling) workInProgress = sibling; + else { + var returnFiber = lanes.return; + null !== returnFiber + ? ((workInProgress = returnFiber), + completeUnitOfWork(returnFiber)) + : (workInProgress = null); + } + break b; + } + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 6: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; + break a; + default: + throw Error("Unexpected SuspendedReason. This is a bug in React."); + } + workLoopConcurrent(); + break; + } catch (thrownValue$105) { + handleThrow(root, thrownValue$105); + } + while (1); + resetContextDependencies(); + ReactCurrentDispatcher.current = prevDispatcher; + executionContext = prevExecutionContext; + if (null !== workInProgress) return 0; + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopConcurrent() { + for (; null !== workInProgress && !shouldYield(); ) + performUnitOfWork(workInProgress); +} +function performUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate; + 0 !== (unitOfWork.mode & 2) + ? (startProfilerTimer(unitOfWork), + (current = beginWork(current, unitOfWork, entangledRenderLanes)), + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0)) + : (current = beginWork(current, unitOfWork, entangledRenderLanes)); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; +} +function replaySuspendedUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate, + isProfilingMode = 0 !== (unitOfWork.mode & 2); + isProfilingMode && startProfilerTimer(unitOfWork); + switch (unitOfWork.tag) { + case 2: + unitOfWork.tag = 0; + case 15: + case 0: + var Component = unitOfWork.type, + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + void 0, + workInProgressRootRenderLanes + ); + break; + case 11: + Component = unitOfWork.type.render; + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + unitOfWork.ref, + workInProgressRootRenderLanes + ); + break; + case 5: + resetHooksOnUnwind(unitOfWork); + default: + unwindInterruptedWork(current, unitOfWork), + (unitOfWork = workInProgress = + resetWorkInProgress(unitOfWork, entangledRenderLanes)), + (current = beginWork(current, unitOfWork, entangledRenderLanes)); + } + isProfilingMode && stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; +} +function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { + resetContextDependencies(); + resetHooksOnUnwind(unitOfWork); + thenableState$1 = null; + thenableIndexCounter$1 = 0; + var returnFiber = unitOfWork.return; + try { + if ( + throwException( + root, + returnFiber, + unitOfWork, + thrownValue, + workInProgressRootRenderLanes + ) + ) { + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + } catch (error) { + if (null !== returnFiber) throw ((workInProgress = returnFiber), error); + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (unitOfWork.flags & 32768) + a: { + root = unitOfWork; + do { + unitOfWork = unwindWork(root.alternate, root); + if (null !== unitOfWork) { + unitOfWork.flags &= 32767; + workInProgress = unitOfWork; + break a; + } + if (0 !== (root.mode & 2)) { + stopProfilerTimerIfRunningAndRecordDelta(root, !1); + unitOfWork = root.actualDuration; + for (thrownValue = root.child; null !== thrownValue; ) + (unitOfWork += thrownValue.actualDuration), + (thrownValue = thrownValue.sibling); + root.actualDuration = unitOfWork; + } + root = root.return; + null !== root && + ((root.flags |= 32768), + (root.subtreeFlags = 0), + (root.deletions = null)); + workInProgress = root; + } while (null !== root); + workInProgressRootExitStatus = 6; + workInProgress = null; + } + else completeUnitOfWork(unitOfWork); +} +function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + var current = completedWork.alternate; + unitOfWork = completedWork.return; + 0 === (completedWork.mode & 2) + ? (current = completeWork(current, completedWork, entangledRenderLanes)) + : (startProfilerTimer(completedWork), + (current = completeWork(current, completedWork, entangledRenderLanes)), + stopProfilerTimerIfRunningAndRecordDelta(completedWork, !1)); + if (null !== current) { + workInProgress = current; + return; + } + completedWork = completedWork.sibling; + if (null !== completedWork) { + workInProgress = completedWork; + return; + } + workInProgress = completedWork = unitOfWork; + } while (null !== completedWork); + 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +} +function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane +) { + var previousUpdateLanePriority = currentUpdatePriority, + prevTransition = ReactCurrentBatchConfig.transition; + try { + (ReactCurrentBatchConfig.transition = null), + (currentUpdatePriority = 2), + commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + previousUpdateLanePriority, + spawnedLane + ); + } finally { + (ReactCurrentBatchConfig.transition = prevTransition), + (currentUpdatePriority = previousUpdateLanePriority); + } + return null; +} +function commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + renderPriorityLevel, + spawnedLane +) { + do flushPassiveEffects(); + while (null !== rootWithPendingPassiveEffects); + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + didIncludeRenderPhaseUpdate = root.finishedWork; + transitions = root.finishedLanes; + if (null === didIncludeRenderPhaseUpdate) return null; + root.finishedWork = null; + root.finishedLanes = 0; + if (didIncludeRenderPhaseUpdate === root.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + root.callbackNode = null; + root.callbackPriority = 0; + root.cancelPendingCommit = null; + var remainingLanes = + didIncludeRenderPhaseUpdate.lanes | didIncludeRenderPhaseUpdate.childLanes; + remainingLanes |= concurrentlyUpdatedLanes; + markRootFinished(root, remainingLanes, spawnedLane); + root === workInProgressRoot && + ((workInProgress = workInProgressRoot = null), + (workInProgressRootRenderLanes = 0)); + (0 === (didIncludeRenderPhaseUpdate.subtreeFlags & 10256) && + 0 === (didIncludeRenderPhaseUpdate.flags & 10256)) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); + return null; + })); + spawnedLane = 0 !== (didIncludeRenderPhaseUpdate.flags & 15990); + if (0 !== (didIncludeRenderPhaseUpdate.subtreeFlags & 15990) || spawnedLane) { + spawnedLane = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + remainingLanes = currentUpdatePriority; + currentUpdatePriority = 2; + var prevExecutionContext = executionContext; + executionContext |= 4; + ReactCurrentOwner.current = null; + commitBeforeMutationEffects(root, didIncludeRenderPhaseUpdate); + commitTime = now(); + commitMutationEffects(root, didIncludeRenderPhaseUpdate, transitions); + root.current = didIncludeRenderPhaseUpdate; + commitLayoutEffects(didIncludeRenderPhaseUpdate, root, transitions); + requestPaint(); + executionContext = prevExecutionContext; + currentUpdatePriority = remainingLanes; + ReactCurrentBatchConfig.transition = spawnedLane; + } else (root.current = didIncludeRenderPhaseUpdate), (commitTime = now()); + rootDoesHavePassiveEffects && + ((rootDoesHavePassiveEffects = !1), + (rootWithPendingPassiveEffects = root), + (pendingPassiveEffectsLanes = transitions)); + remainingLanes = root.pendingLanes; + 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); + onCommitRoot(didIncludeRenderPhaseUpdate.stateNode, renderPriorityLevel); + isDevToolsPresent && root.memoizedUpdaters.clear(); + ensureRootIsScheduled(root); + if (null !== recoverableErrors) + for ( + renderPriorityLevel = root.onRecoverableError, + didIncludeRenderPhaseUpdate = 0; + didIncludeRenderPhaseUpdate < recoverableErrors.length; + didIncludeRenderPhaseUpdate++ + ) + (spawnedLane = recoverableErrors[didIncludeRenderPhaseUpdate]), + (remainingLanes = { + digest: spawnedLane.digest, + componentStack: spawnedLane.stack + }), + renderPriorityLevel(spawnedLane.value, remainingLanes); + if (hasUncaughtError) + throw ( + ((hasUncaughtError = !1), + (root = firstUncaughtError), + (firstUncaughtError = null), + root) + ); + 0 !== (pendingPassiveEffectsLanes & 3) && + 0 !== root.tag && + flushPassiveEffects(); + remainingLanes = root.pendingLanes; + 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) + ? ((nestedUpdateScheduled = !0), + root === rootWithNestedUpdates + ? nestedUpdateCount++ + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))) + : (nestedUpdateCount = 0); + flushSyncWorkAcrossRoots_impl(!1); + return null; +} +function flushPassiveEffects() { + if (null !== rootWithPendingPassiveEffects) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), + prevTransition = ReactCurrentBatchConfig.transition, + previousPriority = currentUpdatePriority; + try { + ReactCurrentBatchConfig.transition = null; + currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; + if (null === rootWithPendingPassiveEffects) + var JSCompiler_inline_result = !1; + else { + renderPriority = rootWithPendingPassiveEffects; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = 0; + if (0 !== (executionContext & 6)) + throw Error("Cannot flush passive effects while already rendering."); + var prevExecutionContext = executionContext; + executionContext |= 4; + commitPassiveUnmountOnFiber(renderPriority.current); + commitPassiveMountOnFiber(renderPriority, renderPriority.current); + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; + for (var i = 0; i < profilerEffects.length; i++) { + var finishedWork = profilerEffects[i]; + if (executionContext & 4 && 0 !== (finishedWork.flags & 4)) + switch (finishedWork.tag) { + case 12: + var passiveEffectDuration = + finishedWork.stateNode.passiveEffectDuration, + _finishedWork$memoize = finishedWork.memoizedProps, + id = _finishedWork$memoize.id, + onPostCommit = _finishedWork$memoize.onPostCommit, + commitTime$86 = commitTime, + phase = null === finishedWork.alternate ? "mount" : "update"; + currentUpdateIsNested && (phase = "nested-update"); + "function" === typeof onPostCommit && + onPostCommit(id, phase, passiveEffectDuration, commitTime$86); + var parentFiber = finishedWork.return; + b: for (; null !== parentFiber; ) { + switch (parentFiber.tag) { + case 3: + parentFiber.stateNode.passiveEffectDuration += + passiveEffectDuration; + break b; + case 12: + parentFiber.stateNode.passiveEffectDuration += + passiveEffectDuration; + break b; } - newValue = newValue.return; + parentFiber = parentFiber.return; } - hasContext = newValue; } - reconcileChildren( - current, - workInProgress, - context.children, - renderLanes + } + executionContext = prevExecutionContext; + flushSyncWorkAcrossRoots_impl(!1); + if ( + injectedHook && + "function" === typeof injectedHook.onPostCommitFiberRoot + ) + try { + injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); + } catch (err) {} + var stateNode = renderPriority.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + JSCompiler_inline_result = !0; + } + return JSCompiler_inline_result; + } finally { + (currentUpdatePriority = previousPriority), + (ReactCurrentBatchConfig.transition = prevTransition); + } + } + return !1; +} +function enqueuePendingPassiveProfilerEffect(fiber) { + pendingPassiveProfilerEffects.push(fiber); + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); + return null; + })); +} +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); + rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); + null !== rootFiber && + (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +} +function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { + if (3 === sourceFiber.tag) + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + else + for (; null !== nearestMountedAncestor; ) { + if (3 === nearestMountedAncestor.tag) { + captureCommitPhaseErrorOnRoot( + nearestMountedAncestor, + sourceFiber, + error ); - workInProgress = workInProgress.child; + break; + } else if (1 === nearestMountedAncestor.tag) { + var instance = nearestMountedAncestor.stateNode; + if ( + "function" === + typeof nearestMountedAncestor.type.getDerivedStateFromError || + ("function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + ) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createClassErrorUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + nearestMountedAncestor = enqueueUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + null !== nearestMountedAncestor && + (markRootUpdated$1(nearestMountedAncestor, 2), + ensureRootIsScheduled(nearestMountedAncestor)); + break; + } } - return workInProgress; - case 9: - return ( - (context = workInProgress.type), - (Component = workInProgress.pendingProps.children), - prepareToReadContext(workInProgress, renderLanes), - (context = readContext(context)), - (Component = Component(context)), - (workInProgress.flags |= 1), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 14: - return ( - (Component = workInProgress.type), - (context = resolveDefaultProps(Component, workInProgress.pendingProps)), - (context = resolveDefaultProps(Component.type, context)), - updateMemoComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 15: - return updateSimpleMemoComponent( - current, - workInProgress, - workInProgress.type, - workInProgress.pendingProps, - renderLanes - ); - case 17: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), - (workInProgress.tag = 1), - isContextProvider(Component) - ? ((current = !0), pushContextProvider(workInProgress)) - : (current = !1), - prepareToReadContext(workInProgress, renderLanes), - constructClassInstance(workInProgress, Component, context), - mountClassInstance(workInProgress, Component, context, renderLanes), - finishClassComponent( - null, - workInProgress, - Component, - !0, - current, - renderLanes - ) - ); + nearestMountedAncestor = nearestMountedAncestor.return; + } +} +function attachPingListener(root, wakeable, lanes) { + var pingCache = root.pingCache; + if (null === pingCache) { + pingCache = root.pingCache = new PossiblyWeakMap(); + var threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else + (threadIDs = pingCache.get(wakeable)), + void 0 === threadIDs && + ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); + threadIDs.has(lanes) || + ((workInProgressRootDidAttachPingListener = !0), + threadIDs.add(lanes), + (pingCache = pingSuspendedRoot.bind(null, root, wakeable, lanes)), + isDevToolsPresent && restorePendingUpdaters(root, lanes), + wakeable.then(pingCache, pingCache)); +} +function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(wakeable); + root.pingedLanes |= root.suspendedLanes & pingedLanes; + workInProgressRoot === root && + (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && + (4 === workInProgressRootExitStatus || + (3 === workInProgressRootExitStatus && + (workInProgressRootRenderLanes & 62914560) === + workInProgressRootRenderLanes && + 300 > now$1() - globalMostRecentFallbackTime) + ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) + : (workInProgressRootPingedLanes |= pingedLanes)); + ensureRootIsScheduled(root); +} +function retryTimedOutBoundary(boundaryFiber, retryLane) { + 0 === retryLane && + (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); + boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + null !== boundaryFiber && + (markRootUpdated$1(boundaryFiber, retryLane), + ensureRootIsScheduled(boundaryFiber)); +} +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState, + retryLane = 0; + null !== suspenseState && (retryLane = suspenseState.retryLane); + retryTimedOutBoundary(boundaryFiber, retryLane); +} +function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = 0; + switch (boundaryFiber.tag) { + case 13: + var retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + null !== suspenseState && (retryLane = suspenseState.retryLane); + break; case 19: - return updateSuspenseListComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode; + break; case 22: - return updateOffscreenComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode._retryCache; + break; + default: + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -}; + null !== retryCache && retryCache.delete(wakeable); + retryTimedOutBoundary(boundaryFiber, retryLane); +} function restorePendingUpdaters(root, lanes) { isDevToolsPresent && root.memoizedUpdaters.forEach(function (schedulingFiber) { @@ -9551,6 +9240,7 @@ function createFiberFromTypeAndProps( case REACT_CONTEXT_TYPE: fiberTag = 9; break a; + case REACT_CONSUMER_TYPE: case REACT_FORWARD_REF_TYPE: fiberTag = 11; break a; @@ -9708,63 +9398,19 @@ function findHostInstance(component) { return null === component ? null : getPublicInstance(component.stateNode); } function updateContainer(element, container, parentComponent, callback) { - var current = container.current, - lane = requestUpdateLane(current); - a: if (parentComponent) { - parentComponent = parentComponent._reactInternals; - b: { - if ( - getNearestMountedFiber(parentComponent) !== parentComponent || - 1 !== parentComponent.tag - ) - throw Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); - var JSCompiler_inline_result = parentComponent; - do { - switch (JSCompiler_inline_result.tag) { - case 3: - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode.context; - break b; - case 1: - if (isContextProvider(JSCompiler_inline_result.type)) { - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode - .__reactInternalMemoizedMergedChildContext; - break b; - } - } - JSCompiler_inline_result = JSCompiler_inline_result.return; - } while (null !== JSCompiler_inline_result); - throw Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - if (1 === parentComponent.tag) { - var Component = parentComponent.type; - if (isContextProvider(Component)) { - parentComponent = processChildContext( - parentComponent, - Component, - JSCompiler_inline_result - ); - break a; - } - } - parentComponent = JSCompiler_inline_result; - } else parentComponent = emptyContextObject; + parentComponent = container.current; + var lane = requestUpdateLane(parentComponent); null === container.context - ? (container.context = parentComponent) - : (container.pendingContext = parentComponent); + ? (container.context = emptyContextObject) + : (container.pendingContext = emptyContextObject); container = createUpdate(lane); container.payload = { element: element }; callback = void 0 === callback ? null : callback; null !== callback && (container.callback = callback); - element = enqueueUpdate(current, container, lane); + element = enqueueUpdate(parentComponent, container, lane); null !== element && - (scheduleUpdateOnFiber(element, current, lane), - entangleTransitions(element, current, lane)); + (scheduleUpdateOnFiber(element, parentComponent, lane), + entangleTransitions(element, parentComponent, lane)); return lane; } function emptyFindFiberByHostInstance() { @@ -9812,10 +9458,10 @@ batchedUpdatesImpl = function (fn, a) { } }; var roots = new Map(), - devToolsConfig$jscomp$inline_1114 = { + devToolsConfig$jscomp$inline_1090 = { findFiberByHostInstance: getInstanceFromNode, bundleType: 0, - version: "18.3.0-canary-c1b45781", + version: "18.3.0-canary-f2de0db5", rendererPackageName: "react-native-renderer", rendererConfig: { getInspectorDataForInstance: getInspectorDataForInstance, @@ -9831,11 +9477,11 @@ var roots = new Map(), }.bind(null, findNodeHandle) } }; -var internals$jscomp$inline_1333 = { - bundleType: devToolsConfig$jscomp$inline_1114.bundleType, - version: devToolsConfig$jscomp$inline_1114.version, - rendererPackageName: devToolsConfig$jscomp$inline_1114.rendererPackageName, - rendererConfig: devToolsConfig$jscomp$inline_1114.rendererConfig, +var internals$jscomp$inline_1312 = { + bundleType: devToolsConfig$jscomp$inline_1090.bundleType, + version: devToolsConfig$jscomp$inline_1090.version, + rendererPackageName: devToolsConfig$jscomp$inline_1090.rendererPackageName, + rendererConfig: devToolsConfig$jscomp$inline_1090.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, @@ -9851,26 +9497,26 @@ var internals$jscomp$inline_1333 = { return null === fiber ? null : fiber.stateNode; }, findFiberByHostInstance: - devToolsConfig$jscomp$inline_1114.findFiberByHostInstance || + devToolsConfig$jscomp$inline_1090.findFiberByHostInstance || emptyFindFiberByHostInstance, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-canary-c1b45781" + reconcilerVersion: "18.3.0-canary-f2de0db5" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { - var hook$jscomp$inline_1334 = __REACT_DEVTOOLS_GLOBAL_HOOK__; + var hook$jscomp$inline_1313 = __REACT_DEVTOOLS_GLOBAL_HOOK__; if ( - !hook$jscomp$inline_1334.isDisabled && - hook$jscomp$inline_1334.supportsFiber + !hook$jscomp$inline_1313.isDisabled && + hook$jscomp$inline_1313.supportsFiber ) try { - (rendererID = hook$jscomp$inline_1334.inject( - internals$jscomp$inline_1333 + (rendererID = hook$jscomp$inline_1313.inject( + internals$jscomp$inline_1312 )), - (injectedHook = hook$jscomp$inline_1334); + (injectedHook = hook$jscomp$inline_1313); } catch (err) {} } exports.createPortal = function (children, containerTag) { diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js index d993f420538989..2544f756e3aaa7 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js @@ -8,7 +8,7 @@ * @nolint * @providesModule ReactNativeRenderer-dev * @preventMunge - * @generated SignedSource<<434937dbc3b1c3592d8ef8196d0c1a52>> + * @generated SignedSource<<4fbb60a6e6520f92ffc104738fdd5ce8>> */ "use strict"; @@ -98,292 +98,14 @@ if (__DEV__) { } } - var fakeNode = null; - - { - if ( - typeof window !== "undefined" && - typeof window.dispatchEvent === "function" && - typeof document !== "undefined" && // $FlowFixMe[method-unbinding] - typeof document.createEvent === "function" - ) { - fakeNode = document.createElement("react"); - } - } - - function invokeGuardedCallbackImpl(name, func, context) { - { - // In DEV mode, we use a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // unintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - // fakeNode signifies we are in an environment with a document and window object - if (fakeNode) { - var evt = document.createEvent("Event"); - var didCall = false; // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - - var didError = true; // Keeps track of the value of window.event so that we can reset it - // during the callback to let user code access window.event in the - // browsers that support it. - - var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event - // dispatching: https://github.com/facebook/react/issues/13688 - - var windowEventDescriptor = Object.getOwnPropertyDescriptor( - window, - "event" - ); - - var restoreAfterDispatch = function () { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the - // window.event assignment in both IE <= 10 as they throw an error - // "Member not found" in strict mode, and in Firefox which does not - // support window.event. - - if ( - typeof window.event !== "undefined" && - window.hasOwnProperty("event") - ) { - window.event = windowEvent; - } - }; // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - // $FlowFixMe[method-unbinding] - - var _funcArgs = Array.prototype.slice.call(arguments, 3); - - var callCallback = function () { - didCall = true; - restoreAfterDispatch(); // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. - - func.apply(context, _funcArgs); - didError = false; - }; // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - - var error; // Use this to track whether the error event is ever called. - - var didSetError = false; - var isCrossOriginError = false; - - var handleWindowError = function (event) { - error = event.error; - didSetError = true; - - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - - if (event.defaultPrevented) { - // Some other error handler has prevented default. - // Browsers silence the error report if this happens. - // We'll remember this to later decide whether to log it or not. - if (error != null && typeof error === "object") { - try { - error._suppressLogging = true; - } catch (inner) { - // Ignore. - } - } - } - }; // Create a fake event type. - - var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - - window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (windowEventDescriptor) { - Object.defineProperty(window, "event", windowEventDescriptor); - } - - if (didCall && didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error( - "An error was thrown inside one of your components, but React " + - "doesn't know what it was. This is likely due to browser " + - 'flakiness. React does its best to preserve the "Pause on ' + - 'exceptions" behavior of the DevTools, which requires some ' + - "DEV-mode only tricks. It's possible that these don't work in " + - "your browser. Try triggering the error in production mode, " + - "or switching to a modern browser. If you suspect that this is " + - "actually an issue with React, please file an issue." - ); - } else if (isCrossOriginError) { - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error( - "A cross-origin error was thrown. React doesn't have access to " + - "the actual error object in development. " + - "See https://reactjs.org/link/crossorigin-error for more information." - ); - } - - this.onError(error); - } // Remove our event listeners - - window.removeEventListener("error", handleWindowError); - - if (didCall) { - return; - } else { - // Something went really wrong, and our event was not dispatched. - // https://github.com/facebook/react/issues/16734 - // https://github.com/facebook/react/issues/16585 - // Fall back to the production implementation. - restoreAfterDispatch(); // we fall through and call the prod version instead - } - } // We only get here if we are in an environment that either does not support the browser - // variant or we had trouble getting the browser to emit the error. - // $FlowFixMe[method-unbinding] - - var funcArgs = Array.prototype.slice.call(arguments, 3); - - try { - // $FlowFixMe[incompatible-call] Flow doesn't understand the arguments splicing. - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } - } - } - - var hasError = false; - var caughtError = null; // Used by event system to capture/rethrow the first error. - - var hasRethrowError = false; - var rethrowError = null; - var reporter = { - onError: function (error) { - hasError = true; - caughtError = error; - } - }; - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); - } - /** - * Same as invokeGuardedCallback, but instead of returning an error, it stores - * it in a global so it can be rethrown by `rethrowCaughtError` later. - * TODO: See if caughtError and rethrowError can be unified. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f - ) { - invokeGuardedCallback.apply(this, arguments); - - if (hasError) { - var error = clearCaughtError(); - - if (!hasRethrowError) { - hasRethrowError = true; - rethrowError = error; - } - } - } - /** - * During execution of guarded functions we will capture the first error which - * we will rethrow to be handled by the top level error handler. - */ - - function rethrowCaughtError() { - if (hasRethrowError) { - var error = rethrowError; - hasRethrowError = false; - rethrowError = null; - throw error; - } - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error = caughtError; - hasError = false; - caughtError = null; - return error; - } else { - throw new Error( - "clearCaughtError was called but no error was captured. This error " + - "is likely caused by a bug in React. Please file an issue." - ); - } - } - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } + var hasError = false; + var caughtError = null; var getFiberCurrentPropsFromNode$1 = null; var getInstanceFromNode = null; var getNodeFromInstance = null; @@ -399,7 +121,7 @@ if (__DEV__) { { if (!getNodeFromInstance || !getInstanceFromNode) { error( - "EventPluginUtils.setComponentTree(...): Injected " + + "Injected " + "module is missing getNodeFromInstance or getInstanceFromNode." ); } @@ -439,9 +161,17 @@ if (__DEV__) { */ function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); + + try { + listener(event); + } catch (error) { + if (!hasError) { + hasError = true; + caughtError = error; + } + } + event.currentTarget = null; } /** @@ -534,7 +264,7 @@ if (__DEV__) { var dispatchInstance = event._dispatchInstances; if (isArray(dispatchListener)) { - throw new Error("executeDirectDispatch(...): Invalid `event`."); + throw new Error("Invalid `event`."); } event.currentTarget = dispatchListener @@ -554,6 +284,14 @@ if (__DEV__) { function hasDispatches(event) { return !!event._dispatchListeners; } + function rethrowCaughtError() { + if (hasError) { + var error = caughtError; + hasError = false; + caughtError = null; + throw error; + } + } var assign = Object.assign; @@ -840,7 +578,7 @@ if (__DEV__) { "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + "If you must keep the original synthetic event around, use event.persist(). " + - "See https://reactjs.org/link/event-pooling for more information.", + "See https://react.dev/link/event-pooling for more information.", action, propName, result @@ -1160,9 +898,7 @@ if (__DEV__) { function accumulate(current, next) { if (next == null) { - throw new Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw new Error("Accumulated items must not be null or undefined."); } if (current == null) { @@ -1200,9 +936,7 @@ if (__DEV__) { function accumulateInto(current, next) { if (next == null) { - throw new Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw new Error("Accumulated items must not be null or undefined."); } if (current == null) { @@ -2940,6 +2674,7 @@ to return true:wantsResponderID| | key._reactInternals = value; } + // ----------------------------------------------------------------------------- var enableSchedulingProfiler = false; var enableProfilerTimer = true; var enableProfilerCommitHooks = true; @@ -2949,6 +2684,7 @@ to return true:wantsResponderID| | var enableLazyContextPropagation = false; var enableLegacyHidden = false; var enableAsyncActions = false; + var enableBigIntSupport = false; // ATTENTION // When adding new symbols to this file, @@ -2959,7 +2695,9 @@ to return true:wantsResponderID| | var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); // TODO: Delete with enableRenderableContext + + var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); @@ -3059,13 +2797,21 @@ to return true:wantsResponderID| | } switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: { + var provider = type; + return getContextName$1(provider._context) + ".Provider"; + } + case REACT_CONTEXT_TYPE: var context = type; - return getContextName$1(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName$1(provider._context) + ".Provider"; + { + return getContextName$1(context) + ".Consumer"; + } + + case REACT_CONSUMER_TYPE: { + return null; + } case REACT_FORWARD_REF_TYPE: return getWrappedName$1(type, type.render, "ForwardRef"); @@ -3118,13 +2864,15 @@ to return true:wantsResponderID| | case CacheComponent: return "Cache"; - case ContextConsumer: + case ContextConsumer: { var context = type; return getContextName(context) + ".Consumer"; + } - case ContextProvider: + case ContextProvider: { var provider = type; return getContextName(provider._context) + ".Provider"; + } case DehydratedFragment: return "DehydratedFragment"; @@ -3364,9 +3112,6 @@ to return true:wantsResponderID| | return null; } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } function isMounted(component) { { var owner = ReactCurrentOwner$3.current; @@ -4379,7 +4124,7 @@ to return true:wantsResponderID| | error( "The installed version of React DevTools is too old and will not work " + "with the current version of React. Please update React DevTools. " + - "https://reactjs.org/link/react-devtools" + "https://react.dev/link/react-devtools" ); } // DevTools exists, even though it doesn't support Fiber. @@ -5126,7 +4871,7 @@ to return true:wantsResponderID| | return laneMap; } - function markRootUpdated(root, updateLane) { + function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update // could unblock them. Clear the suspended lanes so that we can try rendering // them again. @@ -5163,7 +4908,7 @@ to return true:wantsResponderID| | markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); } } - function markRootPinged(root, pingedLanes) { + function markRootPinged$1(root, pingedLanes) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } function markRootFinished(root, remainingLanes, spawnedLane) { @@ -5817,214 +5562,6 @@ to return true:wantsResponderID| | return null; } - function describeBuiltInComponentFrame(name, ownerFn) { - { - var ownerName = null; - - if (ownerFn) { - ownerName = ownerFn.displayName || ownerFn.name || null; - } - - return describeComponentFrame(name, ownerName); - } - } - - { - var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; - new PossiblyWeakMap$1(); - } - - function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - - if (ownerName) { - sourceInfo = " (created by " + ownerName + ")"; - } - - return "\n in " + (name || "Unknown") + sourceInfo; - } - - function describeClassComponentFrame(ctor, ownerFn) { - { - return describeFunctionComponentFrame(ctor, ownerFn); - } - } - function describeFunctionComponentFrame(fn, ownerFn) { - { - if (!fn) { - return ""; - } - - var name = fn.displayName || fn.name || null; - var ownerName = null; - - if (ownerFn) { - ownerName = ownerFn.displayName || ownerFn.name || null; - } - - return describeComponentFrame(name, ownerName); - } - } - - function describeUnknownElementTypeFrameInDEV(type, ownerFn) { - if (type == null) { - return ""; - } - - if (typeof type === "function") { - { - return describeFunctionComponentFrame(type, ownerFn); - } - } - - if (typeof type === "string") { - return describeBuiltInComponentFrame(type, ownerFn); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense", ownerFn); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList", ownerFn); - } - - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render, ownerFn); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, ownerFn); - - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - ownerFn - ); - } catch (x) {} - } - } - } - - return ""; - } - - // $FlowFixMe[method-unbinding] - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - owner ? owner.type : null - ); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe[incompatible-use] This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== "function") { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error( - (componentName || "React class") + - ": " + - location + - " type `" + - typeSpecName + - "` is invalid; " + - "it must be a function, usually from the `prop-types` package, but received `" + - typeof typeSpecs[typeSpecName] + - "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." - ); - err.name = "Invariant Violation"; - throw err; - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" - ); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error( - "%s: type specification of %s" + - " `%s` is invalid; the type checker " + - "function must return `null` or an `Error` but returned a %s. " + - "You may have forgotten to pass an argument to the type checker " + - "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + - "shape all require an argument).", - componentName || "React class", - location, - typeSpecName, - typeof error$1 - ); - - setCurrentlyValidatingElement(null); - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error("Failed %s type: %s", location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - var valueStack = []; var fiberStack; @@ -6076,280 +5613,33 @@ to return true:wantsResponderID| | cursor.current = value; } - var warnedAboutMissingGetChildContext; - - { - warnedAboutMissingGetChildContext = {}; - } - - var emptyContextObject = {}; + var emptyContextObject = {}; { Object.freeze(emptyContextObject); } // A cursor to the current merged context object on the stack. - var contextStackCursor$1 = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - - var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. - // We use this to get access to the parent context after we have already - // pushed the next context provider, and now need to merge their contexts. - - var previousContext = emptyContextObject; - - function getUnmaskedContext( - workInProgress, - Component, - didPushOwnContextIfProvider - ) { - { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - // If the fiber is a context provider itself, when we read its context - // we may have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - - return contextStackCursor$1.current; - } - } - - function cacheContext(workInProgress, unmaskedContext, maskedContext) { - { - var instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - } - - function getMaskedContext(workInProgress, unmaskedContext) { - { - var type = workInProgress.type; - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - - var instance = workInProgress.stateNode; - - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === - unmaskedContext - ) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - var context = {}; - - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentNameFromFiber(workInProgress) || "Unknown"; - checkPropTypes(contextTypes, context, "context", name); - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } - } - function hasContextChanged() { { - return didPerformWorkStackCursor.current; + return false; } } function isContextProvider(type) { { - var childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== undefined; - } - } - - function popContext(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor$1, fiber); - } - } - - function popTopLevelContextObject(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor$1, fiber); - } - } - - function pushTopLevelContextObject(fiber, context, didChange) { - { - if (contextStackCursor$1.current !== emptyContextObject) { - throw new Error( - "Unexpected context found on stack. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - push(contextStackCursor$1, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); + return false; } } function processChildContext(fiber, type, parentContext) { { - var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - - if (typeof instance.getChildContext !== "function") { - { - var componentName = getComponentNameFromFiber(fiber) || "Unknown"; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - - error( - "%s.childContextTypes is specified but there is no getChildContext() method " + - "on the instance. You can either define getChildContext() on %s or remove " + - "childContextTypes from it.", - componentName, - componentName - ); - } - } - - return parentContext; - } - - var childContext = instance.getChildContext(); - - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - } - } - - { - var name = getComponentNameFromFiber(fiber) || "Unknown"; - checkPropTypes( - childContextTypes, - childContext, - "child context", - name - ); - } - - return assign({}, parentContext, childContext); - } - } - - function pushContextProvider(workInProgress) { - { - var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - - var memoizedMergedChildContext = - (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, memoizedMergedChildContext, workInProgress); - push( - didPerformWorkStackCursor, - didPerformWorkStackCursor.current, - workInProgress - ); - return true; - } - } - - function invalidateContextProvider(workInProgress, type, didChange) { - { - var instance = workInProgress.stateNode; - - if (!instance) { - throw new Error( - "Expected to have an instance by this point. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - var mergedContext = processChildContext( - workInProgress, - type, - previousContext - ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor$1, workInProgress); // Now push the new context and mark that it has changed. - - push(contextStackCursor$1, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } + return parentContext; } } function findCurrentUnmaskedContext(fiber) { { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error( - "Expected subtree parent to be a mounted class component. " + - "This error is likely caused by a bug in React. Please file an issue." - ); - } - - var node = fiber; - - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - - case ClassComponent: { - var Component = node.type; - - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - - break; - } - } // $FlowFixMe[incompatible-type] we bail out when we get a null - - node = node.return; - } while (node !== null); - - throw new Error( - "Found unexpected detached subtree parent. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + return emptyContextObject; } } @@ -6468,16 +5758,8 @@ to return true:wantsResponderID| | } var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches - // due to earlier mismatches or a suspended fiber. - - var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary var hydrationErrors = null; - function didSuspendOrErrorWhileHydratingDEV() { - { - return didSuspendOrErrorDEV; - } - } function prepareToHydrateHostInstance(fiber, hostContext) { { @@ -7819,6 +7101,9 @@ to return true:wantsResponderID| | } } + // $FlowFixMe[method-unbinding] + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. @@ -7860,6 +7145,61 @@ to return true:wantsResponderID| | return true; } + function describeBuiltInComponentFrame(name, ownerFn) { + { + var ownerName = null; + + if (ownerFn) { + ownerName = ownerFn.displayName || ownerFn.name || null; + } + + return describeComponentFrame(name, ownerName); + } + } + function describeDebugInfoFrame(name, env) { + return describeBuiltInComponentFrame( + name + (env ? " (" + env + ")" : ""), + null + ); + } + + { + var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; + new PossiblyWeakMap$1(); + } + + function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + + if (ownerName) { + sourceInfo = " (created by " + ownerName + ")"; + } + + return "\n in " + (name || "Unknown") + sourceInfo; + } + + function describeClassComponentFrame(ctor, ownerFn) { + { + return describeFunctionComponentFrame(ctor, ownerFn); + } + } + function describeFunctionComponentFrame(fn, ownerFn) { + { + if (!fn) { + return ""; + } + + var name = fn.displayName || fn.name || null; + var ownerName = null; + + if (ownerFn) { + ownerName = ownerFn.displayName || ownerFn.name || null; + } + + return describeComponentFrame(name, ownerName); + } + } + function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null; @@ -7900,7 +7240,22 @@ to return true:wantsResponderID| | var node = workInProgress; do { - info += describeFiber(node); // $FlowFixMe[incompatible-type] we bail out when we get a null + info += describeFiber(node); + + if (true) { + // Add any Server Component stack frames in reverse order. + var debugInfo = node._debugInfo; + + if (debugInfo) { + for (var i = debugInfo.length - 1; i >= 0; i--) { + var entry = debugInfo[i]; + + if (typeof entry.name === "string") { + info += describeDebugInfoFrame(entry.name, entry.env); + } + } + } + } // $FlowFixMe[incompatible-type] we bail out when we get a null node = node.return; } while (node); @@ -8146,7 +7501,7 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move code with side effects to componentDidMount, and set initial state in the constructor.\n" + "\nPlease update the following components: %s", sortedNames @@ -8161,11 +7516,11 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* If you're updating state whenever props change, " + "refactor your code to use memoization techniques or move it to " + - "static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n" + + "static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n" + "\nPlease update the following components: %s", _sortedNames ); @@ -8179,7 +7534,7 @@ to return true:wantsResponderID| | error( "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "\nPlease update the following components: %s", _sortedNames2 @@ -8193,7 +7548,7 @@ to return true:wantsResponderID| | warn( "componentWillMount has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move code with side effects to componentDidMount, and set initial state in the constructor.\n" + "* Rename componentWillMount to UNSAFE_componentWillMount to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + @@ -8211,11 +7566,11 @@ to return true:wantsResponderID| | warn( "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* If you're updating state whenever props change, refactor your " + "code to use memoization techniques or move it to " + - "static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n" + + "static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n" + "* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + "To rename all deprecated lifecycles to their new names, you can run " + @@ -8232,7 +7587,7 @@ to return true:wantsResponderID| | warn( "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n" + + "See https://react.dev/link/unsafe-component-lifecycles for details.\n\n" + "* Move data fetching code or side effects to componentDidUpdate.\n" + "* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress " + "this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. " + @@ -8305,7 +7660,7 @@ to return true:wantsResponderID| | "\n\nThe old API will be supported in all 16.x releases, but applications " + "using it should migrate to the new version." + "\n\nPlease update the following components: %s" + - "\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", + "\n\nLearn more about this warning here: https://react.dev/link/legacy-context", sortedNames ); } finally { @@ -8585,20 +7940,20 @@ to return true:wantsResponderID| | rejectedThenable.reason = error; } } - ); // Check one more time in case the thenable resolved synchronously. + ); + } // Check one more time in case the thenable resolved synchronously. - switch (thenable.status) { - case "fulfilled": { - var fulfilledThenable = thenable; - return fulfilledThenable.value; - } + switch (thenable.status) { + case "fulfilled": { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } - case "rejected": { - var rejectedThenable = thenable; - var _rejectedError = rejectedThenable.reason; - checkIfUseWrappedInAsyncCatch(_rejectedError); - throw _rejectedError; - } + case "rejected": { + var rejectedThenable = thenable; + var _rejectedError = rejectedThenable.reason; + checkIfUseWrappedInAsyncCatch(_rejectedError); + throw _rejectedError; } } // Suspend. // @@ -8676,11 +8031,26 @@ to return true:wantsResponderID| | var thenableState$1 = null; var thenableIndexCounter$1 = 0; + + function mergeDebugInfo(outer, inner) { + if (inner == null) { + return outer; + } else if (outer === null) { + return inner; + } else { + // If we have two debugInfo, we need to create a new one. This makes the array no longer + // live so we'll miss any future updates if we received more so ideally we should always + // do this after both have fully resolved/unsuspended. + return outer.concat(inner); + } + } + var didWarnAboutMaps; var didWarnAboutGenerators; var didWarnAboutStringRefs; var ownerHasKeyUseWarning; var ownerHasFunctionTypeWarning; + var ownerHasSymbolTypeWarning; var warnForMissingKey = function (child, returnFiber) {}; @@ -8696,6 +8066,7 @@ to return true:wantsResponderID| | ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; + ownerHasSymbolTypeWarning = {}; warnForMissingKey = function (child, returnFiber) { if (child === null || typeof child !== "object") { @@ -8725,7 +8096,7 @@ to return true:wantsResponderID| | error( "Each child in a list should have a unique " + - '"key" prop. See https://reactjs.org/link/warning-keys for ' + + '"key" prop. See https://react.dev/link/warning-keys for ' + "more information." ); }; @@ -8746,122 +8117,128 @@ to return true:wantsResponderID| | return trackUsedThenable(thenableState$1, thenable, index); } - function coerceRef(returnFiber, current, element) { - var mixedRef = element.ref; - - if ( - mixedRef !== null && - typeof mixedRef !== "function" && - typeof mixedRef !== "object" - ) { - { - if ( - // Will already throw with "Function components cannot have string refs" - !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs" - !( - typeof element.type === "function" && !isReactClass(element.type) - ) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" - element._owner - ) { - var componentName = - getComponentNameFromFiber(returnFiber) || "Component"; - - if (!didWarnAboutStringRefs[componentName]) { - error( - 'Component "%s" contains the string ref "%s". Support for string refs ' + - "will be removed in a future major release. We recommend using " + - "useRef() or createRef() instead. " + - "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-string-ref", - componentName, - mixedRef - ); - - didWarnAboutStringRefs[componentName] = true; - } - } - } + function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef + ) { + { + checkPropStringCoercion(mixedRef, "ref"); + } - if (element._owner) { - var owner = element._owner; - var inst; + var stringRef = "" + mixedRef; + var owner = element._owner; - if (owner) { - var ownerFiber = owner; + if (!owner) { + throw new Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of" + + " the following reasons:\n" + + "1. You may be adding a ref to a function component\n" + + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + + "3. You have multiple copies of React loaded\n" + + "See https://react.dev/link/refs-must-have-owner for more information." + ); + } - if (ownerFiber.tag !== ClassComponent) { - throw new Error( - "Function components cannot have string refs. " + - "We recommend using useRef() instead. " + - "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-string-ref" - ); - } + if (owner.tag !== ClassComponent) { + throw new Error( + "Function components cannot have string refs. " + + "We recommend using useRef() instead. " + + "Learn more about using refs safely here: " + + "https://react.dev/link/strict-mode-string-ref" + ); + } - inst = ownerFiber.stateNode; - } + { + if ( + // Will already warn with "Function components cannot be given refs" + !(typeof element.type === "function" && !isReactClass(element.type)) + ) { + var componentName = + getComponentNameFromFiber(returnFiber) || "Component"; - if (!inst) { - throw new Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a " + - "bug in React. Please file an issue." + if (!didWarnAboutStringRefs[componentName]) { + error( + 'Component "%s" contains the string ref "%s". Support for string refs ' + + "will be removed in a future major release. We recommend using " + + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://react.dev/link/strict-mode-string-ref", + componentName, + stringRef ); - } // Assigning this to a const so Flow knows it won't change in the closure - - var resolvedInst = inst; - { - checkPropStringCoercion(mixedRef, "ref"); + didWarnAboutStringRefs[componentName] = true; } + } + } - var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + var inst = owner.stateNode; - if ( - current !== null && - current.ref !== null && - typeof current.ref === "function" && - current.ref._stringRef === stringRef - ) { - return current.ref; - } + if (!inst) { + throw new Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a " + + "bug in React. Please file an issue." + ); + } // Check if previous string ref matches new string ref - var ref = function (value) { - var refs = resolvedInst.refs; + if ( + current !== null && + current.ref !== null && + typeof current.ref === "function" && + current.ref._stringRef === stringRef + ) { + // Reuse the existing string ref + var currentRef = current.ref; + return currentRef; + } // Create a new string ref - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; + var ref = function (value) { + var refs = inst.refs; - ref._stringRef = stringRef; - return ref; + if (value === null) { + delete refs[stringRef]; } else { - if (typeof mixedRef !== "string") { - throw new Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - } - - if (!element._owner) { - throw new Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of" + - " the following reasons:\n" + - "1. You may be adding a ref to a function component\n" + - "2. You may be adding a ref to a component that was not created inside a component's render method\n" + - "3. You have multiple copies of React loaded\n" + - "See https://reactjs.org/link/refs-must-have-owner for more information." - ); - } + refs[stringRef] = value; } + }; + + ref._stringRef = stringRef; + return ref; + } + + function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef; + + { + // Old behavior. + mixedRef = element.ref; } - return mixedRef; + var coercedRef; + + if ( + typeof mixedRef === "string" || + typeof mixedRef === "number" || + typeof mixedRef === "boolean" + ) { + coercedRef = convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef + ); + } else { + coercedRef = mixedRef; + } // TODO: If enableRefAsProp is on, we shouldn't use the `ref` field. We + // should always read the ref from the prop. + + workInProgress.ref = coercedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { @@ -8878,22 +8255,68 @@ to return true:wantsResponderID| | ); } - function warnOnFunctionType(returnFiber) { + function warnOnFunctionType(returnFiber, invalidChild) { { - var componentName = - getComponentNameFromFiber(returnFiber) || "Component"; + var parentName = getComponentNameFromFiber(returnFiber) || "Component"; - if (ownerHasFunctionTypeWarning[componentName]) { + if (ownerHasFunctionTypeWarning[parentName]) { return; } - ownerHasFunctionTypeWarning[componentName] = true; + ownerHasFunctionTypeWarning[parentName] = true; + var name = invalidChild.displayName || invalidChild.name || "Component"; - error( - "Functions are not valid as a React child. This may happen if " + - "you return a Component instead of from render. " + - "Or maybe you meant to call this function rather than return it." - ); + if (returnFiber.tag === HostRoot) { + error( + "Functions are not valid as a React child. This may happen if " + + "you return %s instead of <%s /> from render. " + + "Or maybe you meant to call this function rather than return it.\n" + + " root.render(%s)", + name, + name, + name + ); + } else { + error( + "Functions are not valid as a React child. This may happen if " + + "you return %s instead of <%s /> from render. " + + "Or maybe you meant to call this function rather than return it.\n" + + " <%s>{%s}", + name, + name, + parentName, + name, + parentName + ); + } + } + } + + function warnOnSymbolType(returnFiber, invalidChild) { + { + var parentName = getComponentNameFromFiber(returnFiber) || "Component"; + + if (ownerHasSymbolTypeWarning[parentName]) { + return; + } + + ownerHasSymbolTypeWarning[parentName] = true; // eslint-disable-next-line react-internal/safe-string-coercion + + var name = String(invalidChild); + + if (returnFiber.tag === HostRoot) { + error( + "Symbols are not valid as a React child.\n" + " root.render(%s)", + name + ); + } else { + error( + "Symbols are not valid as a React child.\n" + " <%s>%s", + parentName, + name, + parentName + ); + } } } @@ -8940,7 +8363,7 @@ to return true:wantsResponderID| | return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { + function mapRemainingChildren(currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index // instead. @@ -9009,7 +8432,13 @@ to return true:wantsResponderID| | return newFiber; } - function updateTextNode(returnFiber, current, textContent, lanes) { + function updateTextNode( + returnFiber, + current, + textContent, + lanes, + debugInfo + ) { if (current === null || current.tag !== HostText) { // Insert var created = createFiberFromText( @@ -9018,16 +8447,26 @@ to return true:wantsResponderID| | lanes ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, textContent); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function updateElement(returnFiber, current, element, lanes) { + function updateElement(returnFiber, current, element, lanes, debugInfo) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { @@ -9036,7 +8475,8 @@ to return true:wantsResponderID| | current, element.props.children, lanes, - element.key + element.key, + debugInfo ); } @@ -9054,11 +8494,12 @@ to return true:wantsResponderID| | ) { // Move based on index var existing = useFiber(current, element.props); - existing.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, existing, element); existing.return = returnFiber; { existing._debugOwner = element._owner; + existing._debugInfo = debugInfo; } return existing; @@ -9066,12 +8507,17 @@ to return true:wantsResponderID| | } // Insert var created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, created, element); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } - function updatePortal(returnFiber, current, portal, lanes) { + function updatePortal(returnFiber, current, portal, lanes, debugInfo) { if ( current === null || current.tag !== HostPortal || @@ -9081,16 +8527,33 @@ to return true:wantsResponderID| | // Insert var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, portal.children || []); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function updateFragment(returnFiber, current, fragment, lanes, key) { + function updateFragment( + returnFiber, + current, + fragment, + lanes, + key, + debugInfo + ) { if (current === null || current.tag !== Fragment) { // Insert var created = createFiberFromFragment( @@ -9100,29 +8563,46 @@ to return true:wantsResponderID| | key ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { // Update var existing = useFiber(current, fragment); existing.return = returnFiber; + + { + existing._debugInfo = debugInfo; + } + return existing; } } - function createChild(returnFiber, newChild, lanes) { + function createChild(returnFiber, newChild, lanes, debugInfo) { if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. var created = createFiberFromText( + // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, returnFiber.mode, lanes ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } @@ -9135,8 +8615,16 @@ to return true:wantsResponderID| | lanes ); - _created.ref = coerceRef(returnFiber, null, newChild); + coerceRef(returnFiber, null, _created, newChild); _created.return = returnFiber; + + { + _created._debugInfo = mergeDebugInfo( + debugInfo, + newChild._debugInfo + ); + } + return _created; } @@ -9148,13 +8636,23 @@ to return true:wantsResponderID| | ); _created2.return = returnFiber; + + { + _created2._debugInfo = debugInfo; + } + return _created2; } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; - return createChild(returnFiber, init(payload), lanes); + return createChild( + returnFiber, + init(payload), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) // call merge after init + ); } } @@ -9167,6 +8665,14 @@ to return true:wantsResponderID| | ); _created3.return = returnFiber; + + { + _created3._debugInfo = mergeDebugInfo( + debugInfo, + newChild._debugInfo + ); + } + return _created3; } // Usable node types // @@ -9174,15 +8680,21 @@ to return true:wantsResponderID| | if (typeof newChild.then === "function") { var thenable = newChild; - return createChild(returnFiber, unwrapThenable(thenable), lanes); + return createChild( + returnFiber, + unwrapThenable(thenable), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } if (newChild.$$typeof === REACT_CONTEXT_TYPE) { var context = newChild; return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -9191,20 +8703,25 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } return null; } - function updateSlot(returnFiber, oldFiber, newChild, lanes) { + function updateSlot(returnFiber, oldFiber, newChild, lanes, debugInfo) { // Update the fiber if the keys match, otherwise return null. var key = oldFiber !== null ? oldFiber.key : null; if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text @@ -9213,14 +8730,26 @@ to return true:wantsResponderID| | return null; } - return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes); + return updateTextNode( + returnFiber, + oldFiber, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint + "" + newChild, + lanes, + debugInfo + ); } if (typeof newChild === "object" && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); + return updateElement( + returnFiber, + oldFiber, + newChild, + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } else { return null; } @@ -9228,7 +8757,13 @@ to return true:wantsResponderID| | case REACT_PORTAL_TYPE: { if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); + return updatePortal( + returnFiber, + oldFiber, + newChild, + lanes, + debugInfo + ); } else { return null; } @@ -9237,7 +8772,13 @@ to return true:wantsResponderID| | case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); + return updateSlot( + returnFiber, + oldFiber, + init(payload), + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } } @@ -9246,7 +8787,14 @@ to return true:wantsResponderID| | return null; } - return updateFragment(returnFiber, oldFiber, newChild, lanes, null); + return updateFragment( + returnFiber, + oldFiber, + newChild, + lanes, + null, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } // Usable node types // // Unwrap the inner value and recursively call this function again. @@ -9257,7 +8805,8 @@ to return true:wantsResponderID| | returnFiber, oldFiber, unwrapThenable(thenable), - lanes + lanes, + debugInfo ); } @@ -9266,8 +8815,9 @@ to return true:wantsResponderID| | return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -9276,7 +8826,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } @@ -9288,20 +8842,23 @@ to return true:wantsResponderID| | returnFiber, newIdx, newChild, - lanes + lanes, + debugInfo ) { if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { // Text nodes don't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. var matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode( returnFiber, - matchedFiber, + matchedFiber, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, - lanes + lanes, + debugInfo ); } @@ -9313,7 +8870,13 @@ to return true:wantsResponderID| | newChild.key === null ? newIdx : newChild.key ) || null; - return updateElement(returnFiber, _matchedFiber, newChild, lanes); + return updateElement( + returnFiber, + _matchedFiber, + newChild, + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) + ); } case REACT_PORTAL_TYPE: { @@ -9322,7 +8885,13 @@ to return true:wantsResponderID| | newChild.key === null ? newIdx : newChild.key ) || null; - return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); + return updatePortal( + returnFiber, + _matchedFiber2, + newChild, + lanes, + debugInfo + ); } case REACT_LAZY_TYPE: @@ -9333,7 +8902,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, init(payload), - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -9345,7 +8915,8 @@ to return true:wantsResponderID| | _matchedFiber3, newChild, lanes, - null + null, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } // Usable node types // @@ -9358,7 +8929,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, unwrapThenable(thenable), - lanes + lanes, + debugInfo ); } @@ -9368,8 +8940,9 @@ to return true:wantsResponderID| | existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -9378,7 +8951,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } @@ -9441,7 +9018,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChildren, - lanes + lanes, + debugInfo ) { // This algorithm can't optimize by searching from both ends since we // don't have backpointers on fibers. I'm trying to see how far we can get @@ -9487,7 +9065,8 @@ to return true:wantsResponderID| | returnFiber, oldFiber, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (newFiber === null) { @@ -9541,7 +9120,8 @@ to return true:wantsResponderID| | var _newFiber = createChild( returnFiber, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (_newFiber === null) { @@ -9563,7 +9143,7 @@ to return true:wantsResponderID| | return resultingFirstChild; } // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. + var existingChildren = mapRemainingChildren(oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( @@ -9571,7 +9151,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, newChildren[newIdx], - lanes + lanes, + debugInfo ); if (_newFiber2 !== null) { @@ -9614,7 +9195,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChildrenIterable, - lanes + lanes, + debugInfo ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. @@ -9699,7 +9281,13 @@ to return true:wantsResponderID| | nextOldFiber = oldFiber.sibling; } - var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); + var newFiber = updateSlot( + returnFiber, + oldFiber, + step.value, + lanes, + debugInfo + ); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's @@ -9749,7 +9337,12 @@ to return true:wantsResponderID| | // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, lanes); + var _newFiber3 = createChild( + returnFiber, + step.value, + lanes, + debugInfo + ); if (_newFiber3 === null) { continue; @@ -9770,7 +9363,7 @@ to return true:wantsResponderID| | return resultingFirstChild; } // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. + var existingChildren = mapRemainingChildren(oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( @@ -9778,7 +9371,8 @@ to return true:wantsResponderID| | returnFiber, newIdx, step.value, - lanes + lanes, + debugInfo ); if (_newFiber4 !== null) { @@ -9845,7 +9439,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, element, - lanes + lanes, + debugInfo ) { var key = element.key; var child = currentFirstChild; @@ -9864,6 +9459,7 @@ to return true:wantsResponderID| | { existing._debugOwner = element._owner; + existing._debugInfo = debugInfo; } return existing; @@ -9884,11 +9480,12 @@ to return true:wantsResponderID| | var _existing = useFiber(child, element.props); - _existing.ref = coerceRef(returnFiber, child, element); + coerceRef(returnFiber, child, _existing, element); _existing.return = returnFiber; { _existing._debugOwner = element._owner; + _existing._debugInfo = debugInfo; } return _existing; @@ -9912,6 +9509,11 @@ to return true:wantsResponderID| | element.key ); created.return = returnFiber; + + { + created._debugInfo = debugInfo; + } + return created; } else { var _created4 = createFiberFromElement( @@ -9920,8 +9522,13 @@ to return true:wantsResponderID| | lanes ); - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); + coerceRef(returnFiber, currentFirstChild, _created4, element); _created4.return = returnFiber; + + { + _created4._debugInfo = debugInfo; + } + return _created4; } } @@ -9930,7 +9537,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, portal, - lanes + lanes, + debugInfo ) { var key = portal.key; var child = currentFirstChild; @@ -9970,7 +9578,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + debugInfo ) { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, @@ -9998,7 +9607,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ) ); @@ -10014,13 +9624,13 @@ to return true:wantsResponderID| | case REACT_LAZY_TYPE: var payload = newChild._payload; - var init = newChild._init; // TODO: This function is supposed to be non-recursive. - - return reconcileChildFibers( + var init = newChild._init; + return reconcileChildFibersImpl( returnFiber, currentFirstChild, init(payload), - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -10029,7 +9639,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } @@ -10038,7 +9649,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + mergeDebugInfo(debugInfo, newChild._debugInfo) ); } // Usables are a valid React node type. When React encounters a Usable in // a child position, it unwraps it using the same algorithm as `use`. For @@ -10063,7 +9675,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, unwrapThenable(thenable), - lanes + lanes, + mergeDebugInfo(debugInfo, thenable._debugInfo) ); } @@ -10072,8 +9685,9 @@ to return true:wantsResponderID| | return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, context, lanes), - lanes + readContextDuringReconciliation(returnFiber, context, lanes), + lanes, + debugInfo ); } @@ -10082,12 +9696,13 @@ to return true:wantsResponderID| | if ( (typeof newChild === "string" && newChild !== "") || - typeof newChild === "number" + typeof newChild === "number" || + enableBigIntSupport ) { return placeSingleChild( reconcileSingleTextNode( returnFiber, - currentFirstChild, + currentFirstChild, // $FlowFixMe[unsafe-addition] Flow doesn't want us to use `+` operator with string and bigint "" + newChild, lanes ) @@ -10096,7 +9711,11 @@ to return true:wantsResponderID| | { if (typeof newChild === "function") { - warnOnFunctionType(returnFiber); + warnOnFunctionType(returnFiber, newChild); + } + + if (typeof newChild === "symbol") { + warnOnSymbolType(returnFiber, newChild); } } // Remaining cases are all treated as empty. @@ -10116,7 +9735,8 @@ to return true:wantsResponderID| | returnFiber, currentFirstChild, newChild, - lanes + lanes, + null // debugInfo ); thenableState$1 = null; // Don't bother to reset `thenableIndexCounter` to 0 because it always gets // set at the beginning. @@ -10552,7 +10172,7 @@ to return true:wantsResponderID| | error( "React has detected a change in the order of Hooks called by %s. " + "This will lead to bugs and errors if not fixed. " + - "For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n" + + "For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n" + " Previous render Next render\n" + " ------------------------------------------------------\n" + "%s" + @@ -10603,7 +10223,7 @@ to return true:wantsResponderID| | "1. You might have mismatching versions of React and the renderer (such as React DOM)\n" + "2. You might be breaking the Rules of Hooks\n" + "3. You might have more than one copy of React in the same app\n" + - "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } @@ -12175,8 +11795,8 @@ to return true:wantsResponderID| | } function updateTransition() { - var _updateState = updateState(), - booleanOrThenable = _updateState[0]; + var _updateState2 = updateState(), + booleanOrThenable = _updateState2[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; @@ -12435,7 +12055,7 @@ to return true:wantsResponderID| | "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. " + "You can only call Hooks at the top level of your React function. " + "For more information, see " + - "https://reactjs.org/link/rules-of-hooks" + "https://react.dev/link/rules-of-hooks" ); }; @@ -13464,7 +13084,6 @@ to return true:wantsResponderID| | var didWarnAboutLegacyLifecyclesAndDerivedState; var didWarnAboutUndefinedDerivedState; var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; var didWarnAboutInvalidateContextType; var didWarnOnInvalidCallback; @@ -13475,7 +13094,6 @@ to return true:wantsResponderID| | didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); didWarnAboutDirectlyAssigningPropsToState = new Set(); didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); didWarnOnInvalidCallback = new Set(); // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for @@ -13499,21 +13117,20 @@ to return true:wantsResponderID| | Object.freeze(fakeInternalInstance); } - function warnOnInvalidCallback(callback, callerName) { + function warnOnInvalidCallback(callback) { { if (callback === null || typeof callback === "function") { return; - } + } // eslint-disable-next-line react-internal/safe-string-coercion - var key = callerName + "_" + callback; + var key = String(callback); if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); error( - "%s(...): Expected the last optional `callback` argument to be a " + + "Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", - callerName, callback ); } @@ -13587,7 +13204,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "setState"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13609,7 +13226,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "replaceState"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13631,7 +13248,7 @@ to return true:wantsResponderID| | if (callback !== undefined && callback !== null) { { - warnOnInvalidCallback(callback, "forceUpdate"); + warnOnInvalidCallback(callback); } update.callback = callback; @@ -13711,13 +13328,13 @@ to return true:wantsResponderID| | if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === "function") { error( - "%s(...): No `render` method found on the returned component " + + "No `render` method found on the %s " + "instance: did you accidentally return an object from the constructor?", name ); } else { error( - "%s(...): No `render` method found on the returned component " + + "No `render` method found on the %s " + "instance: you may have forgotten to define `render`.", name ); @@ -13766,24 +13383,18 @@ to return true:wantsResponderID| | } { - if (instance.contextTypes) { + if (ctor.childContextTypes) { error( - "contextTypes was defined as an instance property on %s. Use a static " + - "property to define contextTypes instead.", + "%s uses the legacy childContextTypes API which is no longer supported. " + + "Use React.createContext() instead.", name ); } - if ( - ctor.contextType && - ctor.contextTypes && - !didWarnAboutContextTypeAndContextTypes.has(ctor) - ) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - + if (ctor.contextTypes) { error( - "%s declares both contextTypes and contextType static properties. " + - "The legacy contextTypes property will be ignored.", + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with static contextType instead.", name ); } @@ -13852,9 +13463,8 @@ to return true:wantsResponderID| | if (instance.props !== undefined && hasMutatedProps) { error( - "%s(...): When calling super() in `%s`, make sure to pass " + + "When calling super() in `%s`, make sure to pass " + "up the same props that your component's constructor was passed.", - name, name ); } @@ -13937,8 +13547,6 @@ to return true:wantsResponderID| | } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = false; - var unmaskedContext = emptyContextObject; var context = emptyContextObject; var contextType = ctor.contextType; @@ -13947,8 +13555,7 @@ to return true:wantsResponderID| | var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE && - contextType._context === undefined); // Not a + contextType.$$typeof === REACT_CONTEXT_TYPE); if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); @@ -13962,11 +13569,7 @@ to return true:wantsResponderID| | "try moving the createContext() call to a separate file."; } else if (typeof contextType !== "object") { addendum = " However, it is set to a " + typeof contextType + "."; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = - " Did you accidentally pass the Context.Provider instead?"; - } else if (contextType._context !== undefined) { - // + } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) { addendum = " Did you accidentally pass the Context.Consumer instead?"; } else { @@ -13988,14 +13591,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { context = readContext(contextType); - } else { - unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - var contextTypes = ctor.contextTypes; - isLegacyContextConsumer = - contextTypes !== null && contextTypes !== undefined; - context = isLegacyContextConsumer - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject; } var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. @@ -14103,7 +13698,7 @@ to return true:wantsResponderID| | "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://reactjs.org/link/unsafe-component-lifecycles", + "https://react.dev/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -14115,12 +13710,7 @@ to return true:wantsResponderID| | } } } - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - - if (isLegacyContextConsumer) { - cacheContext(workInProgress, unmaskedContext, context); - } + } // Cache unmasked context so we can avoid recreating masked context unless necessary. return instance; } @@ -14210,8 +13800,7 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else { - var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - instance.context = getMaskedContext(workInProgress, unmaskedContext); + instance.context = emptyContextObject; } { @@ -14295,16 +13884,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); - } else { - var nextLegacyUnmaskedContext = getUnmaskedContext( - workInProgress, - ctor, - true - ); - nextContext = getMaskedContext( - workInProgress, - nextLegacyUnmaskedContext - ); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; @@ -14448,13 +14027,6 @@ to return true:wantsResponderID| | if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); - } else { - var nextUnmaskedContext = getUnmaskedContext( - workInProgress, - ctor, - true - ); - nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; @@ -14608,17 +14180,37 @@ to return true:wantsResponderID| | return shouldUpdate; } + var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. + var stack; + + if (typeof value === "object" && value !== null) { + var capturedStack = CapturedStacks.get(value); + + if (typeof capturedStack === "string") { + stack = capturedStack; + } else { + stack = getStackByFiberInDevAndProd(source); + CapturedStacks.set(value, stack); + } + } else { + stack = getStackByFiberInDevAndProd(source); + } + return { value: value, source: source, - stack: getStackByFiberInDevAndProd(source), + stack: stack, digest: null }; } - function createCapturedValue(value, digest, stack) { + function createCapturedValueFromError(value, digest, stack) { + if (typeof stack === "string") { + CapturedStacks.set(value, stack); + } + return { value: value, source: null, @@ -14664,25 +14256,8 @@ to return true:wantsResponderID| | if (true) { var source = errorInfo.source; var stack = errorInfo.stack; - var componentStack = stack !== null ? stack : ""; // Browsers support silencing uncaught errors by calling - // `preventDefault()` in window `error` handler. - // We record this information as an expando on the error. - - if (error != null && error._suppressLogging) { - if (boundary.tag === ClassComponent) { - // The error is recoverable and was silenced. - // Ignore it and don't print the stack addendum. - // This is handy for testing error boundaries without noise. - return; - } // The error is fatal. Since the silencing might have - // been accidental, we'll surface it anyway. - // However, the browser would have silenced the original error - // so we'll print it first, and then print the stack addendum. - - console["error"](error); // Don't transform to our wrapper - // For a more detailed description of this block, see: - // https://github.com/facebook/react/pull/13384 - } + var componentStack = stack !== null ? stack : ""; // TODO: There's no longer a way to silence these warnings e.g. for tests. + // See https://github.com/facebook/react/pull/13384 var componentName = source ? getComponentNameFromFiber(source) : null; var componentNameMessage = componentName @@ -14695,7 +14270,7 @@ to return true:wantsResponderID| | if (boundary.tag === HostRoot) { errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\n" + - "Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries."; + "Visit https://react.dev/link/error-boundaries to learn more about error boundaries."; } else { var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous"; @@ -14704,19 +14279,17 @@ to return true:wantsResponderID| | ("using the error boundary you provided, " + errorBoundaryName + "."); - } - - var combinedMessage = - componentNameMessage + - "\n" + - componentStack + - "\n\n" + - ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. - // We don't include the original error message and JS stack because the browser - // has already printed it. Even if the application swallows the error, it is still - // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. - - console["error"](combinedMessage); // Don't transform to our wrapper + } // In development, we provide our own message which includes the component stack + // in addition to the error. + + console["error"]( + // Don't transform to our wrapper + "%o\n\n%s\n%s\n\n%s", + error, + componentNameMessage, + componentStack, + errorBoundaryMessage + ); } } catch (e) { // This method must not throw, or React internal state will get messed up. @@ -15307,25 +14880,13 @@ to return true:wantsResponderID| | // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var render = Component.render; - var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent + var ref = workInProgress.ref; + var propsWithoutRef; + + { + propsWithoutRef = nextProps; + } // The rest is a fork of updateFunctionComponent var nextChildren; prepareToReadContext(workInProgress, renderLanes); @@ -15337,7 +14898,7 @@ to return true:wantsResponderID| | current, workInProgress, render, - nextProps, + propsWithoutRef, ref, renderLanes ); @@ -15398,19 +14959,6 @@ to return true:wantsResponderID| | } { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(type) - ); - } - if (Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || "Unknown"; @@ -15440,22 +14988,6 @@ to return true:wantsResponderID| | return child; } - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - _innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(_type) - ); - } - } - var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( @@ -15501,40 +15033,6 @@ to return true:wantsResponderID| | // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - "prop", - getComponentNameFromType(outerMemoType) - ); - } - } - } - } - if (current !== null) { var prevProps = current.memoizedProps; @@ -15607,7 +15105,7 @@ to return true:wantsResponderID| | var nextIsDetached = (workInProgress.stateNode._pendingVisibility & OffscreenDetached) !== 0; var prevState = current !== null ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if (nextProps.mode === "hidden" || enableLegacyHidden || nextIsDetached) { // Rendering a hidden tree. @@ -15772,16 +15270,26 @@ to return true:wantsResponderID| | return workInProgress.child; } - function markRef$1(current, workInProgress) { + function markRef(current, workInProgress) { + // TODO: Check props.ref instead of fiber.ref when enableRefAsProp is on. var ref = workInProgress.ref; - if ( - (current === null && ref !== null) || - (current !== null && current.ref !== ref) - ) { - // Schedule a Ref effect - workInProgress.flags |= Ref; - workInProgress.flags |= RefStatic; + if (ref === null) { + if (current !== null && current.ref !== null) { + // Schedule a Ref effect + workInProgress.flags |= Ref | RefStatic; + } + } else { + if (typeof ref !== "function" && typeof ref !== "object") { + throw new Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + } + + if (current === null || current.ref !== ref) { + // Schedule a Ref effect + workInProgress.flags |= Ref | RefStatic; + } } } @@ -15792,34 +15300,8 @@ to return true:wantsResponderID| | nextProps, renderLanes ) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } - } - var context; - { - var unmaskedContext = getUnmaskedContext( - workInProgress, - Component, - true - ); - context = getMaskedContext(workInProgress, unmaskedContext); - } - var nextChildren; prepareToReadContext(workInProgress, renderLanes); @@ -15929,30 +15411,14 @@ to return true:wantsResponderID| | break; } } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - "prop", - getComponentNameFromType(Component) - ); - } - } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -16022,15 +15488,10 @@ to return true:wantsResponderID| | renderLanes ) { // Refs should update even if shouldComponentUpdate returns false - markRef$1(current, workInProgress); + markRef(current, workInProgress); var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags$1; if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, Component, false); - } - return bailoutOnAlreadyFinishedWork( current, workInProgress, @@ -16096,27 +15557,12 @@ to return true:wantsResponderID| | workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. - if (hasContext) { - invalidateContextProvider(workInProgress, Component, true); - } - return workInProgress.child; } function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; - if (root.pendingContext) { - pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - pushHostContainer(workInProgress, root.containerInfo); } @@ -16168,7 +15614,7 @@ to return true:wantsResponderID| | workInProgress.flags |= ContentReset; } - markRef$1(current, workInProgress); + markRef(current, workInProgress); reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } @@ -16249,21 +15695,6 @@ to return true:wantsResponderID| | } case MemoComponent: { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - "prop", - getComponentNameFromType(Component) - ); - } - } - } - child = updateMemoComponent( null, workInProgress, @@ -16313,9 +15744,8 @@ to return true:wantsResponderID| | var hasContext; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -16343,15 +15773,6 @@ to return true:wantsResponderID| | var props = workInProgress.pendingProps; var context; - { - var unmaskedContext = getUnmaskedContext( - workInProgress, - Component, - false - ); - context = getMaskedContext(workInProgress, unmaskedContext); - } - prepareToReadContext(workInProgress, renderLanes); var value; @@ -16461,9 +15882,8 @@ to return true:wantsResponderID| | var hasContext = false; - if (isContextProvider(Component)) { + if (isContextProvider()) { hasContext = true; - pushContextProvider(workInProgress); } else { hasContext = false; } @@ -16487,6 +15907,16 @@ to return true:wantsResponderID| | // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { + if (Component.contextTypes) { + error( + "%s uses the legacy contextTypes API which is no longer supported. " + + "Use React.createContext() with React.useContext() instead.", + getComponentNameFromType(Component) || "Unknown" + ); + } + } + reconcileChildren(null, workInProgress, value, renderLanes); { @@ -16502,7 +15932,8 @@ to return true:wantsResponderID| | if (Component) { if (Component.childContextTypes) { error( - "%s(...): childContextTypes cannot be defined on a function component.", + "childContextTypes cannot be defined on a function component.\n" + + " %s.childContextTypes = ...", Component.displayName || Component.name || "Component" ); } @@ -17136,7 +16567,7 @@ to return true:wantsResponderID| | } error.digest = digest; - capturedValue = createCapturedValue(error, digest, stack); + capturedValue = createCapturedValueFromError(error, digest, stack); } return retrySuspenseComponentWithoutHydrating( @@ -17246,7 +16677,7 @@ to return true:wantsResponderID| | pushPrimaryTreeSuspenseHandler(workInProgress); workInProgress.flags &= ~ForceClientRender; - var _capturedValue = createCapturedValue( + var _capturedValue = createCapturedValueFromError( new Error( "There was an error while hydrating this Suspense boundary. " + "Switched to client rendering." @@ -17735,8 +17166,12 @@ to return true:wantsResponderID| | var hasWarnedAboutUsingNoValuePropOnContextProvider = false; function updateContextProvider(current, workInProgress, renderLanes) { - var providerType = workInProgress.type; - var context = providerType._context; + var context; + + { + context = workInProgress.type._context; + } + var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; var newValue = newProps.value; @@ -17751,17 +17186,6 @@ to return true:wantsResponderID| | ); } } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes( - providerPropTypes, - newProps, - "prop", - "Context.Provider" - ); - } } pushProvider(workInProgress, context, newValue); @@ -17795,34 +17219,16 @@ to return true:wantsResponderID| | return workInProgress.child; } - var hasWarnedAboutUsingContextAsConsumer = false; - function updateContextConsumer(current, workInProgress, renderLanes) { - var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. + var context; { - if (context._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; + context = workInProgress.type; - error( - "Rendering directly is not supported and will be removed in " + - "a future major release. Did you mean to render instead?" - ); - } + { + if (context._context !== undefined) { + context = context._context; } - } else { - context = context._context; } } @@ -17923,7 +17329,11 @@ to return true:wantsResponderID| | newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. + newWorkInProgress.ref = oldWorkInProgress.ref; + + { + newWorkInProgress._debugInfo = oldWorkInProgress._debugInfo; + } // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; @@ -17995,12 +17405,6 @@ to return true:wantsResponderID| | break; case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - pushContextProvider(workInProgress); - } - break; } @@ -18013,7 +17417,12 @@ to return true:wantsResponderID| | case ContextProvider: { var newValue = workInProgress.memoizedProps.value; - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + pushProvider(workInProgress, context, newValue); break; } @@ -18171,7 +17580,7 @@ to return true:wantsResponderID| | return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } - function beginWork$1(current, workInProgress, renderLanes) { + function beginWork(current, workInProgress, renderLanes) { { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. @@ -18357,31 +17766,16 @@ to return true:wantsResponderID| | return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { - var _type2 = workInProgress.type; + var _type = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + var _resolvedProps3 = resolveDefaultProps(_type, _unresolvedProps3); - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - _resolvedProps3, // Resolved for outer only - "prop", - getComponentNameFromType(_type2) - ); - } - } - } - - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + _resolvedProps3 = resolveDefaultProps(_type.type, _resolvedProps3); return updateMemoComponent( current, workInProgress, - _type2, + _type, _resolvedProps3, renderLanes ); @@ -18744,7 +18138,7 @@ to return true:wantsResponderID| | return readContextForConsumer(currentlyRenderingFiber, context); } - function readContextDuringReconcilation(consumer, context, renderLanes) { + function readContextDuringReconciliation(consumer, context, renderLanes) { if (currentlyRenderingFiber === null) { prepareToReadContext(consumer, renderLanes); } @@ -18824,10 +18218,6 @@ to return true:wantsResponderID| | workInProgress.flags |= Update; } - function markRef(workInProgress) { - workInProgress.flags |= Ref | RefStatic; - } - function appendAllChildren( parent, workInProgress, @@ -19234,12 +18624,6 @@ to return true:wantsResponderID| | return null; case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - bubbleProperties(workInProgress); return null; } @@ -19247,7 +18631,6 @@ to return true:wantsResponderID| | case HostRoot: { var fiberRoot = workInProgress.stateNode; popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; @@ -19302,10 +18685,6 @@ to return true:wantsResponderID| | if (current !== null && workInProgress.stateNode != null) { updateHostComponent(current, workInProgress, _type2, newProps); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } } else { if (!newProps) { if (workInProgress.stateNode === null) { @@ -19351,11 +18730,6 @@ to return true:wantsResponderID| | markUpdate(workInProgress); } } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } } bubbleProperties(workInProgress); // This must come at the very end of the complete phase, because it might @@ -19410,7 +18784,6 @@ to return true:wantsResponderID| | } case SuspenseComponent: { - popSuspenseHandler(workInProgress); var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this // to its own fiber type so that we can add other kinds of hydration // boundaries that aren't associated with a Suspense tree. In anticipation @@ -19431,17 +18804,21 @@ to return true:wantsResponderID| | if (!fallthroughToNormalSuspensePath) { if (workInProgress.flags & ForceClientRender) { - // Special case. There were remaining unhydrated nodes. We treat + popSuspenseHandler(workInProgress); // Special case. There were remaining unhydrated nodes. We treat // this as a mismatch. Revert to client rendering. + return workInProgress; } else { - // Did not finish hydrating, either because this is the initial + popSuspenseHandler(workInProgress); // Did not finish hydrating, either because this is the initial // render or because something suspended. + return null; } } // Continue with the normal Suspense path. } + popSuspenseHandler(workInProgress); + if ((workInProgress.flags & DidCapture) !== NoFlags$1) { // Something suspended. Re-render with the fallback children. workInProgress.lanes = renderLanes; // Do not reset the effect list. @@ -19507,20 +18884,17 @@ to return true:wantsResponderID| | case ContextProvider: // Pop provider fiber - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + popProvider(context, workInProgress); bubbleProperties(workInProgress); return null; case IncompleteClassComponent: { - // Same as class component case. I put it down here so that the tags are - // sequential to ensure this switch is compiled to a jump table. - var _Component = workInProgress.type; - - if (isContextProvider(_Component)) { - popContext(workInProgress); - } - bubbleProperties(workInProgress); return null; } @@ -19812,12 +19186,6 @@ to return true:wantsResponderID| | function unwindWork(current, workInProgress, renderLanes) { switch (workInProgress.tag) { case ClassComponent: { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - var flags = workInProgress.flags; if (flags & ShouldCapture) { @@ -19835,7 +19203,6 @@ to return true:wantsResponderID| | case HostRoot: { popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); var _flags = workInProgress.flags; if ( @@ -19899,7 +19266,12 @@ to return true:wantsResponderID| | return null; case ContextProvider: - var context = workInProgress.type._context; + var context; + + { + context = workInProgress.type._context; + } + popProvider(context, workInProgress); return null; @@ -19936,18 +19308,11 @@ to return true:wantsResponderID| | function unwindInterruptedWork(current, interruptedWork, renderLanes) { switch (interruptedWork.tag) { case ClassComponent: { - var childContextTypes = interruptedWork.type.childContextTypes; - - if (childContextTypes !== null && childContextTypes !== undefined) { - popContext(interruptedWork); - } - break; } case HostRoot: { popHostContainer(interruptedWork); - popTopLevelContextObject(interruptedWork); break; } @@ -19971,7 +19336,12 @@ to return true:wantsResponderID| | break; case ContextProvider: - var context = interruptedWork.type._context; + var context; + + { + context = interruptedWork.type._context; + } + popProvider(context, interruptedWork); break; @@ -20005,20 +19375,6 @@ to return true:wantsResponderID| | ); } - function reportUncaughtErrorInDEV(error) { - // Wrapping each small part of the commit phase into a guarded - // callback is a bit too slow (https://github.com/facebook/react/pull/21666). - // But we rely on it to surface errors to DEV tools like overlays - // (https://github.com/facebook/react/issues/21712). - // As a compromise, rethrow only caught errors in a guard. - { - invokeGuardedCallback(null, function () { - throw error; - }); - clearCaughtError(); - } - } - function callComponentWillUnmountWithTimer(current, instance) { instance.props = current.memoizedProps; instance.state = current.memoizedState; @@ -20395,7 +19751,7 @@ to return true:wantsResponderID| | " }\n" + " fetchData();\n" + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + - "Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching"; + "Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching"; } else { addendum = " You returned: " + destroy; } @@ -21030,6 +20386,8 @@ to return true:wantsResponderID| | } } else { { + // TODO: We should move these warnings to happen during the render + // phase (markRef). if (!ref.hasOwnProperty("current")) { error( "Unexpected ref object provided for %s. " + @@ -23283,7 +22641,9 @@ to return true:wantsResponderID| | var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. // We will log them once the tree commits. - var workInProgressRootRecoverableErrors = null; // The most recent time we either committed a fallback, or when a fallback was + var workInProgressRootRecoverableErrors = null; // Tracks when an update occurs during the render phase. + + var workInProgressRootDidIncludeRecursiveRenderUpdate = false; // Thacks when an update occurs during the commit phase. It's a separate // filled in with the resolved UI. This lets us throttle the appearance of new // content as it streams in, to minimize jank. // TODO: Think of a better name for this variable? @@ -23307,7 +22667,7 @@ to return true:wantsResponderID| | } var hasUncaughtError = false; var firstUncaughtError = null; - var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; + var legacyErrorBoundariesThatAlreadyFailed = null; var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsLanes = NoLanes; @@ -23799,6 +23159,7 @@ to return true:wantsResponderID| | root, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane ); } else { @@ -23829,6 +23190,7 @@ to return true:wantsResponderID| | finishedWork, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane ), @@ -23843,6 +23205,7 @@ to return true:wantsResponderID| | finishedWork, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane ); @@ -23854,6 +23217,7 @@ to return true:wantsResponderID| | finishedWork, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, lanes, spawnedLane ) { @@ -23878,14 +23242,26 @@ to return true:wantsResponderID| | // us that it's ready. This will be canceled if we start work on the // root again. root.cancelPendingCommit = schedulePendingCommit( - commitRoot.bind(null, root, recoverableErrors, transitions) + commitRoot.bind( + null, + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate + ) ); markRootSuspended(root, lanes, spawnedLane); return; } } // Otherwise, commit immediately. - commitRoot(root, recoverableErrors, transitions, spawnedLane); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); } function isRenderConsistentWithExternalStores(finishedWork) { @@ -23948,13 +23324,23 @@ to return true:wantsResponderID| | // eslint-disable-next-line no-unreachable return true; + } // The extra indirections around markRootUpdated and markRootSuspended is + // needed to avoid a circular dependency between this module and + // ReactFiberLane. There's probably a better way to split up these modules and + // avoid this problem. Perhaps all the root-marking functions should move into + // the work loop. + + function markRootUpdated(root, updatedLanes) { + markRootUpdated$1(root, updatedLanes); + } + + function markRootPinged(root, pingedLanes) { + markRootPinged$1(root, pingedLanes); } function markRootSuspended(root, suspendedLanes, spawnedLane) { // When suspending, we should always exclude lanes that were pinged or (more // rarely, since we try to avoid it) updated during the render phase. - // TODO: Lol maybe there's a better way to factor this besides this - // obnoxiously named function :) suspendedLanes = removeLanes( suspendedLanes, workInProgressRootPingedLanes @@ -23963,6 +23349,7 @@ to return true:wantsResponderID| | suspendedLanes, workInProgressRootInterleavedUpdatedLanes ); + markRootSuspended$1(root, suspendedLanes, spawnedLane); } // This is the entry point for synchronous tasks that don't go // through Scheduler @@ -24037,6 +23424,7 @@ to return true:wantsResponderID| | root, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane ); // Before exiting, make sure there's a callback scheduled for the next // pending level. @@ -24181,7 +23569,8 @@ to return true:wantsResponderID| | workInProgressRootPingedLanes = NoLanes; workInProgressDeferredLane = NoLane; workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; // Get the lanes that are entangled with whatever we're about to render. We + workInProgressRootRecoverableErrors = null; + workInProgressRootDidIncludeRecursiveRenderUpdate = false; // Get the lanes that are entangled with whatever we're about to render. We // track these separately so we can distinguish the priority of the render // task from the priority of the lanes it is entangled with. For example, a // transition may not be allowed to finish unless it includes the Sync lane, @@ -24856,15 +24245,6 @@ to return true:wantsResponderID| | : resolveDefaultProps(Component, unresolvedProps); var context; - { - var unmaskedContext = getUnmaskedContext( - unitOfWork, - Component, - true - ); - context = getMaskedContext(unitOfWork, unmaskedContext); - } - next = replayFunctionComponent( current, unitOfWork, @@ -25145,7 +24525,13 @@ to return true:wantsResponderID| | workInProgress = null; } - function commitRoot(root, recoverableErrors, transitions, spawnedLane) { + function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ) { // TODO: This no longer makes any sense. We already wrap the mutation and // layout phases. Should be able to remove. var previousUpdateLanePriority = getCurrentUpdatePriority(); @@ -25158,6 +24544,7 @@ to return true:wantsResponderID| | root, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, previousUpdateLanePriority, spawnedLane ); @@ -25173,6 +24560,7 @@ to return true:wantsResponderID| | root, recoverableErrors, transitions, + didIncludeRenderPhaseUpdate, renderPriorityLevel, spawnedLane ) { @@ -25232,7 +24620,7 @@ to return true:wantsResponderID| | var concurrentlyUpdatedLanes = getConcurrentlyUpdatedLanes(); remainingLanes = mergeLanes(remainingLanes, concurrentlyUpdatedLanes); - markRootFinished(root, remainingLanes, spawnedLane); + markRootFinished(root, remainingLanes, spawnedLane); // Reset this before firing side effects so we can detect recursive updates. if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -25295,7 +24683,7 @@ to return true:wantsResponderID| | // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. commitMutationEffects(root, finishedWork, lanes); // the mutation phase, so that the previous tree is still current during @@ -25414,6 +24802,9 @@ to return true:wantsResponderID| | // hydration is conceptually not an update. if ( + // Check if there was a recursive update spawned by this render, in either + // the render phase or the commit phase. We track these explicitly because + // we can't infer from the remaining lanes alone. // Was the finished render the result of an update (not hydration)? includesSomeLane(lanes, UpdateLanes) && // Did it schedule a sync update? includesSomeLane(remainingLanes, SyncUpdateLanes) @@ -25613,7 +25004,6 @@ to return true:wantsResponderID| | error$1 ) { { - reportUncaughtErrorInDEV(error$1); setIsRunningInsertionEffect(false); } @@ -25835,6 +25225,7 @@ to return true:wantsResponderID| | nestedPassiveUpdateCount = 0; rootWithNestedUpdates = null; rootWithPassiveNestedUpdates = null; + throw new Error( "Maximum update depth exceeded. This can happen when a component " + "repeatedly calls setState inside componentWillUpdate or " + @@ -25991,81 +25382,6 @@ to return true:wantsResponderID| | } } } - var beginWork; - - { - var dummyFiber = null; - - beginWork = function (current, unitOfWork, lanes) { - // If a component throws an error, we replay it again in a synchronously - // dispatched event, so that the debugger will treat it as an uncaught - // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy - // fiber. If beginWork throws, we'll use this to reset the state. - var originalWorkInProgressCopy = assignFiberPropertiesInDEV( - dummyFiber, - unitOfWork - ); - - try { - return beginWork$1(current, unitOfWork, lanes); - } catch (originalError) { - if ( - didSuspendOrErrorWhileHydratingDEV() || - originalError === SuspenseException || - originalError === SelectiveHydrationException || - (originalError !== null && - typeof originalError === "object" && - typeof originalError.then === "function") - ) { - // Don't replay promises. - // Don't replay errors if we are hydrating and have already suspended or handled an error - throw originalError; - } // Don't reset current debug fiber, since we're about to work on the - // same fiber again. - // Unwind the failed stack frame - - resetSuspendedWorkLoopOnUnwind(unitOfWork); - unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. - - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - - if (unitOfWork.mode & ProfileMode) { - // Reset the profiler timer. - startProfilerTimer(unitOfWork); - } // Run beginWork again. - - invokeGuardedCallback( - null, - beginWork$1, - null, - current, - unitOfWork, - lanes - ); - - if (hasCaughtError()) { - var replayError = clearCaughtError(); - - if ( - typeof replayError === "object" && - replayError !== null && - replayError._suppressLogging && - typeof originalError === "object" && - originalError !== null && - !originalError._suppressLogging - ) { - // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. - originalError._suppressLogging = true; - } - } // We always throw the original error in case the second render pass is not idempotent. - // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. - - throw originalError; - } - }; - } - var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInRenderForAnotherComponent; @@ -26096,7 +25412,7 @@ to return true:wantsResponderID| | error( "Cannot update a component (`%s`) while rendering a " + "different component (`%s`). To locate the bad setState() call inside `%s`, " + - "follow the stack trace as described in https://reactjs.org/link/setstate-in-render", + "follow the stack trace as described in https://react.dev/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName @@ -26205,7 +25521,7 @@ to return true:wantsResponderID| | "/* assert on the output */\n\n" + "This ensures that you're testing the behavior the user would see " + "in the browser." + - " Learn more at https://reactjs.org/link/wrap-tests-with-act", + " Learn more at https://react.dev/link/wrap-tests-with-act", getComponentNameFromFiber(fiber) ); } finally { @@ -26237,7 +25553,7 @@ to return true:wantsResponderID| | "/* assert on the output */\n\n" + "This ensures that you're testing the behavior the user would see " + "in the browser." + - " Learn more at https://reactjs.org/link/wrap-tests-with-act" + " Learn more at https://react.dev/link/wrap-tests-with-act" ); } } @@ -26774,6 +26090,7 @@ to return true:wantsResponderID| | { // This isn't directly used but is handy for debugging internals: + this._debugInfo = null; this._debugOwner = null; this._debugNeedsRemount = false; this._debugHookTypes = null; @@ -26912,6 +26229,7 @@ to return true:wantsResponderID| | } { + workInProgress._debugInfo = current._debugInfo; workInProgress._debugNeedsRemount = current._debugNeedsRemount; switch (workInProgress.tag) { @@ -27110,14 +26428,21 @@ to return true:wantsResponderID| | default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: + case REACT_PROVIDER_TYPE: { fiberTag = ContextProvider; break getTag; + } - case REACT_CONTEXT_TYPE: - // This is a consumer + // Fall through + + case REACT_CONTEXT_TYPE: { fiberTag = ContextConsumer; break getTag; + } + + case REACT_CONSUMER_TYPE: + + // Fall through case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; @@ -27286,54 +26611,6 @@ to return true:wantsResponderID| | implementation: portal.implementation }; return fiber; - } // Used for stashing WIP properties to replay failed work in DEV. - - function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoMode); - } // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.refCleanup = source.refCleanup; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - - { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; } function FiberRootNode( @@ -27445,7 +26722,7 @@ to return true:wantsResponderID| | return root; } - var ReactVersion = "18.3.0-canary-03d6f7cf0-20240209"; + var ReactVersion = "18.3.0-canary-9372c6311-20240315"; function createPortal$1( children, @@ -27487,12 +26764,12 @@ to return true:wantsResponderID| | } var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); + var parentContext = findCurrentUnmaskedContext(); if (fiber.tag === ClassComponent) { var Component = fiber.type; - if (isContextProvider(Component)) { + if (isContextProvider()) { return processChildContext(fiber, Component, parentContext); } } @@ -27537,7 +26814,7 @@ to return true:wantsResponderID| | "%s was passed an instance of %s which is inside StrictMode. " + "Instead, add a ref directly to the element you want to reference. " + "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-find-node", + "https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName @@ -27548,7 +26825,7 @@ to return true:wantsResponderID| | "%s was passed an instance of %s which renders StrictMode children. " + "Instead, add a ref directly to the element you want to reference. " + "Learn more about using refs safely here: " + - "https://reactjs.org/link/strict-mode-find-node", + "https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName @@ -27638,7 +26915,7 @@ to return true:wantsResponderID| | { if (typeof callback !== "function") { error( - "render(...): Expected the last optional `callback` argument to be a " + + "Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callback ); diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js index 7f6b01afe37c76..98d026ddcf474e 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js @@ -8,76 +8,33 @@ * @nolint * @providesModule ReactNativeRenderer-prod * @preventMunge - * @generated SignedSource<> + * @generated SignedSource<> */ "use strict"; require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), - Scheduler = require("scheduler"); -function invokeGuardedCallbackImpl(name, func, context) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } -} -var hasError = !1, + Scheduler = require("scheduler"), + isArrayImpl = Array.isArray, + hasError = !1, caughtError = null, - hasRethrowError = !1, - rethrowError = null, - reporter = { - onError: function (error) { - hasError = !0; - caughtError = error; - } - }; -function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = !1; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); -} -function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f -) { - invokeGuardedCallback.apply(this, arguments); - if (hasError) { - if (hasError) { - var error = caughtError; - hasError = !1; - caughtError = null; - } else - throw Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ); - hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); - } -} -var isArrayImpl = Array.isArray, getFiberCurrentPropsFromNode$1 = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event); + try { + listener(event); + } catch (error) { + hasError || ((hasError = !0), (caughtError = error)); + } event.currentTarget = null; } function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - if (isArrayImpl(dispatchListener)) - throw Error("executeDirectDispatch(...): Invalid `event`."); + if (isArrayImpl(dispatchListener)) throw Error("Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -336,9 +293,7 @@ var instrumentationCallback, }; function accumulate(current, next) { if (null == next) - throw Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); return null == current ? next : isArrayImpl(current) @@ -349,9 +304,7 @@ function accumulate(current, next) { } function accumulateInto(current, next) { if (null == next) - throw Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); if (null == current) return next; if (isArrayImpl(current)) { if (isArrayImpl(next)) return current.push.apply(current, next), current; @@ -940,7 +893,7 @@ eventPluginOrder = Array.prototype.slice.call([ "ReactNativeBridgeEventPlugin" ]); recomputePluginOrdering(); -var injectedNamesToPlugins$jscomp$inline_238 = { +var injectedNamesToPlugins$jscomp$inline_234 = { ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: { eventTypes: {}, @@ -986,32 +939,32 @@ var injectedNamesToPlugins$jscomp$inline_238 = { } } }, - isOrderingDirty$jscomp$inline_239 = !1, - pluginName$jscomp$inline_240; -for (pluginName$jscomp$inline_240 in injectedNamesToPlugins$jscomp$inline_238) + isOrderingDirty$jscomp$inline_235 = !1, + pluginName$jscomp$inline_236; +for (pluginName$jscomp$inline_236 in injectedNamesToPlugins$jscomp$inline_234) if ( - injectedNamesToPlugins$jscomp$inline_238.hasOwnProperty( - pluginName$jscomp$inline_240 + injectedNamesToPlugins$jscomp$inline_234.hasOwnProperty( + pluginName$jscomp$inline_236 ) ) { - var pluginModule$jscomp$inline_241 = - injectedNamesToPlugins$jscomp$inline_238[pluginName$jscomp$inline_240]; + var pluginModule$jscomp$inline_237 = + injectedNamesToPlugins$jscomp$inline_234[pluginName$jscomp$inline_236]; if ( - !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_240) || - namesToPlugins[pluginName$jscomp$inline_240] !== - pluginModule$jscomp$inline_241 + !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_236) || + namesToPlugins[pluginName$jscomp$inline_236] !== + pluginModule$jscomp$inline_237 ) { - if (namesToPlugins[pluginName$jscomp$inline_240]) + if (namesToPlugins[pluginName$jscomp$inline_236]) throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - (pluginName$jscomp$inline_240 + "`.") + (pluginName$jscomp$inline_236 + "`.") ); - namesToPlugins[pluginName$jscomp$inline_240] = - pluginModule$jscomp$inline_241; - isOrderingDirty$jscomp$inline_239 = !0; + namesToPlugins[pluginName$jscomp$inline_236] = + pluginModule$jscomp$inline_237; + isOrderingDirty$jscomp$inline_235 = !0; } } -isOrderingDirty$jscomp$inline_239 && recomputePluginOrdering(); +isOrderingDirty$jscomp$inline_235 && recomputePluginOrdering(); var instanceCache = new Map(), instanceProps = new Map(); function getInstanceFromTag(tag) { @@ -1087,11 +1040,11 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); - if (hasRethrowError) + if (hasError) throw ( - ((JSCompiler_inline_result = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), + ((JSCompiler_inline_result = caughtError), + (hasError = !1), + (caughtError = null), JSCompiler_inline_result) ); } @@ -1165,6 +1118,7 @@ var ReactSharedInternals = REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), @@ -1185,115 +1139,7 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } -var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); -function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE - ? null - : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if ("object" === typeof type) - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - return (type.displayName || "Context") + ".Consumer"; - case REACT_PROVIDER_TYPE: - return (type._context.displayName || "Context") + ".Provider"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || - ((type = innerType.displayName || innerType.name || ""), - (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); - return type; - case REACT_MEMO_TYPE: - return ( - (innerType = type.displayName || null), - null !== innerType - ? innerType - : getComponentNameFromType(type.type) || "Memo" - ); - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) {} - } - return null; -} -function getComponentNameFromFiber(fiber) { - var type = fiber.type; - switch (fiber.tag) { - case 24: - return "Cache"; - case 9: - return (type.displayName || "Context") + ".Consumer"; - case 10: - return (type._context.displayName || "Context") + ".Provider"; - case 18: - return "DehydratedFragment"; - case 11: - return ( - (fiber = type.render), - (fiber = fiber.displayName || fiber.name || ""), - type.displayName || - ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef") - ); - case 7: - return "Fragment"; - case 26: - case 27: - case 5: - return type; - case 4: - return "Portal"; - case 3: - return "Root"; - case 6: - return "Text"; - case 16: - return getComponentNameFromType(type); - case 8: - return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode"; - case 22: - return "Offscreen"; - case 12: - return "Profiler"; - case 21: - return "Scope"; - case 13: - return "Suspense"; - case 19: - return "SuspenseList"; - case 25: - return "TracingMarker"; - case 1: - case 0: - case 17: - case 2: - case 14: - case 15: - if ("function" === typeof type) - return type.displayName || type.name || null; - if ("string" === typeof type) return type; - } - return null; -} +Symbol.for("react.client.reference"); function getNearestMountedFiber(fiber) { var node = fiber, nearestMounted = fiber; @@ -1865,7 +1711,7 @@ function createLaneMap(initial) { for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial); return laneMap; } -function markRootUpdated(root, updateLane) { +function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; 268435456 !== updateLane && ((root.suspendedLanes = 0), (root.pingedLanes = 0)); @@ -1976,18 +1822,7 @@ function getPublicInstance(instance) { : instance; } var scheduleTimeout = setTimeout, - cancelTimeout = clearTimeout; -function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - ownerName && (sourceInfo = " (created by " + ownerName + ")"); - return "\n in " + (name || "Unknown") + sourceInfo; -} -function describeFunctionComponentFrame(fn) { - return fn - ? describeComponentFrame(fn.displayName || fn.name || null, null) - : ""; -} -var hasOwnProperty = Object.prototype.hasOwnProperty, + cancelTimeout = clearTimeout, valueStack = [], index = -1; function createCursor(defaultValue) { @@ -2002,89 +1837,7 @@ function push(cursor, value) { valueStack[index] = cursor.current; cursor.current = value; } -var emptyContextObject = {}, - contextStackCursor$1 = createCursor(emptyContextObject), - didPerformWorkStackCursor = createCursor(!1), - previousContext = emptyContextObject; -function getMaskedContext(workInProgress, unmaskedContext) { - var contextTypes = workInProgress.type.contextTypes; - if (!contextTypes) return emptyContextObject; - var instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) - return instance.__reactInternalMemoizedMaskedChildContext; - var context = {}, - key; - for (key in contextTypes) context[key] = unmaskedContext[key]; - instance && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); - return context; -} -function isContextProvider(type) { - type = type.childContextTypes; - return null !== type && void 0 !== type; -} -function popContext() { - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); -} -function pushTopLevelContextObject(fiber, context, didChange) { - if (contextStackCursor$1.current !== emptyContextObject) - throw Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); - push(contextStackCursor$1, context); - push(didPerformWorkStackCursor, didChange); -} -function processChildContext(fiber, type, parentContext) { - var instance = fiber.stateNode; - type = type.childContextTypes; - if ("function" !== typeof instance.getChildContext) return parentContext; - instance = instance.getChildContext(); - for (var contextKey in instance) - if (!(contextKey in type)) - throw Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - return assign({}, parentContext, instance); -} -function pushContextProvider(workInProgress) { - workInProgress = - ((workInProgress = workInProgress.stateNode) && - workInProgress.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current); - return !0; -} -function invalidateContextProvider(workInProgress, type, didChange) { - var instance = workInProgress.stateNode; - if (!instance) - throw Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ); - didChange - ? ((workInProgress = processChildContext( - workInProgress, - type, - previousContext - )), - (instance.__reactInternalMemoizedMergedChildContext = workInProgress), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - push(contextStackCursor$1, workInProgress)) - : pop(didPerformWorkStackCursor); - push(didPerformWorkStackCursor, didChange); -} +var emptyContextObject = {}; function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } @@ -2291,6 +2044,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { workInProgressRootRenderLanes$11, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane )); } @@ -2645,6 +2399,7 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { if (objectIs(objA, objB)) return !0; if ( @@ -2667,6 +2422,16 @@ function shallowEqual(objA, objB) { } return !0; } +function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + ownerName && (sourceInfo = " (created by " + ownerName + ")"); + return "\n in " + (name || "Unknown") + sourceInfo; +} +function describeFunctionComponentFrame(fn) { + return fn + ? describeComponentFrame(fn.displayName || fn.name || null, null) + : ""; +} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -2755,16 +2520,16 @@ function trackUsedThenable(thenableState, thenable, index) { } } ); - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw ( - ((thenableState = thenable.reason), - checkIfUseWrappedInAsyncCatch(thenableState), - thenableState) - ); - } + } + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw ( + ((thenableState = thenable.reason), + checkIfUseWrappedInAsyncCatch(thenableState), + thenableState) + ); } suspendedThenable = thenable; throw SuspenseException; @@ -2794,56 +2559,54 @@ function unwrapThenable(thenable) { null === thenableState$1 && (thenableState$1 = []); return trackUsedThenable(thenableState$1, thenable, index); } -function coerceRef(returnFiber, current, element) { - returnFiber = element.ref; - if ( - null !== returnFiber && - "function" !== typeof returnFiber && - "object" !== typeof returnFiber - ) { - if (element._owner) { - element = element._owner; - if (element) { - if (1 !== element.tag) - throw Error( - "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref" - ); - var inst = element.stateNode; - } - if (!inst) - throw Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ); - var resolvedInst = inst, - stringRef = "" + returnFiber; - if ( - null !== current && - null !== current.ref && - "function" === typeof current.ref && - current.ref._stringRef === stringRef - ) - return current.ref; - current = function (value) { - var refs = resolvedInst.refs; - null === value ? delete refs[stringRef] : (refs[stringRef] = value); - }; - current._stringRef = stringRef; - return current; - } - if ("string" !== typeof returnFiber) - throw Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - if (!element._owner) - throw Error( - "Element ref was specified as a string (" + - returnFiber + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information." - ); +function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef +) { + function ref(value) { + var refs = inst.refs; + null === value ? delete refs[stringRef] : (refs[stringRef] = value); } - return returnFiber; + var stringRef = "" + mixedRef; + returnFiber = element._owner; + if (!returnFiber) + throw Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://react.dev/link/refs-must-have-owner for more information." + ); + if (1 !== returnFiber.tag) + throw Error( + "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://react.dev/link/strict-mode-string-ref" + ); + var inst = returnFiber.stateNode; + if (!inst) + throw Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + if ( + null !== current && + null !== current.ref && + "function" === typeof current.ref && + current.ref._stringRef === stringRef + ) + return current.ref; + ref._stringRef = stringRef; + return ref; +} +function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef = element.ref; + returnFiber = + "string" === typeof mixedRef || + "number" === typeof mixedRef || + "boolean" === typeof mixedRef + ? convertStringRefToCallbackRef(returnFiber, current, element, mixedRef) + : mixedRef; + workInProgress.ref = returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { returnFiber = Object.prototype.toString.call(newChild); @@ -2875,13 +2638,13 @@ function createChildReconciler(shouldTrackSideEffects) { (currentFirstChild = currentFirstChild.sibling); return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { - for (returnFiber = new Map(); null !== currentFirstChild; ) + function mapRemainingChildren(currentFirstChild) { + for (var existingChildren = new Map(); null !== currentFirstChild; ) null !== currentFirstChild.key - ? returnFiber.set(currentFirstChild.key, currentFirstChild) - : returnFiber.set(currentFirstChild.index, currentFirstChild), + ? existingChildren.set(currentFirstChild.key, currentFirstChild) + : existingChildren.set(currentFirstChild.index, currentFirstChild), (currentFirstChild = currentFirstChild.sibling); - return returnFiber; + return existingChildren; } function useFiber(fiber, pendingProps) { fiber = createWorkInProgress(fiber, pendingProps); @@ -2941,7 +2704,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) return ( (lanes = useFiber(current, element.props)), - (lanes.ref = coerceRef(returnFiber, current, element)), + coerceRef(returnFiber, current, lanes, element), (lanes.return = returnFiber), lanes ); @@ -2953,7 +2716,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes ); - lanes.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, lanes, element); lanes.return = returnFiber; return lanes; } @@ -3015,7 +2778,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef(returnFiber, null, newChild)), + coerceRef(returnFiber, null, lanes, newChild), (lanes.return = returnFiber), lanes ); @@ -3049,7 +2812,7 @@ function createChildReconciler(shouldTrackSideEffects) { if (newChild.$$typeof === REACT_CONTEXT_TYPE) return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3096,7 +2859,7 @@ function createChildReconciler(shouldTrackSideEffects) { return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3164,7 +2927,7 @@ function createChildReconciler(shouldTrackSideEffects) { existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3230,7 +2993,7 @@ function createChildReconciler(shouldTrackSideEffects) { return resultingFirstChild; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++ ) @@ -3318,7 +3081,7 @@ function createChildReconciler(shouldTrackSideEffects) { return iteratorFn; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildrenIterable.next() ) @@ -3380,11 +3143,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) { deleteRemainingChildren(returnFiber, child.sibling); currentFirstChild = useFiber(child, newChild.props); - currentFirstChild.ref = coerceRef( - returnFiber, - child, - newChild - ); + coerceRef(returnFiber, child, currentFirstChild, newChild); currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; @@ -3411,11 +3170,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef( - returnFiber, - currentFirstChild, - newChild - )), + coerceRef(returnFiber, currentFirstChild, lanes, newChild), (lanes.return = returnFiber), (returnFiber = lanes)); } @@ -3461,7 +3216,7 @@ function createChildReconciler(shouldTrackSideEffects) { case REACT_LAZY_TYPE: return ( (child = newChild._init), - reconcileChildFibers( + reconcileChildFibersImpl( returnFiber, currentFirstChild, child(newChild._payload), @@ -3494,7 +3249,7 @@ function createChildReconciler(shouldTrackSideEffects) { return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3518,12 +3273,7 @@ function createChildReconciler(shouldTrackSideEffects) { placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild); } - function reconcileChildFibers( - returnFiber, - currentFirstChild, - newChild, - lanes - ) { + return function (returnFiber, currentFirstChild, newChild, lanes) { thenableIndexCounter$1 = 0; returnFiber = reconcileChildFibersImpl( returnFiber, @@ -3533,8 +3283,7 @@ function createChildReconciler(shouldTrackSideEffects) { ); thenableState$1 = null; return returnFiber; - } - return reconcileChildFibers; + }; } var reconcileChildFibers = createChildReconciler(!0), mountChildFibers = createChildReconciler(!1), @@ -3627,7 +3376,7 @@ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, globalClientIdCounter = 0; function throwInvalidHookError() { throw Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } function areHookInputsEqual(nextDeps, prevDeps) { @@ -4516,30 +4265,17 @@ function checkShouldComponentUpdate( : !0; } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = !1, - unmaskedContext = emptyContextObject; - var context = ctor.contextType; - "object" === typeof context && null !== context - ? (context = readContext(context)) - : ((unmaskedContext = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (isLegacyContextConsumer = ctor.contextTypes), - (context = (isLegacyContextConsumer = - null !== isLegacyContextConsumer && void 0 !== isLegacyContextConsumer) - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject)); + var context = emptyContextObject, + contextType = ctor.contextType; + "object" === typeof contextType && + null !== contextType && + (context = readContext(contextType)); ctor = new ctor(props, context); workInProgress.memoizedState = null !== ctor.state && void 0 !== ctor.state ? ctor.state : null; ctor.updater = classComponentUpdater; workInProgress.stateNode = ctor; ctor._reactInternals = workInProgress; - isLegacyContextConsumer && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); return ctor; } function callComponentWillReceiveProps( @@ -4563,12 +4299,10 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { instance.refs = {}; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; - "object" === typeof contextType && null !== contextType - ? (instance.context = readContext(contextType)) - : ((contextType = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (instance.context = getMaskedContext(workInProgress, contextType))); + instance.context = + "object" === typeof contextType && null !== contextType + ? readContext(contextType) + : emptyContextObject; instance.state = workInProgress.memoizedState; contextType = ctor.getDerivedStateFromProps; "function" === typeof contextType && @@ -4590,12 +4324,23 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { "function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308); } +var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { + if ("object" === typeof value && null !== value) { + var stack = CapturedStacks.get(value); + "string" !== typeof stack && + ((stack = getStackByFiberInDevAndProd(source)), + CapturedStacks.set(value, stack)); + } else stack = getStackByFiberInDevAndProd(source); + return { value: value, source: source, stack: stack, digest: null }; +} +function createCapturedValueFromError(value, digest, stack) { + "string" === typeof stack && CapturedStacks.set(value, stack); return { value: value, - source: source, - stack: getStackByFiberInDevAndProd(source), - digest: null + source: null, + stack: null != stack ? stack : null, + digest: null != digest ? digest : null }; } if ( @@ -4941,7 +4686,7 @@ function updateOffscreenComponent(current, workInProgress, renderLanes) { nextChildren = nextProps.children, nextIsDetached = 0 !== (workInProgress.stateNode._pendingVisibility & 2), prevState = null !== current ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if ("hidden" === nextProps.mode || nextIsDetached) { if (0 !== (workInProgress.flags & 128)) { renderLanes = @@ -4995,13 +4740,20 @@ function deferHiddenOffscreenComponent(current, workInProgress, nextBaseLanes) { pushOffscreenSuspenseHandler(workInProgress); return null; } -function markRef$1(current, workInProgress) { +function markRef(current, workInProgress) { var ref = workInProgress.ref; - if ( - (null === current && null !== ref) || - (null !== current && current.ref !== ref) - ) - (workInProgress.flags |= 512), (workInProgress.flags |= 2097152); + if (null === ref) + null !== current && + null !== current.ref && + (workInProgress.flags |= 2097664); + else { + if ("function" !== typeof ref && "object" !== typeof ref) + throw Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + if (null === current || current.ref !== ref) + workInProgress.flags |= 2097664; + } } function updateFunctionComponent( current, @@ -5010,17 +4762,13 @@ function updateFunctionComponent( nextProps, renderLanes ) { - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(workInProgress, context); prepareToReadContext(workInProgress, renderLanes); Component = renderWithHooks( current, workInProgress, Component, nextProps, - context, + void 0, renderLanes ); if (null !== current && !didReceiveUpdate) @@ -5064,10 +4812,6 @@ function updateClassComponent( nextProps, renderLanes ) { - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; prepareToReadContext(workInProgress, renderLanes); if (null === workInProgress.stateNode) resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), @@ -5079,36 +4823,30 @@ function updateClassComponent( oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context, - contextType = Component.contextType; - "object" === typeof contextType && null !== contextType - ? (contextType = readContext(contextType)) - : ((contextType = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (contextType = getMaskedContext(workInProgress, contextType))); - var getDerivedStateFromProps = Component.getDerivedStateFromProps, - hasNewLifecycles = - "function" === typeof getDerivedStateFromProps || - "function" === typeof instance.getSnapshotBeforeUpdate; - hasNewLifecycles || + contextType = Component.contextType, + nextContext = emptyContextObject; + "object" === typeof contextType && + null !== contextType && + (nextContext = readContext(contextType)); + var getDerivedStateFromProps = Component.getDerivedStateFromProps; + (contextType = + "function" === typeof getDerivedStateFromProps || + "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== nextProps || oldContext !== contextType) && + ((oldProps !== nextProps || oldContext !== nextContext) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - contextType + nextContext )); hasForceUpdate = !1; var oldState = workInProgress.memoizedState; instance.state = oldState; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); oldContext = workInProgress.memoizedState; - oldProps !== nextProps || - oldState !== oldContext || - didPerformWorkStackCursor.current || - hasForceUpdate + oldProps !== nextProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps( workInProgress, @@ -5126,9 +4864,9 @@ function updateClassComponent( nextProps, oldState, oldContext, - contextType + nextContext )) - ? (hasNewLifecycles || + ? (contextType || ("function" !== typeof instance.UNSAFE_componentWillMount && "function" !== typeof instance.componentWillMount) || ("function" === typeof instance.componentWillMount && @@ -5143,7 +4881,7 @@ function updateClassComponent( (workInProgress.memoizedState = oldContext)), (instance.props = nextProps), (instance.state = oldContext), - (instance.context = contextType), + (instance.context = nextContext), (nextProps = oldProps)) : ("function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308), @@ -5151,48 +4889,46 @@ function updateClassComponent( } else { instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); - oldProps = workInProgress.memoizedProps; + nextContext = workInProgress.memoizedProps; contextType = workInProgress.type === workInProgress.elementType - ? oldProps - : resolveDefaultProps(workInProgress.type, oldProps); + ? nextContext + : resolveDefaultProps(workInProgress.type, nextContext); instance.props = contextType; - hasNewLifecycles = workInProgress.pendingProps; - oldState = instance.context; + getDerivedStateFromProps = workInProgress.pendingProps; + var oldContext$jscomp$0 = instance.context; oldContext = Component.contextType; - "object" === typeof oldContext && null !== oldContext - ? (oldContext = readContext(oldContext)) - : ((oldContext = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (oldContext = getMaskedContext(workInProgress, oldContext))); - var getDerivedStateFromProps$jscomp$0 = Component.getDerivedStateFromProps; - (getDerivedStateFromProps = - "function" === typeof getDerivedStateFromProps$jscomp$0 || + oldProps = emptyContextObject; + "object" === typeof oldContext && + null !== oldContext && + (oldProps = readContext(oldContext)); + oldState = Component.getDerivedStateFromProps; + (oldContext = + "function" === typeof oldState || "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== hasNewLifecycles || oldState !== oldContext) && + ((nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== oldProps) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - oldContext + oldProps )); hasForceUpdate = !1; - oldState = workInProgress.memoizedState; - instance.state = oldState; + oldContext$jscomp$0 = workInProgress.memoizedState; + instance.state = oldContext$jscomp$0; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); var newState = workInProgress.memoizedState; - oldProps !== hasNewLifecycles || - oldState !== newState || - didPerformWorkStackCursor.current || + nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== newState || hasForceUpdate - ? ("function" === typeof getDerivedStateFromProps$jscomp$0 && + ? ("function" === typeof oldState && (applyDerivedStateFromProps( workInProgress, Component, - getDerivedStateFromProps$jscomp$0, + oldState, nextProps ), (newState = workInProgress.memoizedState)), @@ -5203,47 +4939,47 @@ function updateClassComponent( Component, contextType, nextProps, - oldState, + oldContext$jscomp$0, newState, - oldContext + oldProps ) || !1) - ? (getDerivedStateFromProps || + ? (oldContext || ("function" !== typeof instance.UNSAFE_componentWillUpdate && "function" !== typeof instance.componentWillUpdate) || ("function" === typeof instance.componentWillUpdate && - instance.componentWillUpdate(nextProps, newState, oldContext), + instance.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof instance.UNSAFE_componentWillUpdate && instance.UNSAFE_componentWillUpdate( nextProps, newState, - oldContext + oldProps )), "function" === typeof instance.componentDidUpdate && (workInProgress.flags |= 4), "function" === typeof instance.getSnapshotBeforeUpdate && (workInProgress.flags |= 1024)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (workInProgress.memoizedProps = nextProps), (workInProgress.memoizedState = newState)), (instance.props = nextProps), (instance.state = newState), - (instance.context = oldContext), + (instance.context = oldProps), (nextProps = contextType)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (nextProps = !1)); } @@ -5252,7 +4988,7 @@ function updateClassComponent( workInProgress, Component, nextProps, - hasContext, + !1, renderLanes ); } @@ -5264,21 +5000,18 @@ function finishClassComponent( hasContext, renderLanes ) { - markRef$1(current, workInProgress); - var didCaptureError = 0 !== (workInProgress.flags & 128); - if (!shouldUpdate && !didCaptureError) - return ( - hasContext && invalidateContextProvider(workInProgress, Component, !1), - bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) - ); + markRef(current, workInProgress); + hasContext = 0 !== (workInProgress.flags & 128); + if (!shouldUpdate && !hasContext) + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); shouldUpdate = workInProgress.stateNode; ReactCurrentOwner$1.current = workInProgress; - var nextChildren = - didCaptureError && "function" !== typeof Component.getDerivedStateFromError + Component = + hasContext && "function" !== typeof Component.getDerivedStateFromError ? null : shouldUpdate.render(); workInProgress.flags |= 1; - null !== current && didCaptureError + null !== current && hasContext ? ((workInProgress.child = reconcileChildFibers( workInProgress, current.child, @@ -5288,26 +5021,13 @@ function finishClassComponent( (workInProgress.child = reconcileChildFibers( workInProgress, null, - nextChildren, + Component, renderLanes ))) - : reconcileChildren(current, workInProgress, nextChildren, renderLanes); + : reconcileChildren(current, workInProgress, Component, renderLanes); workInProgress.memoizedState = shouldUpdate.state; - hasContext && invalidateContextProvider(workInProgress, Component, !0); return workInProgress.child; } -function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - root.pendingContext - ? pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ) - : root.context && - pushTopLevelContextObject(workInProgress, root.context, !1); - pushHostContainer(workInProgress, root.containerInfo); -} var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: null }; @@ -5499,18 +5219,16 @@ function updateDehydratedSuspenseComponent( return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags &= -257), + (didPrimaryChildrenDefer = createCapturedValueFromError( + Error( + "There was an error while hydrating this Suspense boundary. Switched to client rendering." + ) + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: Error( - "There was an error while hydrating this Suspense boundary. Switched to client rendering." - ), - source: null, - stack: null, - digest: null - } + didPrimaryChildrenDefer ) ); if (null !== workInProgress.memoizedState) @@ -5567,17 +5285,16 @@ function updateDehydratedSuspenseComponent( "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering." )), (suspenseState.digest = didPrimaryChildrenDefer), + (didPrimaryChildrenDefer = createCapturedValueFromError( + suspenseState, + didPrimaryChildrenDefer, + void 0 + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: suspenseState, - source: null, - stack: null, - digest: - null != didPrimaryChildrenDefer ? didPrimaryChildrenDefer : null - } + didPrimaryChildrenDefer ) ); didPrimaryChildrenDefer = 0 !== (renderLanes & current.childLanes); @@ -5807,29 +5524,25 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ) { switch (workInProgress.tag) { case 3: - pushHostRootContext(workInProgress); + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 27: case 5: pushHostContext(workInProgress); break; - case 1: - isContextProvider(workInProgress.type) && - pushContextProvider(workInProgress); - break; case 4: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 10: - var context = workInProgress.type._context, - nextValue = workInProgress.memoizedProps.value; + var newValue = workInProgress.memoizedProps.value, + context = workInProgress.type._context; push(valueCursor, context._currentValue); - context._currentValue = nextValue; + context._currentValue = newValue; break; case 13: - context = workInProgress.memoizedState; - if (null !== context) { - if (null !== context.dehydrated) + newValue = workInProgress.memoizedState; + if (null !== newValue) { + if (null !== newValue.dehydrated) return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags |= 128), @@ -5848,9 +5561,9 @@ function attemptEarlyBailoutIfNoScheduledUpdate( pushPrimaryTreeSuspenseHandler(workInProgress); break; case 19: - context = 0 !== (renderLanes & workInProgress.childLanes); + newValue = 0 !== (renderLanes & workInProgress.childLanes); if (0 !== (current.flags & 128)) { - if (context) + if (newValue) return updateSuspenseListComponent( current, workInProgress, @@ -5858,13 +5571,13 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ); workInProgress.flags |= 128; } - nextValue = workInProgress.memoizedState; - null !== nextValue && - ((nextValue.rendering = null), - (nextValue.tail = null), - (nextValue.lastEffect = null)); + context = workInProgress.memoizedState; + null !== context && + ((context.rendering = null), + (context.tail = null), + (context.lastEffect = null)); push(suspenseStackCursor, suspenseStackCursor.current); - if (context) break; + if (newValue) break; else return null; case 22: case 23: @@ -5875,3285 +5588,3255 @@ function attemptEarlyBailoutIfNoScheduledUpdate( } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } -var valueCursor = createCursor(null), - currentlyRenderingFiber = null, - lastContextDependency = null, - lastFullyObservedContext = null; -function resetContextDependencies() { - lastFullyObservedContext = - lastContextDependency = - currentlyRenderingFiber = - null; -} -function popProvider(context) { - context._currentValue = valueCursor.current; - pop(valueCursor); -} -function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - for (; null !== parent; ) { - var alternate = parent.alternate; - (parent.childLanes & renderLanes) !== renderLanes - ? ((parent.childLanes |= renderLanes), - null !== alternate && (alternate.childLanes |= renderLanes)) - : null !== alternate && - (alternate.childLanes & renderLanes) !== renderLanes && - (alternate.childLanes |= renderLanes); - if (parent === propagationRoot) break; - parent = parent.return; - } -} -function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastFullyObservedContext = lastContextDependency = null; - workInProgress = workInProgress.dependencies; - null !== workInProgress && - null !== workInProgress.firstContext && - (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), - (workInProgress.firstContext = null)); -} -function readContext(context) { - return readContextForConsumer(currentlyRenderingFiber, context); -} -function readContextDuringReconcilation(consumer, context, renderLanes) { - null === currentlyRenderingFiber && - prepareToReadContext(consumer, renderLanes); - return readContextForConsumer(consumer, context); -} -function readContextForConsumer(consumer, context) { - var value = context._currentValue; - if (lastFullyObservedContext !== context) - if ( - ((context = { context: context, memoizedValue: value, next: null }), - null === lastContextDependency) - ) { - if (null === consumer) - throw Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." +function beginWork(current, workInProgress, renderLanes) { + if (null !== current) + if (current.memoizedProps !== workInProgress.pendingProps) + didReceiveUpdate = !0; + else { + if ( + 0 === (current.lanes & renderLanes) && + 0 === (workInProgress.flags & 128) + ) + return ( + (didReceiveUpdate = !1), + attemptEarlyBailoutIfNoScheduledUpdate( + current, + workInProgress, + renderLanes + ) ); - lastContextDependency = context; - consumer.dependencies = { lanes: 0, firstContext: context }; - } else lastContextDependency = lastContextDependency.next = context; - return value; -} -var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; -function handleAsyncAction() {} -function scheduleRetryEffect(workInProgress, retryQueue) { - null !== retryQueue - ? (workInProgress.flags |= 4) - : workInProgress.flags & 16384 && - ((retryQueue = - 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), - (workInProgress.lanes |= retryQueue)); -} -function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - switch (renderState.tailMode) { - case "hidden": - hasRenderedATailFallback = renderState.tail; - for (var lastTailNode = null; null !== hasRenderedATailFallback; ) - null !== hasRenderedATailFallback.alternate && - (lastTailNode = hasRenderedATailFallback), - (hasRenderedATailFallback = hasRenderedATailFallback.sibling); - null === lastTailNode - ? (renderState.tail = null) - : (lastTailNode.sibling = null); - break; - case "collapsed": - lastTailNode = renderState.tail; - for (var lastTailNode$61 = null; null !== lastTailNode; ) - null !== lastTailNode.alternate && (lastTailNode$61 = lastTailNode), - (lastTailNode = lastTailNode.sibling); - null === lastTailNode$61 - ? hasRenderedATailFallback || null === renderState.tail - ? (renderState.tail = null) - : (renderState.tail.sibling = null) - : (lastTailNode$61.sibling = null); - } -} -function bubbleProperties(completedWork) { - var didBailout = - null !== completedWork.alternate && - completedWork.alternate.child === completedWork.child, - newChildLanes = 0, - subtreeFlags = 0; - if (didBailout) - for (var child$62 = completedWork.child; null !== child$62; ) - (newChildLanes |= child$62.lanes | child$62.childLanes), - (subtreeFlags |= child$62.subtreeFlags & 31457280), - (subtreeFlags |= child$62.flags & 31457280), - (child$62.return = completedWork), - (child$62 = child$62.sibling); - else - for (child$62 = completedWork.child; null !== child$62; ) - (newChildLanes |= child$62.lanes | child$62.childLanes), - (subtreeFlags |= child$62.subtreeFlags), - (subtreeFlags |= child$62.flags), - (child$62.return = completedWork), - (child$62 = child$62.sibling); - completedWork.subtreeFlags |= subtreeFlags; - completedWork.childLanes = newChildLanes; - return didBailout; -} -function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; + didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; + } + else didReceiveUpdate = !1; + workInProgress.lanes = 0; switch (workInProgress.tag) { case 2: + var Component = workInProgress.type; + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + prepareToReadContext(workInProgress, renderLanes); + var value = renderWithHooks( + null, + workInProgress, + Component, + current, + void 0, + renderLanes + ); + workInProgress.flags |= 1; + "object" === typeof value && + null !== value && + "function" === typeof value.render && + void 0 === value.$$typeof + ? ((workInProgress.tag = 1), + (workInProgress.memoizedState = null), + (workInProgress.updateQueue = null), + (workInProgress.memoizedState = + null !== value.state && void 0 !== value.state + ? value.state + : null), + initializeUpdateQueue(workInProgress), + (value.updater = classComponentUpdater), + (workInProgress.stateNode = value), + (value._reactInternals = workInProgress), + mountClassInstance(workInProgress, Component, current, renderLanes), + (workInProgress = finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ))) + : ((workInProgress.tag = 0), + reconcileChildren(null, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 16: - case 15: + Component = workInProgress.elementType; + a: { + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + value = Component._init; + Component = value(Component._payload); + workInProgress.type = Component; + value = workInProgress.tag = resolveLazyComponentTag(Component); + current = resolveDefaultProps(Component, current); + switch (value) { + case 0: + workInProgress = updateFunctionComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 1: + workInProgress = updateClassComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 11: + workInProgress = updateForwardRef( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 14: + workInProgress = updateMemoComponent( + null, + workInProgress, + Component, + resolveDefaultProps(Component.type, current), + renderLanes + ); + break a; + } + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + ); + } + return workInProgress; case 0: - case 11: - case 7: - case 8: - case 12: - case 9: - case 14: - return bubbleProperties(workInProgress), null; - case 1: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateFunctionComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); - case 3: + case 1: return ( - (renderLanes = workInProgress.stateNode), - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - renderLanes.pendingContext && - ((renderLanes.context = renderLanes.pendingContext), - (renderLanes.pendingContext = null)), - (null !== current && null !== current.child) || - null === current || - (current.memoizedState.isDehydrated && - 0 === (workInProgress.flags & 256)) || - ((workInProgress.flags |= 1024), - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), - (hydrationErrors = null))), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateClassComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); + case 3: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + if (null === current) + throw Error("Should have a current fiber. This is a bug in React."); + value = workInProgress.pendingProps; + Component = workInProgress.memoizedState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, value, null, renderLanes); + value = workInProgress.memoizedState.element; + value === Component + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + )) + : (reconcileChildren(current, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 26: case 27: case 5: - popHostContext(workInProgress); - var type = workInProgress.type; - if (null !== current && null != workInProgress.stateNode) - current.memoizedProps !== newProps && (workInProgress.flags |= 4), - current.ref !== workInProgress.ref && - (workInProgress.flags |= 2097664); - else { - if (!newProps) { - if (null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - bubbleProperties(workInProgress); - return null; - } - current = rootInstanceStackCursor.current; - renderLanes = allocateTag(); - type = getViewConfigForType(type); - var updatePayload = diffProperties( - null, - emptyObject, - newProps, - type.validAttributes - ); - ReactNativePrivateInterface.UIManager.createView( - renderLanes, - type.uiViewClassName, - current, - updatePayload - ); - current = new ReactNativeFiberHostComponent( - renderLanes, - type, - workInProgress - ); - instanceCache.set(renderLanes, workInProgress); - instanceProps.set(renderLanes, newProps); - a: for (renderLanes = workInProgress.child; null !== renderLanes; ) { - if (5 === renderLanes.tag || 6 === renderLanes.tag) - current._children.push(renderLanes.stateNode); - else if (4 !== renderLanes.tag && null !== renderLanes.child) { - renderLanes.child.return = renderLanes; - renderLanes = renderLanes.child; - continue; - } - if (renderLanes === workInProgress) break a; - for (; null === renderLanes.sibling; ) { - if ( - null === renderLanes.return || - renderLanes.return === workInProgress - ) - break a; - renderLanes = renderLanes.return; - } - renderLanes.sibling.return = renderLanes.return; - renderLanes = renderLanes.sibling; - } - workInProgress.stateNode = current; - finalizeInitialChildren(current) && (workInProgress.flags |= 4); - null !== workInProgress.ref && (workInProgress.flags |= 2097664); - } - bubbleProperties(workInProgress); - workInProgress.flags &= -16777217; - return null; + return ( + pushHostContext(workInProgress), + (Component = workInProgress.pendingProps.children), + markRef(current, workInProgress), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); case 6: - if (current && null != workInProgress.stateNode) - current.memoizedProps !== newProps && (workInProgress.flags |= 4); - else { - if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - renderLanes = rootInstanceStackCursor.current; - if (!contextStackCursor.current.isInAParentText) - throw Error( - "Text strings must be rendered within a component." - ); - current = allocateTag(); - ReactNativePrivateInterface.UIManager.createView( - current, - "RCTRawText", - renderLanes, - { text: newProps } - ); - instanceCache.set(current, workInProgress); - workInProgress.stateNode = current; - } - bubbleProperties(workInProgress); return null; case 13: - popSuspenseHandler(workInProgress); - newProps = workInProgress.memoizedState; - if ( - null === current || - (null !== current.memoizedState && - null !== current.memoizedState.dehydrated) - ) { - if (null !== newProps && null !== newProps.dehydrated) { - if (null === current) { - throw Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ); - throw Error( - "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ); - } - 0 === (workInProgress.flags & 128) && - (workInProgress.memoizedState = null); - workInProgress.flags |= 4; - bubbleProperties(workInProgress); - type = !1; - } else - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), - (type = !0); - if (!type) return workInProgress.flags & 256 ? workInProgress : null; - } - if (0 !== (workInProgress.flags & 128)) - return (workInProgress.lanes = renderLanes), workInProgress; - renderLanes = null !== newProps; - renderLanes !== (null !== current && null !== current.memoizedState) && - renderLanes && - (workInProgress.child.flags |= 8192); - scheduleRetryEffect(workInProgress, workInProgress.updateQueue); - bubbleProperties(workInProgress); - return null; + return updateSuspenseComponent(current, workInProgress, renderLanes); case 4: - return popHostContainer(), bubbleProperties(workInProgress), null; - case 10: return ( - popProvider(workInProgress.type._context), - bubbleProperties(workInProgress), - null + pushHostContainer( + workInProgress, + workInProgress.stateNode.containerInfo + ), + (Component = workInProgress.pendingProps), + null === current + ? (workInProgress.child = reconcileChildFibers( + workInProgress, + null, + Component, + renderLanes + )) + : reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 17: + case 11: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateForwardRef(current, workInProgress, Component, value, renderLanes) ); - case 19: - pop(suspenseStackCursor); - type = workInProgress.memoizedState; - if (null === type) return bubbleProperties(workInProgress), null; - newProps = 0 !== (workInProgress.flags & 128); - updatePayload = type.rendering; - if (null === updatePayload) - if (newProps) cutOffTailIfNeeded(type, !1); - else { - if ( - 0 !== workInProgressRootExitStatus || - (null !== current && 0 !== (current.flags & 128)) - ) - for (current = workInProgress.child; null !== current; ) { - updatePayload = findFirstSuspended(current); - if (null !== updatePayload) { - workInProgress.flags |= 128; - cutOffTailIfNeeded(type, !1); - current = updatePayload.updateQueue; - workInProgress.updateQueue = current; - scheduleRetryEffect(workInProgress, current); - workInProgress.subtreeFlags = 0; - for (current = workInProgress.child; null !== current; ) - resetWorkInProgress(current, renderLanes), - (current = current.sibling); - push( - suspenseStackCursor, - (suspenseStackCursor.current & 1) | 2 - ); - return workInProgress.child; - } - current = current.sibling; - } - null !== type.tail && - now() > workInProgressRootRenderTargetTime && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(type, !1), - (workInProgress.lanes = 4194304)); - } - else { - if (!newProps) - if ( - ((current = findFirstSuspended(updatePayload)), null !== current) - ) { - if ( - ((workInProgress.flags |= 128), - (newProps = !0), - (renderLanes = current.updateQueue), - (workInProgress.updateQueue = renderLanes), - scheduleRetryEffect(workInProgress, renderLanes), - cutOffTailIfNeeded(type, !0), - null === type.tail && - "hidden" === type.tailMode && - !updatePayload.alternate) - ) - return bubbleProperties(workInProgress), null; - } else - 2 * now() - type.renderingStartTime > - workInProgressRootRenderTargetTime && - 536870912 !== renderLanes && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(type, !1), - (workInProgress.lanes = 4194304)); - type.isBackwards - ? ((updatePayload.sibling = workInProgress.child), - (workInProgress.child = updatePayload)) - : ((renderLanes = type.last), - null !== renderLanes - ? (renderLanes.sibling = updatePayload) - : (workInProgress.child = updatePayload), - (type.last = updatePayload)); - } - if (null !== type.tail) - return ( - (workInProgress = type.tail), - (type.rendering = workInProgress), - (type.tail = workInProgress.sibling), - (type.renderingStartTime = now()), - (workInProgress.sibling = null), - (renderLanes = suspenseStackCursor.current), - push( - suspenseStackCursor, - newProps ? (renderLanes & 1) | 2 : renderLanes & 1 - ), - workInProgress - ); - bubbleProperties(workInProgress); - return null; - case 22: - case 23: + case 7: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (newProps = null !== workInProgress.memoizedState), - null !== current - ? (null !== current.memoizedState) !== newProps && - (workInProgress.flags |= 8192) - : newProps && (workInProgress.flags |= 8192), - newProps && 0 !== (workInProgress.mode & 1) - ? 0 !== (renderLanes & 536870912) && - 0 === (workInProgress.flags & 128) && - (bubbleProperties(workInProgress), - workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) - : bubbleProperties(workInProgress), - (renderLanes = workInProgress.updateQueue), - null !== renderLanes && - scheduleRetryEffect(workInProgress, renderLanes.retryQueue), - null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps, + renderLanes + ), + workInProgress.child ); - case 24: - return null; - case 25: - return null; - } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -} -function unwindWork(current, workInProgress) { - switch (workInProgress.tag) { - case 1: + case 8: return ( - isContextProvider(workInProgress.type) && popContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child ); - case 3: + case 12: return ( - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - (current = workInProgress.flags), - 0 !== (current & 65536) && 0 === (current & 128) - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child ); - case 26: - case 27: - case 5: - return popHostContext(workInProgress), null; - case 13: - popSuspenseHandler(workInProgress); - current = workInProgress.memoizedState; - if ( - null !== current && - null !== current.dehydrated && - null === workInProgress.alternate - ) - throw Error( - "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." - ); - current = workInProgress.flags; - return current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null; - case 19: - return pop(suspenseStackCursor), null; - case 4: - return popHostContainer(), null; case 10: - return popProvider(workInProgress.type._context), null; - case 22: - case 23: - return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + a: { + Component = workInProgress.type._context; + value = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps, + newValue = value.value; + push(valueCursor, Component._currentValue); + Component._currentValue = newValue; + if (null !== oldProps) + if (objectIs(oldProps.value, newValue)) { + if (oldProps.children === value.children) { + workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + ); + break a; + } + } else + for ( + oldProps = workInProgress.child, + null !== oldProps && (oldProps.return = workInProgress); + null !== oldProps; + + ) { + var list = oldProps.dependencies; + if (null !== list) { + newValue = oldProps.child; + for ( + var dependency = list.firstContext; + null !== dependency; + + ) { + if (dependency.context === Component) { + if (1 === oldProps.tag) { + dependency = createUpdate(renderLanes & -renderLanes); + dependency.tag = 2; + var updateQueue = oldProps.updateQueue; + if (null !== updateQueue) { + updateQueue = updateQueue.shared; + var pending = updateQueue.pending; + null === pending + ? (dependency.next = dependency) + : ((dependency.next = pending.next), + (pending.next = dependency)); + updateQueue.pending = dependency; + } + } + oldProps.lanes |= renderLanes; + dependency = oldProps.alternate; + null !== dependency && (dependency.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + oldProps.return, + renderLanes, + workInProgress + ); + list.lanes |= renderLanes; + break; + } + dependency = dependency.next; + } + } else if (10 === oldProps.tag) + newValue = + oldProps.type === workInProgress.type ? null : oldProps.child; + else if (18 === oldProps.tag) { + newValue = oldProps.return; + if (null === newValue) + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + newValue.lanes |= renderLanes; + list = newValue.alternate; + null !== list && (list.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + newValue, + renderLanes, + workInProgress + ); + newValue = oldProps.sibling; + } else newValue = oldProps.child; + if (null !== newValue) newValue.return = oldProps; + else + for (newValue = oldProps; null !== newValue; ) { + if (newValue === workInProgress) { + newValue = null; + break; + } + oldProps = newValue.sibling; + if (null !== oldProps) { + oldProps.return = newValue.return; + newValue = oldProps; + break; + } + newValue = newValue.return; + } + oldProps = newValue; + } + reconcileChildren(current, workInProgress, value.children, renderLanes); + workInProgress = workInProgress.child; + } + return workInProgress; + case 9: + return ( + (value = workInProgress.type), + (Component = workInProgress.pendingProps.children), + prepareToReadContext(workInProgress, renderLanes), + (value = readContext(value)), + (Component = Component(value)), + (workInProgress.flags |= 1), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); + case 14: + return ( + (Component = workInProgress.type), + (value = resolveDefaultProps(Component, workInProgress.pendingProps)), + (value = resolveDefaultProps(Component.type, value)), + updateMemoComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) + ); + case 15: + return updateSimpleMemoComponent( + current, + workInProgress, + workInProgress.type, + workInProgress.pendingProps, + renderLanes + ); + case 17: + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), + (workInProgress.tag = 1), + prepareToReadContext(workInProgress, renderLanes), + constructClassInstance(workInProgress, Component, value), + mountClassInstance(workInProgress, Component, value, renderLanes), + finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ) ); - case 24: - return null; - case 25: - return null; - default: - return null; - } -} -function unwindInterruptedWork(current, interruptedWork) { - switch (interruptedWork.tag) { - case 1: - current = interruptedWork.type.childContextTypes; - null !== current && void 0 !== current && popContext(); - break; - case 3: - popHostContainer(); - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); - break; - case 26: - case 27: - case 5: - popHostContext(interruptedWork); - break; - case 4: - popHostContainer(); - break; - case 13: - popSuspenseHandler(interruptedWork); - break; case 19: - pop(suspenseStackCursor); - break; - case 10: - popProvider(interruptedWork.type._context); - break; + return updateSuspenseListComponent(current, workInProgress, renderLanes); case 22: - case 23: - popSuspenseHandler(interruptedWork), popHiddenContext(); + return updateOffscreenComponent(current, workInProgress, renderLanes); } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); } -var offscreenSubtreeIsHidden = !1, - offscreenSubtreeWasHidden = !1, - PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, - nextEffect = null; -function safelyAttachRef(current, nearestMountedAncestor) { - try { - var ref = current.ref; - if (null !== ref) { - var instance = current.stateNode; - switch (current.tag) { - case 26: - case 27: - case 5: - var instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - "function" === typeof ref - ? (current.refCleanup = ref(instanceToUse)) - : (ref.current = instanceToUse); - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } +var valueCursor = createCursor(null), + currentlyRenderingFiber = null, + lastContextDependency = null, + lastFullyObservedContext = null; +function resetContextDependencies() { + lastFullyObservedContext = + lastContextDependency = + currentlyRenderingFiber = + null; } -function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref, - refCleanup = current.refCleanup; - if (null !== ref) - if ("function" === typeof refCleanup) - try { - refCleanup(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } finally { - (current.refCleanup = null), - (current = current.alternate), - null != current && (current.refCleanup = null); - } - else if ("function" === typeof ref) - try { - ref(null); - } catch (error$77) { - captureCommitPhaseError(current, nearestMountedAncestor, error$77); - } - else ref.current = null; +function popProvider(context) { + context._currentValue = valueCursor.current; + pop(valueCursor); } -function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); +function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + for (; null !== parent; ) { + var alternate = parent.alternate; + (parent.childLanes & renderLanes) !== renderLanes + ? ((parent.childLanes |= renderLanes), + null !== alternate && (alternate.childLanes |= renderLanes)) + : null !== alternate && + (alternate.childLanes & renderLanes) !== renderLanes && + (alternate.childLanes |= renderLanes); + if (parent === propagationRoot) break; + parent = parent.return; } } -var shouldFireAfterActiveInstanceBlur = !1; -function commitBeforeMutationEffects(root, firstChild) { - for (nextEffect = firstChild; null !== nextEffect; ) +function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastFullyObservedContext = lastContextDependency = null; + workInProgress = workInProgress.dependencies; + null !== workInProgress && + null !== workInProgress.firstContext && + (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), + (workInProgress.firstContext = null)); +} +function readContext(context) { + return readContextForConsumer(currentlyRenderingFiber, context); +} +function readContextDuringReconciliation(consumer, context, renderLanes) { + null === currentlyRenderingFiber && + prepareToReadContext(consumer, renderLanes); + return readContextForConsumer(consumer, context); +} +function readContextForConsumer(consumer, context) { + var value = context._currentValue; + if (lastFullyObservedContext !== context) if ( - ((root = nextEffect), - (firstChild = root.child), - 0 !== (root.subtreeFlags & 1028) && null !== firstChild) - ) - (firstChild.return = root), (nextEffect = firstChild); - else - for (; null !== nextEffect; ) { - root = nextEffect; - try { - var current = root.alternate, - flags = root.flags; - switch (root.tag) { - case 0: - break; - case 11: - case 15: - break; - case 1: - if (0 !== (flags & 1024) && null !== current) { - var prevProps = current.memoizedProps, - prevState = current.memoizedState, - instance = root.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - root.elementType === root.type - ? prevProps - : resolveDefaultProps(root.type, prevProps), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - break; - case 5: - case 26: - case 27: - case 6: - case 4: - case 17: - break; - default: - if (0 !== (flags & 1024)) - throw Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ); - } - } catch (error) { - captureCommitPhaseError(root, root.return, error); - } - firstChild = root.sibling; - if (null !== firstChild) { - firstChild.return = root.return; - nextEffect = firstChild; - break; - } - nextEffect = root.return; - } - current = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = !1; - return current; -} -function commitHookEffectListUnmount( - flags, - finishedWork, - nearestMountedAncestor -) { - var updateQueue = finishedWork.updateQueue; - updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; - if (null !== updateQueue) { - var effect = (updateQueue = updateQueue.next); - do { - if ((effect.tag & flags) === flags) { - var inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - ((inst.destroy = void 0), - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); - } - effect = effect.next; - } while (effect !== updateQueue); - } + ((context = { context: context, memoizedValue: value, next: null }), + null === lastContextDependency) + ) { + if (null === consumer) + throw Error( + "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." + ); + lastContextDependency = context; + consumer.dependencies = { lanes: 0, firstContext: context }; + } else lastContextDependency = lastContextDependency.next = context; + return value; } -function commitHookEffectListMount(flags, finishedWork) { - finishedWork = finishedWork.updateQueue; - finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; - if (null !== finishedWork) { - var effect = (finishedWork = finishedWork.next); - do { - if ((effect.tag & flags) === flags) { - var create$78 = effect.create, - inst = effect.inst; - create$78 = create$78(); - inst.destroy = create$78; - } - effect = effect.next; - } while (effect !== finishedWork); - } +var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; +function handleAsyncAction() {} +function scheduleRetryEffect(workInProgress, retryQueue) { + null !== retryQueue + ? (workInProgress.flags |= 4) + : workInProgress.flags & 16384 && + ((retryQueue = + 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), + (workInProgress.lanes |= retryQueue)); } -function commitHookLayoutEffects(finishedWork, hookFlags) { - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); +function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + switch (renderState.tailMode) { + case "hidden": + hasRenderedATailFallback = renderState.tail; + for (var lastTailNode = null; null !== hasRenderedATailFallback; ) + null !== hasRenderedATailFallback.alternate && + (lastTailNode = hasRenderedATailFallback), + (hasRenderedATailFallback = hasRenderedATailFallback.sibling); + null === lastTailNode + ? (renderState.tail = null) + : (lastTailNode.sibling = null); + break; + case "collapsed": + lastTailNode = renderState.tail; + for (var lastTailNode$61 = null; null !== lastTailNode; ) + null !== lastTailNode.alternate && (lastTailNode$61 = lastTailNode), + (lastTailNode = lastTailNode.sibling); + null === lastTailNode$61 + ? hasRenderedATailFallback || null === renderState.tail + ? (renderState.tail = null) + : (renderState.tail.sibling = null) + : (lastTailNode$61.sibling = null); } } -function commitClassCallbacks(finishedWork) { - var updateQueue = finishedWork.updateQueue; - if (null !== updateQueue) { - var instance = finishedWork.stateNode; - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } +function bubbleProperties(completedWork) { + var didBailout = + null !== completedWork.alternate && + completedWork.alternate.child === completedWork.child, + newChildLanes = 0, + subtreeFlags = 0; + if (didBailout) + for (var child$62 = completedWork.child; null !== child$62; ) + (newChildLanes |= child$62.lanes | child$62.childLanes), + (subtreeFlags |= child$62.subtreeFlags & 31457280), + (subtreeFlags |= child$62.flags & 31457280), + (child$62.return = completedWork), + (child$62 = child$62.sibling); + else + for (child$62 = completedWork.child; null !== child$62; ) + (newChildLanes |= child$62.lanes | child$62.childLanes), + (subtreeFlags |= child$62.subtreeFlags), + (subtreeFlags |= child$62.flags), + (child$62.return = completedWork), + (child$62 = child$62.sibling); + completedWork.subtreeFlags |= subtreeFlags; + completedWork.childLanes = newChildLanes; + return didBailout; } -function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { - var flags = finishedWork.flags; - switch (finishedWork.tag) { +function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; + switch (workInProgress.tag) { + case 2: + case 16: + case 15: case 0: case 11: - case 15: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitHookLayoutEffects(finishedWork, 5); - break; + case 7: + case 8: + case 12: + case 9: + case 14: + return bubbleProperties(workInProgress), null; case 1: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 4) - if (((finishedRoot = finishedWork.stateNode), null === current)) - try { - finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current.memoizedProps - : resolveDefaultProps(finishedWork.type, current.memoizedProps); - current = current.memoizedState; - try { - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$79) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$79 - ); - } - } - flags & 64 && commitClassCallbacks(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; + return bubbleProperties(workInProgress), null; case 3: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { - finishedRoot = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 27: - case 5: - finishedRoot = getPublicInstance(finishedWork.child.stateNode); - break; - case 1: - finishedRoot = finishedWork.child.stateNode; - } - try { - commitCallbacks(flags, finishedRoot); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - break; + return ( + (renderLanes = workInProgress.stateNode), + popHostContainer(), + renderLanes.pendingContext && + ((renderLanes.context = renderLanes.pendingContext), + (renderLanes.pendingContext = null)), + (null !== current && null !== current.child) || + null === current || + (current.memoizedState.isDehydrated && + 0 === (workInProgress.flags & 256)) || + ((workInProgress.flags |= 1024), + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), + (hydrationErrors = null))), + bubbleProperties(workInProgress), + null + ); case 26: case 27: case 5: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 13: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 22: - if (0 !== (finishedWork.mode & 1)) { - if ( - ((prevProps = - null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), - !prevProps) - ) { - current = - (null !== current && null !== current.memoizedState) || - offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevProps; - (offscreenSubtreeWasHidden = current) && - !prevOffscreenSubtreeWasHidden - ? recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - 0 !== (finishedWork.subtreeFlags & 8772) - ) - : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } - } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && - ("manual" === finishedWork.memoizedProps.mode - ? safelyAttachRef(finishedWork, finishedWork.return) - : safelyDetachRef(finishedWork, finishedWork.return)); - break; - default: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - } -} -function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - null !== alternate && - ((fiber.alternate = null), detachFiberAfterEffects(alternate)); - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - fiber.stateNode = null; - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - fiber.updateQueue = null; -} -function isHostParent(fiber) { - return 5 === fiber.tag || 3 === fiber.tag || 4 === fiber.tag; -} -function getHostSibling(fiber) { - a: for (;;) { - for (; null === fiber.sibling; ) { - if (null === fiber.return || isHostParent(fiber.return)) return null; - fiber = fiber.return; - } - fiber.sibling.return = fiber.return; - for ( - fiber = fiber.sibling; - 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; - - ) { - if (fiber.flags & 2) continue a; - if (null === fiber.child || 4 === fiber.tag) continue a; - else (fiber.child.return = fiber), (fiber = fiber.child); - } - if (!(fiber.flags & 2)) return fiber.stateNode; - } -} -function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { - var tag = node.tag; - if (5 === tag || 6 === tag) - if (((node = node.stateNode), before)) { - if ("number" === typeof parent) - throw Error("Container does not support insertBefore operation"); - } else - ReactNativePrivateInterface.UIManager.setChildren(parent, [ - "number" === typeof node ? node : node._nativeTag - ]); - else if (4 !== tag && ((node = node.child), null !== node)) - for ( - insertOrAppendPlacementNodeIntoContainer(node, before, parent), - node = node.sibling; - null !== node; - - ) - insertOrAppendPlacementNodeIntoContainer(node, before, parent), - (node = node.sibling); -} -function insertOrAppendPlacementNode(node, before, parent) { - var tag = node.tag; - if (5 === tag || 6 === tag) - if (((node = node.stateNode), before)) { - tag = parent._children; - var index = tag.indexOf(node); - 0 <= index - ? (tag.splice(index, 1), - (before = tag.indexOf(before)), - tag.splice(before, 0, node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [index], - [before], - [], - [], - [] - )) - : ((before = tag.indexOf(before)), - tag.splice(before, 0, node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [], - [], - ["number" === typeof node ? node : node._nativeTag], - [before], - [] - )); - } else - (before = "number" === typeof node ? node : node._nativeTag), - (tag = parent._children), - (index = tag.indexOf(node)), - 0 <= index - ? (tag.splice(index, 1), - tag.push(node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [index], - [tag.length - 1], - [], - [], - [] - )) - : (tag.push(node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [], - [], - [before], - [tag.length - 1], - [] - )); - else if (4 !== tag && ((node = node.child), null !== node)) - for ( - insertOrAppendPlacementNode(node, before, parent), node = node.sibling; - null !== node; - - ) - insertOrAppendPlacementNode(node, before, parent), (node = node.sibling); -} -var hostParent = null, - hostParentIsContainer = !1; -function recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - parent -) { - for (parent = parent.child; null !== parent; ) - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), - (parent = parent.sibling); -} -function commitDeletionEffectsOnFiber( - finishedRoot, - nearestMountedAncestor, - deletedFiber -) { - if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) - try { - injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); - } catch (err) {} - switch (deletedFiber.tag) { - case 26: - case 27: - case 5: - offscreenSubtreeWasHidden || - safelyDetachRef(deletedFiber, nearestMountedAncestor); - case 6: - var prevHostParent = hostParent, - prevHostParentIsContainer = hostParentIsContainer; - hostParent = null; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - null !== hostParent && - (hostParentIsContainer - ? ((finishedRoot = hostParent), - recursivelyUncacheFiberNode(deletedFiber.stateNode), - ReactNativePrivateInterface.UIManager.manageChildren( - finishedRoot, - [], - [], - [], - [], - [0] - )) - : ((finishedRoot = hostParent), - (nearestMountedAncestor = deletedFiber.stateNode), - recursivelyUncacheFiberNode(nearestMountedAncestor), - (deletedFiber = finishedRoot._children), - (nearestMountedAncestor = deletedFiber.indexOf( - nearestMountedAncestor - )), - deletedFiber.splice(nearestMountedAncestor, 1), - ReactNativePrivateInterface.UIManager.manageChildren( - finishedRoot._nativeTag, - [], - [], - [], - [], - [nearestMountedAncestor] - ))); - break; - case 18: - null !== hostParent && shim$1(); - break; - case 4: - prevHostParent = hostParent; - prevHostParentIsContainer = hostParentIsContainer; - hostParent = deletedFiber.stateNode.containerInfo; - hostParentIsContainer = !0; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - break; - case 0: - case 11: - case 14: - case 15: - if ( - !offscreenSubtreeWasHidden && - ((prevHostParent = deletedFiber.updateQueue), - null !== prevHostParent && - ((prevHostParent = prevHostParent.lastEffect), - null !== prevHostParent)) - ) { - prevHostParentIsContainer = prevHostParent = prevHostParent.next; - do { - var tag = prevHostParentIsContainer.tag, - inst = prevHostParentIsContainer.inst, - destroy = inst.destroy; - void 0 !== destroy && - (0 !== (tag & 2) - ? ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )) - : 0 !== (tag & 4) && - ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - ))); - prevHostParentIsContainer = prevHostParentIsContainer.next; - } while (prevHostParentIsContainer !== prevHostParent); - } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 1: - if ( - !offscreenSubtreeWasHidden && - (safelyDetachRef(deletedFiber, nearestMountedAncestor), - (prevHostParent = deletedFiber.stateNode), - "function" === typeof prevHostParent.componentWillUnmount) - ) - try { - (prevHostParent.props = deletedFiber.memoizedProps), - (prevHostParent.state = deletedFiber.memoizedState), - prevHostParent.componentWillUnmount(); - } catch (error) { - captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); - } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 21: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 22: - safelyDetachRef(deletedFiber, nearestMountedAncestor); - deletedFiber.mode & 1 - ? ((offscreenSubtreeWasHidden = - (prevHostParent = offscreenSubtreeWasHidden) || - null !== deletedFiber.memoizedState), - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ), - (offscreenSubtreeWasHidden = prevHostParent)) - : recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - default: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - } -} -function getRetryCache(finishedWork) { - switch (finishedWork.tag) { - case 13: - case 19: - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); - return retryCache; - case 22: - return ( - (finishedWork = finishedWork.stateNode), - (retryCache = finishedWork._retryCache), - null === retryCache && - (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), - retryCache - ); - default: - throw Error( - "Unexpected Suspense handler tag (" + - finishedWork.tag + - "). This is a bug in React." - ); - } -} -function attachSuspenseRetryListeners(finishedWork, wakeables) { - var retryCache = getRetryCache(finishedWork); - wakeables.forEach(function (wakeable) { - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - retryCache.has(wakeable) || - (retryCache.add(wakeable), wakeable.then(retry, retry)); - }); -} -function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) { - var deletions = parentFiber.deletions; - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - try { - var root = root$jscomp$0, - returnFiber = parentFiber, - parent = returnFiber; - a: for (; null !== parent; ) { - switch (parent.tag) { - case 27: - case 5: - hostParent = parent.stateNode; - hostParentIsContainer = !1; - break a; - case 3: - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = !0; - break a; - case 4: - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = !0; + popHostContext(workInProgress); + var type = workInProgress.type; + if (null !== current && null != workInProgress.stateNode) + current.memoizedProps !== newProps && (workInProgress.flags |= 4); + else { + if (!newProps) { + if (null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + bubbleProperties(workInProgress); + return null; + } + current = rootInstanceStackCursor.current; + renderLanes = allocateTag(); + type = getViewConfigForType(type); + var updatePayload = diffProperties( + null, + emptyObject, + newProps, + type.validAttributes + ); + ReactNativePrivateInterface.UIManager.createView( + renderLanes, + type.uiViewClassName, + current, + updatePayload + ); + current = new ReactNativeFiberHostComponent( + renderLanes, + type, + workInProgress + ); + instanceCache.set(renderLanes, workInProgress); + instanceProps.set(renderLanes, newProps); + a: for (renderLanes = workInProgress.child; null !== renderLanes; ) { + if (5 === renderLanes.tag || 6 === renderLanes.tag) + current._children.push(renderLanes.stateNode); + else if (4 !== renderLanes.tag && null !== renderLanes.child) { + renderLanes.child.return = renderLanes; + renderLanes = renderLanes.child; + continue; + } + if (renderLanes === workInProgress) break a; + for (; null === renderLanes.sibling; ) { + if ( + null === renderLanes.return || + renderLanes.return === workInProgress + ) break a; + renderLanes = renderLanes.return; } - parent = parent.return; - } - if (null === hostParent) - throw Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); - commitDeletionEffectsOnFiber(root, returnFiber, childToDelete); - hostParent = null; - hostParentIsContainer = !1; - var alternate = childToDelete.alternate; - null !== alternate && (alternate.return = null); - childToDelete.return = null; - } catch (error) { - captureCommitPhaseError(childToDelete, parentFiber, error); - } - } - if (parentFiber.subtreeFlags & 12854) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), - (parentFiber = parentFiber.sibling); -} -function commitMutationEffectsOnFiber(finishedWork, root) { - var current = finishedWork.alternate, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - try { - commitHookEffectListUnmount(3, finishedWork, finishedWork.return), - commitHookEffectListMount(3, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - try { - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$87) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$87); - } - } - break; - case 1: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - flags & 64 && - offscreenSubtreeIsHidden && - ((finishedWork = finishedWork.updateQueue), - null !== finishedWork && - ((flags = finishedWork.callbacks), - null !== flags && - ((current = finishedWork.shared.hiddenCallbacks), - (finishedWork.shared.hiddenCallbacks = - null === current ? flags : current.concat(flags))))); - break; - case 26: - case 27: - case 5: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - if (flags & 4 && ((flags = finishedWork.stateNode), null != flags)) { - var newProps = finishedWork.memoizedProps; - current = null !== current ? current.memoizedProps : newProps; - finishedWork.updateQueue = null; - try { - var viewConfig = flags.viewConfig; - instanceProps.set(flags._nativeTag, newProps); - var updatePayload = diffProperties( - null, - current, - newProps, - viewConfig.validAttributes - ); - null != updatePayload && - ReactNativePrivateInterface.UIManager.updateView( - flags._nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } catch (error$90) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$90); + renderLanes.sibling.return = renderLanes.return; + renderLanes = renderLanes.sibling; } + workInProgress.stateNode = current; + finalizeInitialChildren(current) && (workInProgress.flags |= 4); } - break; + bubbleProperties(workInProgress); + workInProgress.flags &= -16777217; + return null; case 6: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - if (null === finishedWork.stateNode) + if (current && null != workInProgress.stateNode) + current.memoizedProps !== newProps && (workInProgress.flags |= 4); + else { + if ("string" !== typeof newProps && null === workInProgress.stateNode) throw Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); - flags = finishedWork.stateNode; - current = finishedWork.memoizedProps; - try { - ReactNativePrivateInterface.UIManager.updateView( - flags, - "RCTRawText", - { text: current } + renderLanes = rootInstanceStackCursor.current; + if (!contextStackCursor.current.isInAParentText) + throw Error( + "Text strings must be rendered within a component." ); - } catch (error$91) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$91); - } - } - break; - case 3: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - break; - case 4: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - break; - case 13: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - finishedWork.child.flags & 8192 && - ((current = null !== current && null !== current.memoizedState), - null === finishedWork.memoizedState || - current || - (globalMostRecentFallbackTime = now())); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); - break; - case 22: - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - viewConfig = null !== finishedWork.memoizedState; - updatePayload = null !== current && null !== current.memoizedState; - if (finishedWork.mode & 1) { - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || viewConfig; - offscreenSubtreeWasHidden = - prevOffscreenSubtreeWasHidden || updatePayload; - recursivelyTraverseMutationEffects(root, finishedWork); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - } else recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - root = finishedWork.stateNode; - root._current = finishedWork; - root._visibility &= -3; - root._visibility |= root._pendingVisibility & 2; + current = allocateTag(); + ReactNativePrivateInterface.UIManager.createView( + current, + "RCTRawText", + renderLanes, + { text: newProps } + ); + instanceCache.set(current, workInProgress); + workInProgress.stateNode = current; + } + bubbleProperties(workInProgress); + return null; + case 13: + newProps = workInProgress.memoizedState; if ( - flags & 8192 && - ((root._visibility = viewConfig - ? root._visibility & -2 - : root._visibility | 1), - viewConfig && - ((root = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), - null === current || - updatePayload || - root || - (0 !== (finishedWork.mode & 1) && - recursivelyTraverseDisappearLayoutEffects(finishedWork))), - null === finishedWork.memoizedProps || - "manual" !== finishedWork.memoizedProps.mode) - ) - a: for (current = null, root = finishedWork; ; ) { - if (5 === root.tag) { - if (null === current) { - current = root; - try { - if (((newProps = root.stateNode), viewConfig)) { - var viewConfig$jscomp$0 = newProps.viewConfig; - var updatePayload$jscomp$0 = diffProperties( - null, - emptyObject, - { style: { display: "none" } }, - viewConfig$jscomp$0.validAttributes - ); - ReactNativePrivateInterface.UIManager.updateView( - newProps._nativeTag, - viewConfig$jscomp$0.uiViewClassName, - updatePayload$jscomp$0 - ); - } else { - var instance = root.stateNode, - props = root.memoizedProps, - viewConfig$jscomp$1 = instance.viewConfig, - prevProps = assign({}, props, { - style: [props.style, { display: "none" }] - }); - var updatePayload$jscomp$1 = diffProperties( - null, - prevProps, - props, - viewConfig$jscomp$1.validAttributes - ); - ReactNativePrivateInterface.UIManager.updateView( - instance._nativeTag, - viewConfig$jscomp$1.uiViewClassName, - updatePayload$jscomp$1 - ); - } - } catch (error) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error + null === current || + (null !== current.memoizedState && + null !== current.memoizedState.dehydrated) + ) { + if (null !== newProps && null !== newProps.dehydrated) { + if (null === current) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + 0 === (workInProgress.flags & 128) && + (workInProgress.memoizedState = null); + workInProgress.flags |= 4; + bubbleProperties(workInProgress); + type = !1; + } else + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), + (type = !0); + if (!type) { + if (workInProgress.flags & 256) + return popSuspenseHandler(workInProgress), workInProgress; + popSuspenseHandler(workInProgress); + return null; + } + } + popSuspenseHandler(workInProgress); + if (0 !== (workInProgress.flags & 128)) + return (workInProgress.lanes = renderLanes), workInProgress; + renderLanes = null !== newProps; + renderLanes !== (null !== current && null !== current.memoizedState) && + renderLanes && + (workInProgress.child.flags |= 8192); + scheduleRetryEffect(workInProgress, workInProgress.updateQueue); + bubbleProperties(workInProgress); + return null; + case 4: + return popHostContainer(), bubbleProperties(workInProgress), null; + case 10: + return ( + popProvider(workInProgress.type._context), + bubbleProperties(workInProgress), + null + ); + case 17: + return bubbleProperties(workInProgress), null; + case 19: + pop(suspenseStackCursor); + type = workInProgress.memoizedState; + if (null === type) return bubbleProperties(workInProgress), null; + newProps = 0 !== (workInProgress.flags & 128); + updatePayload = type.rendering; + if (null === updatePayload) + if (newProps) cutOffTailIfNeeded(type, !1); + else { + if ( + 0 !== workInProgressRootExitStatus || + (null !== current && 0 !== (current.flags & 128)) + ) + for (current = workInProgress.child; null !== current; ) { + updatePayload = findFirstSuspended(current); + if (null !== updatePayload) { + workInProgress.flags |= 128; + cutOffTailIfNeeded(type, !1); + current = updatePayload.updateQueue; + workInProgress.updateQueue = current; + scheduleRetryEffect(workInProgress, current); + workInProgress.subtreeFlags = 0; + for (current = workInProgress.child; null !== current; ) + resetWorkInProgress(current, renderLanes), + (current = current.sibling); + push( + suspenseStackCursor, + (suspenseStackCursor.current & 1) | 2 ); + return workInProgress.child; } + current = current.sibling; } - } else if (6 === root.tag) { - if (null === current) - try { - throw Error("Not yet implemented."); - } catch (error$81) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$81 - ); - } - } else if ( - ((22 !== root.tag && 23 !== root.tag) || - null === root.memoizedState || - root === finishedWork) && - null !== root.child - ) { - root.child.return = root; - root = root.child; - continue; - } - if (root === finishedWork) break a; - for (; null === root.sibling; ) { - if (null === root.return || root.return === finishedWork) break a; - current === root && (current = null); - root = root.return; - } - current === root && (current = null); - root.sibling.return = root.return; - root = root.sibling; + null !== type.tail && + now() > workInProgressRootRenderTargetTime && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(type, !1), + (workInProgress.lanes = 4194304)); } - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((current = flags.retryQueue), - null !== current && - ((flags.retryQueue = null), - attachSuspenseRetryListeners(finishedWork, current)))); + else { + if (!newProps) + if ( + ((current = findFirstSuspended(updatePayload)), null !== current) + ) { + if ( + ((workInProgress.flags |= 128), + (newProps = !0), + (renderLanes = current.updateQueue), + (workInProgress.updateQueue = renderLanes), + scheduleRetryEffect(workInProgress, renderLanes), + cutOffTailIfNeeded(type, !0), + null === type.tail && + "hidden" === type.tailMode && + !updatePayload.alternate) + ) + return bubbleProperties(workInProgress), null; + } else + 2 * now() - type.renderingStartTime > + workInProgressRootRenderTargetTime && + 536870912 !== renderLanes && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(type, !1), + (workInProgress.lanes = 4194304)); + type.isBackwards + ? ((updatePayload.sibling = workInProgress.child), + (workInProgress.child = updatePayload)) + : ((renderLanes = type.last), + null !== renderLanes + ? (renderLanes.sibling = updatePayload) + : (workInProgress.child = updatePayload), + (type.last = updatePayload)); + } + if (null !== type.tail) + return ( + (workInProgress = type.tail), + (type.rendering = workInProgress), + (type.tail = workInProgress.sibling), + (type.renderingStartTime = now()), + (workInProgress.sibling = null), + (renderLanes = suspenseStackCursor.current), + push( + suspenseStackCursor, + newProps ? (renderLanes & 1) | 2 : renderLanes & 1 + ), + workInProgress + ); + bubbleProperties(workInProgress); + return null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (newProps = null !== workInProgress.memoizedState), + null !== current + ? (null !== current.memoizedState) !== newProps && + (workInProgress.flags |= 8192) + : newProps && (workInProgress.flags |= 8192), + newProps && 0 !== (workInProgress.mode & 1) + ? 0 !== (renderLanes & 536870912) && + 0 === (workInProgress.flags & 128) && + (bubbleProperties(workInProgress), + workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) + : bubbleProperties(workInProgress), + (renderLanes = workInProgress.updateQueue), + null !== renderLanes && + scheduleRetryEffect(workInProgress, renderLanes.retryQueue), + null + ); + case 24: + return null; + case 25: + return null; + } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); +} +function unwindWork(current, workInProgress) { + switch (workInProgress.tag) { + case 1: + return ( + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); + case 3: + return ( + popHostContainer(), + (current = workInProgress.flags), + 0 !== (current & 65536) && 0 === (current & 128) + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); + case 26: + case 27: + case 5: + return popHostContext(workInProgress), null; + case 13: + popSuspenseHandler(workInProgress); + current = workInProgress.memoizedState; + if ( + null !== current && + null !== current.dehydrated && + null === workInProgress.alternate + ) + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + current = workInProgress.flags; + return current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null; + case 19: + return pop(suspenseStackCursor), null; + case 4: + return popHostContainer(), null; + case 10: + return popProvider(workInProgress.type._context), null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); + case 24: + return null; + case 25: + return null; + default: + return null; + } +} +function unwindInterruptedWork(current, interruptedWork) { + switch (interruptedWork.tag) { + case 3: + popHostContainer(); + break; + case 26: + case 27: + case 5: + popHostContext(interruptedWork); + break; + case 4: + popHostContainer(); + break; + case 13: + popSuspenseHandler(interruptedWork); break; case 19: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); + pop(suspenseStackCursor); break; - case 21: + case 10: + popProvider(interruptedWork.type._context); break; - default: - recursivelyTraverseMutationEffects(root, finishedWork), - commitReconciliationEffects(finishedWork); + case 22: + case 23: + popSuspenseHandler(interruptedWork), popHiddenContext(); } } -function commitReconciliationEffects(finishedWork) { - var flags = finishedWork.flags; - if (flags & 2) { - try { - a: { - for (var parent = finishedWork.return; null !== parent; ) { - if (isHostParent(parent)) { - var JSCompiler_inline_result = parent; - break a; - } - parent = parent.return; - } - throw Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - switch (JSCompiler_inline_result.tag) { +var offscreenSubtreeIsHidden = !1, + offscreenSubtreeWasHidden = !1, + PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, + nextEffect = null; +function safelyAttachRef(current, nearestMountedAncestor) { + try { + var ref = current.ref; + if (null !== ref) { + var instance = current.stateNode; + switch (current.tag) { + case 26: case 27: case 5: - var parent$jscomp$0 = JSCompiler_inline_result.stateNode; - JSCompiler_inline_result.flags & 32 && - (JSCompiler_inline_result.flags &= -33); - var before = getHostSibling(finishedWork); - insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0); - break; - case 3: - case 4: - var parent$82 = JSCompiler_inline_result.stateNode.containerInfo, - before$83 = getHostSibling(finishedWork); - insertOrAppendPlacementNodeIntoContainer( - finishedWork, - before$83, - parent$82 - ); + var instanceToUse = getPublicInstance(instance); break; default: - throw Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ); + instanceToUse = instance; } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); + "function" === typeof ref + ? (current.refCleanup = ref(instanceToUse)) + : (ref.current = instanceToUse); } - finishedWork.flags &= -3; + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); } - flags & 4096 && (finishedWork.flags &= -4097); } -function recursivelyTraverseLayoutEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 8772) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), - (parentFiber = parentFiber.sibling); +function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref, + refCleanup = current.refCleanup; + if (null !== ref) + if ("function" === typeof refCleanup) + try { + refCleanup(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } finally { + (current.refCleanup = null), + (current = current.alternate), + null != current && (current.refCleanup = null); + } + else if ("function" === typeof ref) + try { + ref(null); + } catch (error$76) { + captureCommitPhaseError(current, nearestMountedAncestor, error$76); + } + else ref.current = null; } -function recursivelyTraverseDisappearLayoutEffects(parentFiber) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - commitHookEffectListUnmount(4, finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 1: - safelyDetachRef(finishedWork, finishedWork.return); - var instance = finishedWork.stateNode; - if ("function" === typeof instance.componentWillUnmount) { - var current = finishedWork, - nearestMountedAncestor = finishedWork.return; - try { - var current$jscomp$0 = current; - instance.props = current$jscomp$0.memoizedProps; - instance.state = current$jscomp$0.memoizedState; - instance.componentWillUnmount(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); +function safelyCallDestroy(current, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } +} +var shouldFireAfterActiveInstanceBlur = !1; +function commitBeforeMutationEffects(root, firstChild) { + for (nextEffect = firstChild; null !== nextEffect; ) + if ( + ((root = nextEffect), + (firstChild = root.child), + 0 !== (root.subtreeFlags & 1028) && null !== firstChild) + ) + (firstChild.return = root), (nextEffect = firstChild); + else + for (; null !== nextEffect; ) { + root = nextEffect; + try { + var current = root.alternate, + flags = root.flags; + switch (root.tag) { + case 0: + break; + case 11: + case 15: + break; + case 1: + if (0 !== (flags & 1024) && null !== current) { + var prevProps = current.memoizedProps, + prevState = current.memoizedState, + instance = root.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + root.elementType === root.type + ? prevProps + : resolveDefaultProps(root.type, prevProps), + prevState + ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + case 3: + break; + case 5: + case 26: + case 27: + case 6: + case 4: + case 17: + break; + default: + if (0 !== (flags & 1024)) + throw Error( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); } + } catch (error) { + captureCommitPhaseError(root, root.return, error); } - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 26: - case 27: - case 5: - safelyDetachRef(finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 22: - safelyDetachRef(finishedWork, finishedWork.return); - null === finishedWork.memoizedState && - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - default: - recursivelyTraverseDisappearLayoutEffects(finishedWork); - } - parentFiber = parentFiber.sibling; - } + firstChild = root.sibling; + if (null !== firstChild) { + firstChild.return = root.return; + nextEffect = firstChild; + break; + } + nextEffect = root.return; + } + current = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = !1; + return current; } -function recursivelyTraverseReappearLayoutEffects( - finishedRoot$jscomp$0, - parentFiber, - includeWorkInProgressEffects +function commitHookEffectListUnmount( + flags, + finishedWork, + nearestMountedAncestor ) { - includeWorkInProgressEffects = - includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - commitHookLayoutEffects(finishedWork, 4); - break; - case 1: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - var instance = finishedWork.stateNode; - if ("function" === typeof instance.componentDidMount) - try { - instance.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - finishedRoot = finishedWork.updateQueue; - if (null !== finishedRoot) { - var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks; - if (null !== hiddenCallbacks) - for ( - finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; - finishedRoot < hiddenCallbacks.length; - finishedRoot++ - ) - callCallback(hiddenCallbacks[finishedRoot], instance); - } - includeWorkInProgressEffects && - flags & 64 && - commitClassCallbacks(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 26: - case 27: - case 5: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 13: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 22: - null === finishedWork.memoizedState && - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - default: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - } - parentFiber = parentFiber.sibling; + var updateQueue = finishedWork.updateQueue; + updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; + if (null !== updateQueue) { + var effect = (updateQueue = updateQueue.next); + do { + if ((effect.tag & flags) === flags) { + var inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + ((inst.destroy = void 0), + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); + } + effect = effect.next; + } while (effect !== updateQueue); } } -function commitHookPassiveMountEffects(finishedWork, hookFlags) { +function commitHookEffectListMount(flags, finishedWork) { + finishedWork = finishedWork.updateQueue; + finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; + if (null !== finishedWork) { + var effect = (finishedWork = finishedWork.next); + do { + if ((effect.tag & flags) === flags) { + var create$77 = effect.create, + inst = effect.inst; + create$77 = create$77(); + inst.destroy = create$77; + } + effect = effect.next; + } while (effect !== finishedWork); + } +} +function commitHookLayoutEffects(finishedWork, hookFlags) { try { commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } -function recursivelyTraversePassiveMountEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveMountOnFiber(root, parentFiber), - (parentFiber = parentFiber.sibling); +function commitClassCallbacks(finishedWork) { + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var instance = finishedWork.stateNode; + try { + commitCallbacks(updateQueue, instance); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } } -function commitPassiveMountOnFiber(finishedRoot, finishedWork) { +function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { var flags = finishedWork.flags; switch (finishedWork.tag) { case 0: case 11: case 15: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitHookLayoutEffects(finishedWork, 5); + break; + case 1: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 4) + if (((finishedRoot = finishedWork.stateNode), null === current)) + try { + finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + else { + var prevProps = + finishedWork.elementType === finishedWork.type + ? current.memoizedProps + : resolveDefaultProps(finishedWork.type, current.memoizedProps); + current = current.memoizedState; + try { + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$78) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$78 + ); + } + } + flags & 64 && commitClassCallbacks(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); break; case 3: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { + finishedRoot = null; + if (null !== finishedWork.child) + switch (finishedWork.child.tag) { + case 27: + case 5: + finishedRoot = getPublicInstance(finishedWork.child.stateNode); + break; + case 1: + finishedRoot = finishedWork.child.stateNode; + } + try { + commitCallbacks(flags, finishedRoot); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } break; - case 23: + case 26: + case 27: + case 5: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); break; - case 22: - flags = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : finishedWork.mode & 1 || - ((flags._visibility |= 4), - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) - : flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : ((flags._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); + case 12: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); break; - case 24: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + case 13: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + break; + case 22: + if (0 !== (finishedWork.mode & 1)) { + if ( + ((prevProps = + null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), + !prevProps) + ) { + current = + (null !== current && null !== current.memoizedState) || + offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevProps; + (offscreenSubtreeWasHidden = current) && + !prevOffscreenSubtreeWasHidden + ? recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + 0 !== (finishedWork.subtreeFlags & 8772) + ) + : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } + } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && + ("manual" === finishedWork.memoizedProps.mode + ? safelyAttachRef(finishedWork, finishedWork.return) + : safelyDetachRef(finishedWork, finishedWork.return)); break; default: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); } } -function recursivelyTraverseReconnectPassiveEffects( - finishedRoot$jscomp$0, - parentFiber -) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - commitHookPassiveMountEffects(finishedWork, 8); - break; - case 23: - break; - case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? instance._visibility & 4 - ? recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - ) - : finishedWork.mode & 1 || - ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )) - : ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - break; - default: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); +function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; + null !== alternate && + ((fiber.alternate = null), detachFiberAfterEffects(alternate)); + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + fiber.stateNode = null; + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; +} +function isHostParent(fiber) { + return 5 === fiber.tag || 3 === fiber.tag || 4 === fiber.tag; +} +function getHostSibling(fiber) { + a: for (;;) { + for (; null === fiber.sibling; ) { + if (null === fiber.return || isHostParent(fiber.return)) return null; + fiber = fiber.return; } - parentFiber = parentFiber.sibling; + fiber.sibling.return = fiber.return; + for ( + fiber = fiber.sibling; + 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; + + ) { + if (fiber.flags & 2) continue a; + if (null === fiber.child || 4 === fiber.tag) continue a; + else (fiber.child.return = fiber), (fiber = fiber.child); + } + if (!(fiber.flags & 2)) return fiber.stateNode; } } -var suspenseyCommitFlag = 8192; -function recursivelyAccumulateSuspenseyCommit(parentFiber) { - if (parentFiber.subtreeFlags & suspenseyCommitFlag) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - accumulateSuspenseyCommitOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); +function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { + var tag = node.tag; + if (5 === tag || 6 === tag) + if (((node = node.stateNode), before)) { + if ("number" === typeof parent) + throw Error("Container does not support insertBefore operation"); + } else + ReactNativePrivateInterface.UIManager.setChildren(parent, [ + "number" === typeof node ? node : node._nativeTag + ]); + else if (4 !== tag && ((node = node.child), null !== node)) + for ( + insertOrAppendPlacementNodeIntoContainer(node, before, parent), + node = node.sibling; + null !== node; + + ) + insertOrAppendPlacementNodeIntoContainer(node, before, parent), + (node = node.sibling); } -function accumulateSuspenseyCommitOnFiber(fiber) { - switch (fiber.tag) { +function insertOrAppendPlacementNode(node, before, parent) { + var tag = node.tag; + if (5 === tag || 6 === tag) + if (((node = node.stateNode), before)) { + tag = parent._children; + var index = tag.indexOf(node); + 0 <= index + ? (tag.splice(index, 1), + (before = tag.indexOf(before)), + tag.splice(before, 0, node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [index], + [before], + [], + [], + [] + )) + : ((before = tag.indexOf(before)), + tag.splice(before, 0, node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [], + [], + ["number" === typeof node ? node : node._nativeTag], + [before], + [] + )); + } else + (before = "number" === typeof node ? node : node._nativeTag), + (tag = parent._children), + (index = tag.indexOf(node)), + 0 <= index + ? (tag.splice(index, 1), + tag.push(node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [index], + [tag.length - 1], + [], + [], + [] + )) + : (tag.push(node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [], + [], + [before], + [tag.length - 1], + [] + )); + else if (4 !== tag && ((node = node.child), null !== node)) + for ( + insertOrAppendPlacementNode(node, before, parent), node = node.sibling; + null !== node; + + ) + insertOrAppendPlacementNode(node, before, parent), (node = node.sibling); +} +var hostParent = null, + hostParentIsContainer = !1; +function recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + parent +) { + for (parent = parent.child; null !== parent; ) + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), + (parent = parent.sibling); +} +function commitDeletionEffectsOnFiber( + finishedRoot, + nearestMountedAncestor, + deletedFiber +) { + if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) + try { + injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); + } catch (err) {} + switch (deletedFiber.tag) { case 26: - recursivelyAccumulateSuspenseyCommit(fiber); - if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) - throw Error( - "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." - ); + case 27: + case 5: + offscreenSubtreeWasHidden || + safelyDetachRef(deletedFiber, nearestMountedAncestor); + case 6: + var prevHostParent = hostParent, + prevHostParentIsContainer = hostParentIsContainer; + hostParent = null; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; + null !== hostParent && + (hostParentIsContainer + ? ((finishedRoot = hostParent), + recursivelyUncacheFiberNode(deletedFiber.stateNode), + ReactNativePrivateInterface.UIManager.manageChildren( + finishedRoot, + [], + [], + [], + [], + [0] + )) + : ((finishedRoot = hostParent), + (nearestMountedAncestor = deletedFiber.stateNode), + recursivelyUncacheFiberNode(nearestMountedAncestor), + (deletedFiber = finishedRoot._children), + (nearestMountedAncestor = deletedFiber.indexOf( + nearestMountedAncestor + )), + deletedFiber.splice(nearestMountedAncestor, 1), + ReactNativePrivateInterface.UIManager.manageChildren( + finishedRoot._nativeTag, + [], + [], + [], + [], + [nearestMountedAncestor] + ))); break; - case 5: - recursivelyAccumulateSuspenseyCommit(fiber); + case 18: + null !== hostParent && shim$1(); break; - case 3: case 4: - recursivelyAccumulateSuspenseyCommit(fiber); - break; - case 22: - if (null === fiber.memoizedState) { - var current = fiber.alternate; - null !== current && null !== current.memoizedState - ? ((current = suspenseyCommitFlag), - (suspenseyCommitFlag = 16777216), - recursivelyAccumulateSuspenseyCommit(fiber), - (suspenseyCommitFlag = current)) - : recursivelyAccumulateSuspenseyCommit(fiber); - } + prevHostParent = hostParent; + prevHostParentIsContainer = hostParentIsContainer; + hostParent = deletedFiber.stateNode.containerInfo; + hostParentIsContainer = !0; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; break; - default: - recursivelyAccumulateSuspenseyCommit(fiber); - } -} -function detachAlternateSiblings(parentFiber) { - var previousFiber = parentFiber.alternate; - if ( - null !== previousFiber && - ((parentFiber = previousFiber.child), null !== parentFiber) - ) { - previousFiber.child = null; - do - (previousFiber = parentFiber.sibling), - (parentFiber.sibling = null), - (parentFiber = previousFiber); - while (null !== parentFiber); - } -} -function recursivelyTraversePassiveUnmountEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveUnmountOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); -} -function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { case 0: case 11: + case 14: case 15: - recursivelyTraversePassiveUnmountEffects(finishedWork); - finishedWork.flags & 2048 && - commitHookEffectListUnmount(9, finishedWork, finishedWork.return); + if ( + !offscreenSubtreeWasHidden && + ((prevHostParent = deletedFiber.updateQueue), + null !== prevHostParent && + ((prevHostParent = prevHostParent.lastEffect), + null !== prevHostParent)) + ) { + prevHostParentIsContainer = prevHostParent = prevHostParent.next; + do { + var tag = prevHostParentIsContainer.tag, + inst = prevHostParentIsContainer.inst, + destroy = inst.destroy; + void 0 !== destroy && + (0 !== (tag & 2) + ? ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )) + : 0 !== (tag & 4) && + ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + ))); + prevHostParentIsContainer = prevHostParentIsContainer.next; + } while (prevHostParentIsContainer !== prevHostParent); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 1: + if ( + !offscreenSubtreeWasHidden && + (safelyDetachRef(deletedFiber, nearestMountedAncestor), + (prevHostParent = deletedFiber.stateNode), + "function" === typeof prevHostParent.componentWillUnmount) + ) + try { + (prevHostParent.props = deletedFiber.memoizedProps), + (prevHostParent.state = deletedFiber.memoizedState), + prevHostParent.componentWillUnmount(); + } catch (error) { + captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + break; + case 21: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState && - instance._visibility & 4 && - (null === finishedWork.return || 13 !== finishedWork.return.tag) - ? ((instance._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(finishedWork)) - : recursivelyTraversePassiveUnmountEffects(finishedWork); + safelyDetachRef(deletedFiber, nearestMountedAncestor); + deletedFiber.mode & 1 + ? ((offscreenSubtreeWasHidden = + (prevHostParent = offscreenSubtreeWasHidden) || + null !== deletedFiber.memoizedState), + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ), + (offscreenSubtreeWasHidden = prevHostParent)) + : recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; default: - recursivelyTraversePassiveUnmountEffects(finishedWork); - } -} -function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - deletions = parentFiber; - switch (deletions.tag) { - case 0: - case 11: - case 15: - commitHookEffectListUnmount(8, deletions, deletions.return); - recursivelyTraverseDisconnectPassiveEffects(deletions); - break; - case 22: - i = deletions.stateNode; - i._visibility & 4 && - ((i._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(deletions)); - break; - default: - recursivelyTraverseDisconnectPassiveEffects(deletions); - } - parentFiber = parentFiber.sibling; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); } } -function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - deletedSubtreeRoot, - nearestMountedAncestor -) { - for (; null !== nextEffect; ) { - var fiber = nextEffect; - switch (fiber.tag) { - case 0: - case 11: - case 15: - commitHookEffectListUnmount(8, fiber, nearestMountedAncestor); - } - var child = fiber.child; - if (null !== child) (child.return = fiber), (nextEffect = child); - else - a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { - child = nextEffect; - var sibling = child.sibling, - returnFiber = child.return; - detachFiberAfterEffects(child); - if (child === fiber) { - nextEffect = null; - break a; - } - if (null !== sibling) { - sibling.return = returnFiber; - nextEffect = sibling; - break a; - } - nextEffect = returnFiber; - } +function getRetryCache(finishedWork) { + switch (finishedWork.tag) { + case 13: + case 19: + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); + return retryCache; + case 22: + return ( + (finishedWork = finishedWork.stateNode), + (retryCache = finishedWork._retryCache), + null === retryCache && + (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), + retryCache + ); + default: + throw Error( + "Unexpected Suspense handler tag (" + + finishedWork.tag + + "). This is a bug in React." + ); } } -var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, - executionContext = 0, - workInProgressRoot = null, - workInProgress = null, - workInProgressRootRenderLanes = 0, - workInProgressSuspendedReason = 0, - workInProgressThrownValue = null, - workInProgressRootDidAttachPingListener = !1, - entangledRenderLanes = 0, - workInProgressRootExitStatus = 0, - workInProgressRootFatalError = null, - workInProgressRootSkippedLanes = 0, - workInProgressRootInterleavedUpdatedLanes = 0, - workInProgressRootPingedLanes = 0, - workInProgressDeferredLane = 0, - workInProgressRootConcurrentErrors = null, - workInProgressRootRecoverableErrors = null, - globalMostRecentFallbackTime = 0, - workInProgressRootRenderTargetTime = Infinity, - workInProgressTransitions = null, - hasUncaughtError = !1, - firstUncaughtError = null, - legacyErrorBoundariesThatAlreadyFailed = null, - rootDoesHavePassiveEffects = !1, - rootWithPendingPassiveEffects = null, - pendingPassiveEffectsLanes = 0, - nestedUpdateCount = 0, - rootWithNestedUpdates = null; -function requestUpdateLane(fiber) { - if (0 === (fiber.mode & 1)) return 2; - if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) - return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; - fiber = ReactCurrentBatchConfig$1.transition; - null !== fiber && fiber._callbacks.add(handleAsyncAction); - if (null !== fiber) - return ( - 0 === currentEventTransitionLane && - (currentEventTransitionLane = claimNextTransitionLane()), - currentEventTransitionLane - ); - fiber = currentUpdatePriority; - return 0 !== fiber ? fiber : 32; -} -function requestDeferredLane() { - 0 === workInProgressDeferredLane && - (workInProgressDeferredLane = - 0 !== (workInProgressRootRenderLanes & 536870912) - ? 536870912 - : claimNextTransitionLane()); - var suspenseHandler = suspenseHandlerStackCursor.current; - null !== suspenseHandler && (suspenseHandler.flags |= 32); - return workInProgressDeferredLane; +function attachSuspenseRetryListeners(finishedWork, wakeables) { + var retryCache = getRetryCache(finishedWork); + wakeables.forEach(function (wakeable) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + retryCache.has(wakeable) || + (retryCache.add(wakeable), wakeable.then(retry, retry)); + }); } -function scheduleUpdateOnFiber(root, fiber, lane) { - if ( - (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || - null !== root.cancelPendingCommit - ) - prepareFreshStack(root, 0), - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); - markRootUpdated(root, lane); - if (0 === (executionContext & 2) || root !== workInProgressRoot) - root === workInProgressRoot && - (0 === (executionContext & 2) && - (workInProgressRootInterleavedUpdatedLanes |= lane), - 4 === workInProgressRootExitStatus && - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - )), - ensureRootIsScheduled(root), - 2 === lane && - 0 === executionContext && - 0 === (fiber.mode & 1) && - ((workInProgressRootRenderTargetTime = now() + 500), - flushSyncWorkAcrossRoots_impl(!0)); +function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) { + var deletions = parentFiber.deletions; + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + var root = root$jscomp$0, + returnFiber = parentFiber, + parent = returnFiber; + a: for (; null !== parent; ) { + switch (parent.tag) { + case 27: + case 5: + hostParent = parent.stateNode; + hostParentIsContainer = !1; + break a; + case 3: + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = !0; + break a; + case 4: + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = !0; + break a; + } + parent = parent.return; + } + if (null === hostParent) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + commitDeletionEffectsOnFiber(root, returnFiber, childToDelete); + hostParent = null; + hostParentIsContainer = !1; + var alternate = childToDelete.alternate; + null !== alternate && (alternate.return = null); + childToDelete.return = null; + } catch (error) { + captureCommitPhaseError(childToDelete, parentFiber, error); + } + } + if (parentFiber.subtreeFlags & 12854) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), + (parentFiber = parentFiber.sibling); } -function performConcurrentWorkOnRoot(root, didTimeout) { - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var originalCallbackNode = root.callbackNode; - if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) - return null; - var lanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : 0 - ); - if (0 === lanes) return null; - var exitStatus = (didTimeout = - 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) - ? renderRootConcurrent(root, lanes) - : renderRootSync(root, lanes); - if (0 !== exitStatus) { - var renderWasConcurrent = didTimeout; - do { - if (6 === exitStatus) markRootSuspended(root, lanes, 0); - else { - didTimeout = root.current.alternate; - if ( - renderWasConcurrent && - !isRenderConsistentWithExternalStores(didTimeout) - ) { - exitStatus = renderRootSync(root, lanes); - renderWasConcurrent = !1; - continue; +function commitMutationEffectsOnFiber(finishedWork, root) { + var current = finishedWork.alternate, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + try { + commitHookEffectListUnmount(3, finishedWork, finishedWork.return), + commitHookEffectListMount(3, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } - if (2 === exitStatus) { - renderWasConcurrent = lanes; - var errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - renderWasConcurrent + try { + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$86) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$86); + } + } + break; + case 1: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + flags & 64 && + offscreenSubtreeIsHidden && + ((finishedWork = finishedWork.updateQueue), + null !== finishedWork && + ((flags = finishedWork.callbacks), + null !== flags && + ((current = finishedWork.shared.hiddenCallbacks), + (finishedWork.shared.hiddenCallbacks = + null === current ? flags : current.concat(flags))))); + break; + case 26: + case 27: + case 5: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + if (flags & 4 && ((flags = finishedWork.stateNode), null != flags)) { + var newProps = finishedWork.memoizedProps; + current = null !== current ? current.memoizedProps : newProps; + finishedWork.updateQueue = null; + try { + var viewConfig = flags.viewConfig; + instanceProps.set(flags._nativeTag, newProps); + var updatePayload = diffProperties( + null, + current, + newProps, + viewConfig.validAttributes ); - 0 !== errorRetryLanes && - ((lanes = errorRetryLanes), - (exitStatus = recoverFromConcurrentError( - root, - renderWasConcurrent, - errorRetryLanes - ))); + null != updatePayload && + ReactNativePrivateInterface.UIManager.updateView( + flags._nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } catch (error$89) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$89); } - if (1 === exitStatus) - throw ( - ((originalCallbackNode = workInProgressRootFatalError), - prepareFreshStack(root, 0), - markRootSuspended(root, lanes, 0), - ensureRootIsScheduled(root), - originalCallbackNode) + } + break; + case 6: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + if (null === finishedWork.stateNode) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); + flags = finishedWork.stateNode; + current = finishedWork.memoizedProps; + try { + ReactNativePrivateInterface.UIManager.updateView( + flags, + "RCTRawText", + { text: current } ); - root.finishedWork = didTimeout; - root.finishedLanes = lanes; - a: { - renderWasConcurrent = root; - switch (exitStatus) { - case 0: - case 1: - throw Error("Root did not complete. This is a bug in React."); - case 4: - if ((lanes & 4194176) === lanes) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane + } catch (error$90) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$90); + } + } + break; + case 3: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 4: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 13: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + finishedWork.child.flags & 8192 && + ((current = null !== current && null !== current.memoizedState), + null === finishedWork.memoizedState || + current || + (globalMostRecentFallbackTime = now())); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 22: + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + viewConfig = null !== finishedWork.memoizedState; + updatePayload = null !== current && null !== current.memoizedState; + if (finishedWork.mode & 1) { + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || viewConfig; + offscreenSubtreeWasHidden = + prevOffscreenSubtreeWasHidden || updatePayload; + recursivelyTraverseMutationEffects(root, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + } else recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + root = finishedWork.stateNode; + root._current = finishedWork; + root._visibility &= -3; + root._visibility |= root._pendingVisibility & 2; + if ( + flags & 8192 && + ((root._visibility = viewConfig + ? root._visibility & -2 + : root._visibility | 1), + viewConfig && + ((root = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), + null === current || + updatePayload || + root || + (0 !== (finishedWork.mode & 1) && + recursivelyTraverseDisappearLayoutEffects(finishedWork))), + null === finishedWork.memoizedProps || + "manual" !== finishedWork.memoizedProps.mode) + ) + a: for (current = null, root = finishedWork; ; ) { + if (5 === root.tag) { + if (null === current) { + current = root; + try { + if (((newProps = root.stateNode), viewConfig)) { + var viewConfig$jscomp$0 = newProps.viewConfig; + var updatePayload$jscomp$0 = diffProperties( + null, + emptyObject, + { style: { display: "none" } }, + viewConfig$jscomp$0.validAttributes + ); + ReactNativePrivateInterface.UIManager.updateView( + newProps._nativeTag, + viewConfig$jscomp$0.uiViewClassName, + updatePayload$jscomp$0 + ); + } else { + var instance = root.stateNode, + props = root.memoizedProps, + viewConfig$jscomp$1 = instance.viewConfig, + prevProps = assign({}, props, { + style: [props.style, { display: "none" }] + }); + var updatePayload$jscomp$1 = diffProperties( + null, + prevProps, + props, + viewConfig$jscomp$1.validAttributes + ); + ReactNativePrivateInterface.UIManager.updateView( + instance._nativeTag, + viewConfig$jscomp$1.uiViewClassName, + updatePayload$jscomp$1 + ); + } + } catch (error) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error ); - break a; } - break; - case 2: - case 3: - case 5: - break; - default: - throw Error("Unknown root exit status."); - } - if ( - (lanes & 62914560) === lanes && - 3 === exitStatus && - ((exitStatus = globalMostRecentFallbackTime + 300 - now()), - 10 < exitStatus) + } + } else if (6 === root.tag) { + if (null === current) + try { + throw Error("Not yet implemented."); + } catch (error$80) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$80 + ); + } + } else if ( + ((22 !== root.tag && 23 !== root.tag) || + null === root.memoizedState || + root === finishedWork) && + null !== root.child ) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane - ); - if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; - renderWasConcurrent.timeoutHandle = scheduleTimeout( - commitRootWhenReady.bind( - null, - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ), - exitStatus - ); - break a; + root.child.return = root; + root = root.child; + continue; } - commitRootWhenReady( - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ); + if (root === finishedWork) break a; + for (; null === root.sibling; ) { + if (null === root.return || root.return === finishedWork) break a; + current === root && (current = null); + root = root.return; + } + current === root && (current = null); + root.sibling.return = root.return; + root = root.sibling; } - } + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((current = flags.retryQueue), + null !== current && + ((flags.retryQueue = null), + attachSuspenseRetryListeners(finishedWork, current)))); break; - } while (1); - } - ensureRootIsScheduled(root); - scheduleTaskForRootDuringMicrotask(root, now()); - root = - root.callbackNode === originalCallbackNode - ? performConcurrentWorkOnRoot.bind(null, root) - : null; - return root; -} -function recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes -) { - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, - JSCompiler_inline_result; - (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && - (prepareFreshStack(root, errorRetryLanes).flags |= 256); - errorRetryLanes = renderRootSync(root, errorRetryLanes); - if (2 !== errorRetryLanes) { - if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) - return ( - (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), - (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), - 4 - ); - root = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - null !== root && queueRecoverableErrors(root); - } - return errorRetryLanes; -} -function queueRecoverableErrors(errors) { - null === workInProgressRootRecoverableErrors - ? (workInProgressRootRecoverableErrors = errors) - : workInProgressRootRecoverableErrors.push.apply( - workInProgressRootRecoverableErrors, - errors - ); -} -function commitRootWhenReady( - root, - finishedWork, - recoverableErrors, - transitions, - lanes, - spawnedLane -) { - 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); - commitRoot(root, recoverableErrors, transitions, spawnedLane); + case 19: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 21: + break; + default: + recursivelyTraverseMutationEffects(root, finishedWork), + commitReconciliationEffects(finishedWork); + } } -function isRenderConsistentWithExternalStores(finishedWork) { - for (var node = finishedWork; ; ) { - if (node.flags & 16384) { - var updateQueue = node.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.stores), null !== updateQueue) - ) - for (var i = 0; i < updateQueue.length; i++) { - var check = updateQueue[i], - getSnapshot = check.getSnapshot; - check = check.value; - try { - if (!objectIs(getSnapshot(), check)) return !1; - } catch (error) { - return !1; +function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + if (flags & 2) { + try { + a: { + for (var parent = finishedWork.return; null !== parent; ) { + if (isHostParent(parent)) { + var JSCompiler_inline_result = parent; + break a; } + parent = parent.return; } - } - updateQueue = node.child; - if (node.subtreeFlags & 16384 && null !== updateQueue) - (updateQueue.return = node), (node = updateQueue); - else { - if (node === finishedWork) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === finishedWork) return !0; - node = node.return; + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); } - node.sibling.return = node.return; - node = node.sibling; + switch (JSCompiler_inline_result.tag) { + case 27: + case 5: + var parent$jscomp$0 = JSCompiler_inline_result.stateNode; + JSCompiler_inline_result.flags & 32 && + (JSCompiler_inline_result.flags &= -33); + var before = getHostSibling(finishedWork); + insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0); + break; + case 3: + case 4: + var parent$81 = JSCompiler_inline_result.stateNode.containerInfo, + before$82 = getHostSibling(finishedWork); + insertOrAppendPlacementNodeIntoContainer( + finishedWork, + before$82, + parent$81 + ); + break; + default: + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } + finishedWork.flags &= -3; } - return !0; + flags & 4096 && (finishedWork.flags &= -4097); } -function markRootSuspended(root, suspendedLanes, spawnedLane) { - suspendedLanes &= ~workInProgressRootPingedLanes; - suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - for ( - var expirationTimes = root.expirationTimes, lanes = suspendedLanes; - 0 < lanes; - - ) { - var index$6 = 31 - clz32(lanes), - lane = 1 << index$6; - expirationTimes[index$6] = -1; - lanes &= ~lane; - } - 0 !== spawnedLane && - markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); +function recursivelyTraverseLayoutEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 8772) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), + (parentFiber = parentFiber.sibling); } -function resetWorkInProgressStack() { - if (null !== workInProgress) { - if (0 === workInProgressSuspendedReason) - var interruptedWork = workInProgress.return; - else - (interruptedWork = workInProgress), - resetContextDependencies(), - resetHooksOnUnwind(interruptedWork), - (thenableState$1 = null), - (thenableIndexCounter$1 = 0), - (interruptedWork = workInProgress); - for (; null !== interruptedWork; ) - unwindInterruptedWork(interruptedWork.alternate, interruptedWork), - (interruptedWork = interruptedWork.return); - workInProgress = null; +function recursivelyTraverseDisappearLayoutEffects(parentFiber) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 1: + safelyDetachRef(finishedWork, finishedWork.return); + var instance = finishedWork.stateNode; + if ("function" === typeof instance.componentWillUnmount) { + var current = finishedWork, + nearestMountedAncestor = finishedWork.return; + try { + var current$jscomp$0 = current; + instance.props = current$jscomp$0.memoizedProps; + instance.state = current$jscomp$0.memoizedState; + instance.componentWillUnmount(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 26: + case 27: + case 5: + safelyDetachRef(finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 22: + safelyDetachRef(finishedWork, finishedWork.return); + null === finishedWork.memoizedState && + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + default: + recursivelyTraverseDisappearLayoutEffects(finishedWork); + } + parentFiber = parentFiber.sibling; } } -function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = 0; - var timeoutHandle = root.timeoutHandle; - -1 !== timeoutHandle && - ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); - timeoutHandle = root.cancelPendingCommit; - null !== timeoutHandle && - ((root.cancelPendingCommit = null), timeoutHandle()); - resetWorkInProgressStack(); - workInProgressRoot = root; - workInProgress = timeoutHandle = createWorkInProgress(root.current, null); - workInProgressRootRenderLanes = lanes; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - workInProgressRootDidAttachPingListener = !1; - workInProgressRootExitStatus = 0; - workInProgressRootFatalError = null; - workInProgressDeferredLane = - workInProgressRootPingedLanes = - workInProgressRootInterleavedUpdatedLanes = - workInProgressRootSkippedLanes = - 0; - workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = - null; - 0 !== (lanes & 8) && (lanes |= lanes & 32); - var allEntangledLanes = root.entangledLanes; - if (0 !== allEntangledLanes) - for ( - root = root.entanglements, allEntangledLanes &= lanes; - 0 < allEntangledLanes; - - ) { - var index$4 = 31 - clz32(allEntangledLanes), - lane = 1 << index$4; - lanes |= root[index$4]; - allEntangledLanes &= ~lane; +function recursivelyTraverseReappearLayoutEffects( + finishedRoot$jscomp$0, + parentFiber, + includeWorkInProgressEffects +) { + includeWorkInProgressEffects = + includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + commitHookLayoutEffects(finishedWork, 4); + break; + case 1: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + var instance = finishedWork.stateNode; + if ("function" === typeof instance.componentDidMount) + try { + instance.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + finishedRoot = finishedWork.updateQueue; + if (null !== finishedRoot) { + var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks; + if (null !== hiddenCallbacks) + for ( + finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; + finishedRoot < hiddenCallbacks.length; + finishedRoot++ + ) + callCallback(hiddenCallbacks[finishedRoot], instance); + } + includeWorkInProgressEffects && + flags & 64 && + commitClassCallbacks(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 26: + case 27: + case 5: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 12: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 13: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 22: + null === finishedWork.memoizedState && + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + default: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); } - entangledRenderLanes = lanes; - finishQueueingConcurrentUpdates(); - return timeoutHandle; -} -function handleThrow(root, thrownValue) { - currentlyRenderingFiber$1 = null; - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - ReactCurrentOwner.current = null; - thrownValue === SuspenseException - ? ((thrownValue = getSuspendedThenable()), - (root = suspenseHandlerStackCursor.current), - (workInProgressSuspendedReason = - (null !== root && - ((workInProgressRootRenderLanes & 4194176) === - workInProgressRootRenderLanes - ? null !== shellBoundary - : ((workInProgressRootRenderLanes & 62914560) !== - workInProgressRootRenderLanes && - 0 === (workInProgressRootRenderLanes & 536870912)) || - root !== shellBoundary)) || - 0 !== (workInProgressRootSkippedLanes & 134217727) || - 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) - ? 3 - : 2)) - : thrownValue === SuspenseyCommitException - ? ((thrownValue = getSuspendedThenable()), - (workInProgressSuspendedReason = 4)) - : (workInProgressSuspendedReason = - thrownValue === SelectiveHydrationException - ? 8 - : null !== thrownValue && - "object" === typeof thrownValue && - "function" === typeof thrownValue.then - ? 6 - : 1); - workInProgressThrownValue = thrownValue; - null === workInProgress && - ((workInProgressRootExitStatus = 1), - (workInProgressRootFatalError = thrownValue)); + parentFiber = parentFiber.sibling; + } } -function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +function commitHookPassiveMountEffects(finishedWork, hookFlags) { + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } } -function renderDidSuspendDelayIfPossible() { - workInProgressRootExitStatus = 4; - (0 === (workInProgressRootSkippedLanes & 134217727) && - 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || - null === workInProgressRoot || - markRootSuspended( - workInProgressRoot, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); +function recursivelyTraversePassiveMountEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveMountOnFiber(root, parentFiber), + (parentFiber = parentFiber.sibling); } -function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) - (workInProgressTransitions = null), prepareFreshStack(root, lanes); - lanes = !1; - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - var unitOfWork = workInProgress, - thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - case 3: - case 2: - lanes || - null !== suspenseHandlerStackCursor.current || - (lanes = !0); - default: - (workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, unitOfWork, thrownValue); - } - } - workLoopSync(); +function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); break; - } catch (thrownValue$95) { - handleThrow(root, thrownValue$95); - } - while (1); - lanes && root.shellSuspendCounter++; - resetContextDependencies(); - executionContext = prevExecutionContext; - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - throw Error( - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; -} -function workLoopSync() { - for (; null !== workInProgress; ) performUnitOfWork(workInProgress); -} -function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) - (workInProgressTransitions = null), - (workInProgressRootRenderTargetTime = now() + 500), - prepareFreshStack(root, lanes); - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - lanes = workInProgress; - var thrownValue = workInProgressThrownValue; - b: switch (workInProgressSuspendedReason) { - case 1: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 2: - if (isThenableResolved(thrownValue)) { - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(lanes); - break; - } - lanes = function () { - 2 === workInProgressSuspendedReason && - workInProgressRoot === root && - (workInProgressSuspendedReason = 7); - ensureRootIsScheduled(root); - }; - thrownValue.then(lanes, lanes); - break a; - case 3: - workInProgressSuspendedReason = 7; - break a; - case 4: - workInProgressSuspendedReason = 5; - break a; - case 7: - isThenableResolved(thrownValue) - ? ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - replaySuspendedUnitOfWork(lanes)) - : ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, lanes, thrownValue)); - break; - case 5: - switch (workInProgress.tag) { - case 5: - case 26: - case 27: - lanes = workInProgress; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - var sibling = lanes.sibling; - if (null !== sibling) workInProgress = sibling; - else { - var returnFiber = lanes.return; - null !== returnFiber - ? ((workInProgress = returnFiber), - completeUnitOfWork(returnFiber)) - : (workInProgress = null); - } - break b; - } - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 6: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, thrownValue); - break; - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - default: - throw Error("Unexpected SuspendedReason. This is a bug in React."); - } - } - workLoopConcurrent(); + case 3: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + case 23: + break; + case 22: + flags = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : finishedWork.mode & 1 || + ((flags._visibility |= 4), + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) + : flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : ((flags._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); break; - } catch (thrownValue$97) { - handleThrow(root, thrownValue$97); + default: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + } +} +function recursivelyTraverseReconnectPassiveEffects( + finishedRoot$jscomp$0, + parentFiber +) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + commitHookPassiveMountEffects(finishedWork, 8); + break; + case 23: + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? instance._visibility & 4 + ? recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + ) + : finishedWork.mode & 1 || + ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )) + : ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); } - while (1); - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - executionContext = prevExecutionContext; - if (null !== workInProgress) return 0; - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; + parentFiber = parentFiber.sibling; + } } -function workLoopConcurrent() { - for (; null !== workInProgress && !shouldYield(); ) - performUnitOfWork(workInProgress); +var suspenseyCommitFlag = 8192; +function recursivelyAccumulateSuspenseyCommit(parentFiber) { + if (parentFiber.subtreeFlags & suspenseyCommitFlag) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + accumulateSuspenseyCommitOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); } -function performUnitOfWork(unitOfWork) { - var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next); - ReactCurrentOwner.current = null; +function accumulateSuspenseyCommitOnFiber(fiber) { + switch (fiber.tag) { + case 26: + recursivelyAccumulateSuspenseyCommit(fiber); + if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) + throw Error( + "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." + ); + break; + case 5: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 3: + case 4: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 22: + if (null === fiber.memoizedState) { + var current = fiber.alternate; + null !== current && null !== current.memoizedState + ? ((current = suspenseyCommitFlag), + (suspenseyCommitFlag = 16777216), + recursivelyAccumulateSuspenseyCommit(fiber), + (suspenseyCommitFlag = current)) + : recursivelyAccumulateSuspenseyCommit(fiber); + } + break; + default: + recursivelyAccumulateSuspenseyCommit(fiber); + } } -function replaySuspendedUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate; - switch (unitOfWork.tag) { - case 2: - unitOfWork.tag = 0; - case 15: +function detachAlternateSiblings(parentFiber) { + var previousFiber = parentFiber.alternate; + if ( + null !== previousFiber && + ((parentFiber = previousFiber.child), null !== parentFiber) + ) { + previousFiber.child = null; + do + (previousFiber = parentFiber.sibling), + (parentFiber.sibling = null), + (parentFiber = previousFiber); + while (null !== parentFiber); + } +} +function recursivelyTraversePassiveUnmountEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); + } + detachAlternateSiblings(parentFiber); + } + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveUnmountOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); +} +function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { case 0: - var Component = unitOfWork.type, - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(unitOfWork, context); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - context, - workInProgressRootRenderLanes - ); - break; case 11: - Component = unitOfWork.type.render; - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - unitOfWork.ref, - workInProgressRootRenderLanes - ); + case 15: + recursivelyTraversePassiveUnmountEffects(finishedWork); + finishedWork.flags & 2048 && + commitHookEffectListUnmount(9, finishedWork, finishedWork.return); + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState && + instance._visibility & 4 && + (null === finishedWork.return || 13 !== finishedWork.return.tag) + ? ((instance._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(finishedWork)) + : recursivelyTraversePassiveUnmountEffects(finishedWork); break; - case 5: - resetHooksOnUnwind(unitOfWork); default: - unwindInterruptedWork(current, unitOfWork), - (unitOfWork = workInProgress = - resetWorkInProgress(unitOfWork, entangledRenderLanes)), - (current = beginWork(current, unitOfWork, entangledRenderLanes)); + recursivelyTraversePassiveUnmountEffects(finishedWork); } - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; } -function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { - resetContextDependencies(); - resetHooksOnUnwind(unitOfWork); - thenableState$1 = null; - thenableIndexCounter$1 = 0; - var returnFiber = unitOfWork.return; - try { - if ( - throwException( - root, - returnFiber, - unitOfWork, - thrownValue, - workInProgressRootRenderLanes - ) - ) { - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; +function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); + } + detachAlternateSiblings(parentFiber); + } + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + deletions = parentFiber; + switch (deletions.tag) { + case 0: + case 11: + case 15: + commitHookEffectListUnmount(8, deletions, deletions.return); + recursivelyTraverseDisconnectPassiveEffects(deletions); + break; + case 22: + i = deletions.stateNode; + i._visibility & 4 && + ((i._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(deletions)); + break; + default: + recursivelyTraverseDisconnectPassiveEffects(deletions); + } + parentFiber = parentFiber.sibling; + } +} +function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + deletedSubtreeRoot, + nearestMountedAncestor +) { + for (; null !== nextEffect; ) { + var fiber = nextEffect; + switch (fiber.tag) { + case 0: + case 11: + case 15: + commitHookEffectListUnmount(8, fiber, nearestMountedAncestor); } - } catch (error) { - if (null !== returnFiber) throw ((workInProgress = returnFiber), error); - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - if (unitOfWork.flags & 32768) - a: { - root = unitOfWork; - do { - unitOfWork = unwindWork(root.alternate, root); - if (null !== unitOfWork) { - unitOfWork.flags &= 32767; - workInProgress = unitOfWork; + var child = fiber.child; + if (null !== child) (child.return = fiber), (nextEffect = child); + else + a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { + child = nextEffect; + var sibling = child.sibling, + returnFiber = child.return; + detachFiberAfterEffects(child); + if (child === fiber) { + nextEffect = null; break a; } - root = root.return; - null !== root && - ((root.flags |= 32768), - (root.subtreeFlags = 0), - (root.deletions = null)); - workInProgress = root; - } while (null !== root); - workInProgressRootExitStatus = 6; - workInProgress = null; - } - else completeUnitOfWork(unitOfWork); + if (null !== sibling) { + sibling.return = returnFiber; + nextEffect = sibling; + break a; + } + nextEffect = returnFiber; + } + } } -function completeUnitOfWork(unitOfWork) { - var completedWork = unitOfWork; - do { - unitOfWork = completedWork.return; - var next = completeWork( - completedWork.alternate, - completedWork, - entangledRenderLanes +var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, + executionContext = 0, + workInProgressRoot = null, + workInProgress = null, + workInProgressRootRenderLanes = 0, + workInProgressSuspendedReason = 0, + workInProgressThrownValue = null, + workInProgressRootDidAttachPingListener = !1, + entangledRenderLanes = 0, + workInProgressRootExitStatus = 0, + workInProgressRootFatalError = null, + workInProgressRootSkippedLanes = 0, + workInProgressRootInterleavedUpdatedLanes = 0, + workInProgressRootPingedLanes = 0, + workInProgressDeferredLane = 0, + workInProgressRootConcurrentErrors = null, + workInProgressRootRecoverableErrors = null, + workInProgressRootDidIncludeRecursiveRenderUpdate = !1, + globalMostRecentFallbackTime = 0, + workInProgressRootRenderTargetTime = Infinity, + workInProgressTransitions = null, + hasUncaughtError = !1, + firstUncaughtError = null, + legacyErrorBoundariesThatAlreadyFailed = null, + rootDoesHavePassiveEffects = !1, + rootWithPendingPassiveEffects = null, + pendingPassiveEffectsLanes = 0, + nestedUpdateCount = 0, + rootWithNestedUpdates = null; +function requestUpdateLane(fiber) { + if (0 === (fiber.mode & 1)) return 2; + if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) + return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; + fiber = ReactCurrentBatchConfig$1.transition; + null !== fiber && fiber._callbacks.add(handleAsyncAction); + if (null !== fiber) + return ( + 0 === currentEventTransitionLane && + (currentEventTransitionLane = claimNextTransitionLane()), + currentEventTransitionLane ); - if (null !== next) { - workInProgress = next; - return; - } - completedWork = completedWork.sibling; - if (null !== completedWork) { - workInProgress = completedWork; - return; - } - workInProgress = completedWork = unitOfWork; - } while (null !== completedWork); - 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); + fiber = currentUpdatePriority; + return 0 !== fiber ? fiber : 32; +} +function requestDeferredLane() { + 0 === workInProgressDeferredLane && + (workInProgressDeferredLane = + 0 !== (workInProgressRootRenderLanes & 536870912) + ? 536870912 + : claimNextTransitionLane()); + var suspenseHandler = suspenseHandlerStackCursor.current; + null !== suspenseHandler && (suspenseHandler.flags |= 32); + return workInProgressDeferredLane; +} +function scheduleUpdateOnFiber(root, fiber, lane) { + if ( + (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || + null !== root.cancelPendingCommit + ) + prepareFreshStack(root, 0), + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane + ); + markRootUpdated$1(root, lane); + if (0 === (executionContext & 2) || root !== workInProgressRoot) + root === workInProgressRoot && + (0 === (executionContext & 2) && + (workInProgressRootInterleavedUpdatedLanes |= lane), + 4 === workInProgressRootExitStatus && + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane + )), + ensureRootIsScheduled(root), + 2 === lane && + 0 === executionContext && + 0 === (fiber.mode & 1) && + ((workInProgressRootRenderTargetTime = now() + 500), + flushSyncWorkAcrossRoots_impl(!0)); +} +function performConcurrentWorkOnRoot(root, didTimeout) { + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + var originalCallbackNode = root.callbackNode; + if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) + return null; + var lanes = getNextLanes( + root, + root === workInProgressRoot ? workInProgressRootRenderLanes : 0 + ); + if (0 === lanes) return null; + var exitStatus = (didTimeout = + 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) + ? renderRootConcurrent(root, lanes) + : renderRootSync(root, lanes); + if (0 !== exitStatus) { + var renderWasConcurrent = didTimeout; + do { + if (6 === exitStatus) markRootSuspended(root, lanes, 0); + else { + didTimeout = root.current.alternate; + if ( + renderWasConcurrent && + !isRenderConsistentWithExternalStores(didTimeout) + ) { + exitStatus = renderRootSync(root, lanes); + renderWasConcurrent = !1; + continue; + } + if (2 === exitStatus) { + renderWasConcurrent = lanes; + var errorRetryLanes = getLanesToRetrySynchronouslyOnError( + root, + renderWasConcurrent + ); + 0 !== errorRetryLanes && + ((lanes = errorRetryLanes), + (exitStatus = recoverFromConcurrentError( + root, + renderWasConcurrent, + errorRetryLanes + ))); + } + if (1 === exitStatus) + throw ( + ((originalCallbackNode = workInProgressRootFatalError), + prepareFreshStack(root, 0), + markRootSuspended(root, lanes, 0), + ensureRootIsScheduled(root), + originalCallbackNode) + ); + root.finishedWork = didTimeout; + root.finishedLanes = lanes; + a: { + renderWasConcurrent = root; + switch (exitStatus) { + case 0: + case 1: + throw Error("Root did not complete. This is a bug in React."); + case 4: + if ((lanes & 4194176) === lanes) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + break a; + } + break; + case 2: + case 3: + case 5: + break; + default: + throw Error("Unknown root exit status."); + } + if ( + (lanes & 62914560) === lanes && + 3 === exitStatus && + ((exitStatus = globalMostRecentFallbackTime + 300 - now()), + 10 < exitStatus) + ) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; + renderWasConcurrent.timeoutHandle = scheduleTimeout( + commitRootWhenReady.bind( + null, + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ), + exitStatus + ); + break a; + } + commitRootWhenReady( + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ); + } + } + break; + } while (1); + } + ensureRootIsScheduled(root); + scheduleTaskForRootDuringMicrotask(root, now()); + root = + root.callbackNode === originalCallbackNode + ? performConcurrentWorkOnRoot.bind(null, root) + : null; + return root; } -function commitRoot(root, recoverableErrors, transitions, spawnedLane) { - var previousUpdateLanePriority = currentUpdatePriority, - prevTransition = ReactCurrentBatchConfig.transition; - try { - (ReactCurrentBatchConfig.transition = null), - (currentUpdatePriority = 2), - commitRootImpl( - root, - recoverableErrors, - transitions, - previousUpdateLanePriority, - spawnedLane +function recoverFromConcurrentError( + root, + originallyAttemptedLanes, + errorRetryLanes +) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, + JSCompiler_inline_result; + (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && + (prepareFreshStack(root, errorRetryLanes).flags |= 256); + errorRetryLanes = renderRootSync(root, errorRetryLanes); + if (2 !== errorRetryLanes) { + if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) + return ( + (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), + (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), + 4 ); - } finally { - (ReactCurrentBatchConfig.transition = prevTransition), - (currentUpdatePriority = previousUpdateLanePriority); + root = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + null !== root && queueRecoverableErrors(root); } - return null; + return errorRetryLanes; } -function commitRootImpl( +function queueRecoverableErrors(errors) { + null === workInProgressRootRecoverableErrors + ? (workInProgressRootRecoverableErrors = errors) + : workInProgressRootRecoverableErrors.push.apply( + workInProgressRootRecoverableErrors, + errors + ); +} +function commitRootWhenReady( root, + finishedWork, recoverableErrors, transitions, - renderPriorityLevel, + didIncludeRenderPhaseUpdate, + lanes, spawnedLane ) { - do flushPassiveEffects(); - while (null !== rootWithPendingPassiveEffects); - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var finishedWork = root.finishedWork; - transitions = root.finishedLanes; - if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedLanes = 0; - if (finishedWork === root.current) - throw Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ); - root.callbackNode = null; - root.callbackPriority = 0; - root.cancelPendingCommit = null; - var remainingLanes = finishedWork.lanes | finishedWork.childLanes; - remainingLanes |= concurrentlyUpdatedLanes; - markRootFinished(root, remainingLanes, spawnedLane); - root === workInProgressRoot && - ((workInProgress = workInProgressRoot = null), - (workInProgressRootRenderLanes = 0)); - (0 === (finishedWork.subtreeFlags & 10256) && - 0 === (finishedWork.flags & 10256)) || - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); - spawnedLane = 0 !== (finishedWork.flags & 15990); - if (0 !== (finishedWork.subtreeFlags & 15990) || spawnedLane) { - spawnedLane = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = null; - remainingLanes = currentUpdatePriority; - currentUpdatePriority = 2; - var prevExecutionContext = executionContext; - executionContext |= 4; - ReactCurrentOwner.current = null; - commitBeforeMutationEffects(root, finishedWork); - commitMutationEffectsOnFiber(finishedWork, root); - root.current = finishedWork; - commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); - requestPaint(); - executionContext = prevExecutionContext; - currentUpdatePriority = remainingLanes; - ReactCurrentBatchConfig.transition = spawnedLane; - } else root.current = finishedWork; - rootDoesHavePassiveEffects && - ((rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsLanes = transitions)); - remainingLanes = root.pendingLanes; - 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - ensureRootIsScheduled(root); - if (null !== recoverableErrors) - for ( - renderPriorityLevel = root.onRecoverableError, finishedWork = 0; - finishedWork < recoverableErrors.length; - finishedWork++ - ) - (spawnedLane = recoverableErrors[finishedWork]), - (remainingLanes = { - digest: spawnedLane.digest, - componentStack: spawnedLane.stack - }), - renderPriorityLevel(spawnedLane.value, remainingLanes); - if (hasUncaughtError) - throw ( - ((hasUncaughtError = !1), - (root = firstUncaughtError), - (firstUncaughtError = null), - root) - ); - 0 !== (pendingPassiveEffectsLanes & 3) && - 0 !== root.tag && - flushPassiveEffects(); - remainingLanes = root.pendingLanes; - 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) - ? root === rootWithNestedUpdates - ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) - : (nestedUpdateCount = 0); - flushSyncWorkAcrossRoots_impl(!1); - return null; + 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); } -function flushPassiveEffects() { - if (null !== rootWithPendingPassiveEffects) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), - prevTransition = ReactCurrentBatchConfig.transition, - previousPriority = currentUpdatePriority; - try { - ReactCurrentBatchConfig.transition = null; - currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; - if (null === rootWithPendingPassiveEffects) - var JSCompiler_inline_result = !1; - else { - renderPriority = rootWithPendingPassiveEffects; - rootWithPendingPassiveEffects = null; - pendingPassiveEffectsLanes = 0; - if (0 !== (executionContext & 6)) - throw Error("Cannot flush passive effects while already rendering."); - var prevExecutionContext = executionContext; - executionContext |= 4; - commitPassiveUnmountOnFiber(renderPriority.current); - commitPassiveMountOnFiber(renderPriority, renderPriority.current); - executionContext = prevExecutionContext; - flushSyncWorkAcrossRoots_impl(!1); - if ( - injectedHook && - "function" === typeof injectedHook.onPostCommitFiberRoot - ) +function isRenderConsistentWithExternalStores(finishedWork) { + for (var node = finishedWork; ; ) { + if (node.flags & 16384) { + var updateQueue = node.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.stores), null !== updateQueue) + ) + for (var i = 0; i < updateQueue.length; i++) { + var check = updateQueue[i], + getSnapshot = check.getSnapshot; + check = check.value; try { - injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); - } catch (err) {} - JSCompiler_inline_result = !0; + if (!objectIs(getSnapshot(), check)) return !1; + } catch (error) { + return !1; + } + } + } + updateQueue = node.child; + if (node.subtreeFlags & 16384 && null !== updateQueue) + (updateQueue.return = node), (node = updateQueue); + else { + if (node === finishedWork) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return !0; + node = node.return; } - return JSCompiler_inline_result; - } finally { - (currentUpdatePriority = previousPriority), - (ReactCurrentBatchConfig.transition = prevTransition); + node.sibling.return = node.return; + node = node.sibling; } } - return !1; -} -function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); - rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); - null !== rootFiber && - (markRootUpdated(rootFiber, 2), ensureRootIsScheduled(rootFiber)); + return !0; } -function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { - if (3 === sourceFiber.tag) - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); - else - for (; null !== nearestMountedAncestor; ) { - if (3 === nearestMountedAncestor.tag) { - captureCommitPhaseErrorOnRoot( - nearestMountedAncestor, - sourceFiber, - error - ); - break; - } else if (1 === nearestMountedAncestor.tag) { - var instance = nearestMountedAncestor.stateNode; - if ( - "function" === - typeof nearestMountedAncestor.type.getDerivedStateFromError || - ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) - ) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createClassErrorUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - nearestMountedAncestor = enqueueUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - null !== nearestMountedAncestor && - (markRootUpdated(nearestMountedAncestor, 2), - ensureRootIsScheduled(nearestMountedAncestor)); - break; - } - } - nearestMountedAncestor = nearestMountedAncestor.return; - } +function markRootSuspended(root, suspendedLanes, spawnedLane) { + suspendedLanes &= ~workInProgressRootPingedLanes; + suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; + for ( + var expirationTimes = root.expirationTimes, lanes = suspendedLanes; + 0 < lanes; + + ) { + var index$6 = 31 - clz32(lanes), + lane = 1 << index$6; + expirationTimes[index$6] = -1; + lanes &= ~lane; + } + 0 !== spawnedLane && + markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); } -function attachPingListener(root, wakeable, lanes) { - var pingCache = root.pingCache; - if (null === pingCache) { - pingCache = root.pingCache = new PossiblyWeakMap(); - var threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else - (threadIDs = pingCache.get(wakeable)), - void 0 === threadIDs && - ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); - threadIDs.has(lanes) || - ((workInProgressRootDidAttachPingListener = !0), - threadIDs.add(lanes), - (root = pingSuspendedRoot.bind(null, root, wakeable, lanes)), - wakeable.then(root, root)); +function resetWorkInProgressStack() { + if (null !== workInProgress) { + if (0 === workInProgressSuspendedReason) + var interruptedWork = workInProgress.return; + else + (interruptedWork = workInProgress), + resetContextDependencies(), + resetHooksOnUnwind(interruptedWork), + (thenableState$1 = null), + (thenableIndexCounter$1 = 0), + (interruptedWork = workInProgress); + for (; null !== interruptedWork; ) + unwindInterruptedWork(interruptedWork.alternate, interruptedWork), + (interruptedWork = interruptedWork.return); + workInProgress = null; + } } -function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(wakeable); - root.pingedLanes |= root.suspendedLanes & pingedLanes; - workInProgressRoot === root && - (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && - (4 === workInProgressRootExitStatus || - (3 === workInProgressRootExitStatus && - (workInProgressRootRenderLanes & 62914560) === - workInProgressRootRenderLanes && - 300 > now() - globalMostRecentFallbackTime) - ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) - : (workInProgressRootPingedLanes |= pingedLanes)); - ensureRootIsScheduled(root); +function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = 0; + var timeoutHandle = root.timeoutHandle; + -1 !== timeoutHandle && + ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); + timeoutHandle = root.cancelPendingCommit; + null !== timeoutHandle && + ((root.cancelPendingCommit = null), timeoutHandle()); + resetWorkInProgressStack(); + workInProgressRoot = root; + workInProgress = timeoutHandle = createWorkInProgress(root.current, null); + workInProgressRootRenderLanes = lanes; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + workInProgressRootDidAttachPingListener = !1; + workInProgressRootExitStatus = 0; + workInProgressRootFatalError = null; + workInProgressDeferredLane = + workInProgressRootPingedLanes = + workInProgressRootInterleavedUpdatedLanes = + workInProgressRootSkippedLanes = + 0; + workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = + null; + workInProgressRootDidIncludeRecursiveRenderUpdate = !1; + 0 !== (lanes & 8) && (lanes |= lanes & 32); + var allEntangledLanes = root.entangledLanes; + if (0 !== allEntangledLanes) + for ( + root = root.entanglements, allEntangledLanes &= lanes; + 0 < allEntangledLanes; + + ) { + var index$4 = 31 - clz32(allEntangledLanes), + lane = 1 << index$4; + lanes |= root[index$4]; + allEntangledLanes &= ~lane; + } + entangledRenderLanes = lanes; + finishQueueingConcurrentUpdates(); + return timeoutHandle; } -function retryTimedOutBoundary(boundaryFiber, retryLane) { - 0 === retryLane && - (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); - boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - null !== boundaryFiber && - (markRootUpdated(boundaryFiber, retryLane), - ensureRootIsScheduled(boundaryFiber)); +function handleThrow(root, thrownValue) { + currentlyRenderingFiber$1 = null; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentOwner.current = null; + thrownValue === SuspenseException + ? ((thrownValue = getSuspendedThenable()), + (root = suspenseHandlerStackCursor.current), + (workInProgressSuspendedReason = + (null !== root && + ((workInProgressRootRenderLanes & 4194176) === + workInProgressRootRenderLanes + ? null !== shellBoundary + : ((workInProgressRootRenderLanes & 62914560) !== + workInProgressRootRenderLanes && + 0 === (workInProgressRootRenderLanes & 536870912)) || + root !== shellBoundary)) || + 0 !== (workInProgressRootSkippedLanes & 134217727) || + 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) + ? 3 + : 2)) + : thrownValue === SuspenseyCommitException + ? ((thrownValue = getSuspendedThenable()), + (workInProgressSuspendedReason = 4)) + : (workInProgressSuspendedReason = + thrownValue === SelectiveHydrationException + ? 8 + : null !== thrownValue && + "object" === typeof thrownValue && + "function" === typeof thrownValue.then + ? 6 + : 1); + workInProgressThrownValue = thrownValue; + null === workInProgress && + ((workInProgressRootExitStatus = 1), + (workInProgressRootFatalError = thrownValue)); } -function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState, - retryLane = 0; - null !== suspenseState && (retryLane = suspenseState.retryLane); - retryTimedOutBoundary(boundaryFiber, retryLane); +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } -function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = 0; - switch (boundaryFiber.tag) { - case 13: - var retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - null !== suspenseState && (retryLane = suspenseState.retryLane); - break; - case 19: - retryCache = boundaryFiber.stateNode; - break; - case 22: - retryCache = boundaryFiber.stateNode._retryCache; - break; - default: - throw Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ); - } - null !== retryCache && retryCache.delete(wakeable); - retryTimedOutBoundary(boundaryFiber, retryLane); +function renderDidSuspendDelayIfPossible() { + workInProgressRootExitStatus = 4; + (0 === (workInProgressRootSkippedLanes & 134217727) && + 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || + null === workInProgressRoot || + markRootSuspended( + workInProgressRoot, + workInProgressRootRenderLanes, + workInProgressDeferredLane + ); } -var beginWork; -beginWork = function (current, workInProgress, renderLanes) { - if (null !== current) - if ( - current.memoizedProps !== workInProgress.pendingProps || - didPerformWorkStackCursor.current - ) - didReceiveUpdate = !0; - else { - if ( - 0 === (current.lanes & renderLanes) && - 0 === (workInProgress.flags & 128) - ) - return ( - (didReceiveUpdate = !1), - attemptEarlyBailoutIfNoScheduledUpdate( - current, - workInProgress, - renderLanes - ) - ); - didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; - } - else didReceiveUpdate = !1; - workInProgress.lanes = 0; - switch (workInProgress.tag) { - case 2: - var Component = workInProgress.type; - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - var context = getMaskedContext( - workInProgress, - contextStackCursor$1.current - ); - prepareToReadContext(workInProgress, renderLanes); - context = renderWithHooks( - null, - workInProgress, - Component, - current, - context, - renderLanes - ); - workInProgress.flags |= 1; - if ( - "object" === typeof context && - null !== context && - "function" === typeof context.render && - void 0 === context.$$typeof - ) { - workInProgress.tag = 1; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; - workInProgress.memoizedState = - null !== context.state && void 0 !== context.state - ? context.state - : null; - initializeUpdateQueue(workInProgress); - context.updater = classComponentUpdater; - workInProgress.stateNode = context; - context._reactInternals = workInProgress; - mountClassInstance(workInProgress, Component, current, renderLanes); - workInProgress = finishClassComponent( - null, - workInProgress, - Component, - !0, - hasContext, - renderLanes - ); - } else - (workInProgress.tag = 0), - reconcileChildren(null, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child); - return workInProgress; - case 16: - Component = workInProgress.elementType; - a: { - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - context = Component._init; - Component = context(Component._payload); - workInProgress.type = Component; - context = workInProgress.tag = resolveLazyComponentTag(Component); - current = resolveDefaultProps(Component, current); - switch (context) { - case 0: - workInProgress = updateFunctionComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); +function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) + (workInProgressTransitions = null), prepareFreshStack(root, lanes); + lanes = !1; + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + var unitOfWork = workInProgress, + thrownValue = workInProgressThrownValue; + switch (workInProgressSuspendedReason) { + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; break a; + case 3: + case 2: + lanes || + null !== suspenseHandlerStackCursor.current || + (lanes = !0); + default: + (workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, unitOfWork, thrownValue); + } + } + workLoopSync(); + break; + } catch (thrownValue$94) { + handleThrow(root, thrownValue$94); + } + while (1); + lanes && root.shellSuspendCounter++; + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopSync() { + for (; null !== workInProgress; ) performUnitOfWork(workInProgress); +} +function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) + (workInProgressTransitions = null), + (workInProgressRootRenderTargetTime = now() + 500), + prepareFreshStack(root, lanes); + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + lanes = workInProgress; + var thrownValue = workInProgressThrownValue; + b: switch (workInProgressSuspendedReason) { case 1: - workInProgress = updateClassComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 2: + if (isThenableResolved(thrownValue)) { + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + replaySuspendedUnitOfWork(lanes); + break; + } + lanes = function () { + 2 === workInProgressSuspendedReason && + workInProgressRoot === root && + (workInProgressSuspendedReason = 7); + ensureRootIsScheduled(root); + }; + thrownValue.then(lanes, lanes); break a; - case 11: - workInProgress = updateForwardRef( - null, - workInProgress, - Component, - current, - renderLanes - ); + case 3: + workInProgressSuspendedReason = 7; break a; - case 14: - workInProgress = updateMemoComponent( - null, - workInProgress, - Component, - resolveDefaultProps(Component.type, current), - renderLanes - ); + case 4: + workInProgressSuspendedReason = 5; + break a; + case 7: + isThenableResolved(thrownValue) + ? ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + replaySuspendedUnitOfWork(lanes)) + : ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, lanes, thrownValue)); + break; + case 5: + switch (workInProgress.tag) { + case 5: + case 26: + case 27: + lanes = workInProgress; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + var sibling = lanes.sibling; + if (null !== sibling) workInProgress = sibling; + else { + var returnFiber = lanes.return; + null !== returnFiber + ? ((workInProgress = returnFiber), + completeUnitOfWork(returnFiber)) + : (workInProgress = null); + } + break b; + } + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 6: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, thrownValue); + break; + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; break a; + default: + throw Error("Unexpected SuspendedReason. This is a bug in React."); } - throw Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." - ); } - return workInProgress; + workLoopConcurrent(); + break; + } catch (thrownValue$96) { + handleThrow(root, thrownValue$96); + } + while (1); + resetContextDependencies(); + ReactCurrentDispatcher.current = prevDispatcher; + executionContext = prevExecutionContext; + if (null !== workInProgress) return 0; + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; +} +function workLoopConcurrent() { + for (; null !== workInProgress && !shouldYield(); ) + performUnitOfWork(workInProgress); +} +function performUnitOfWork(unitOfWork) { + var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next); + ReactCurrentOwner.current = null; +} +function replaySuspendedUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate; + switch (unitOfWork.tag) { + case 2: + unitOfWork.tag = 0; + case 15: case 0: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateFunctionComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 1: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateClassComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 3: - pushHostRootContext(workInProgress); - if (null === current) - throw Error("Should have a current fiber. This is a bug in React."); - context = workInProgress.pendingProps; - Component = workInProgress.memoizedState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, context, null, renderLanes); - context = workInProgress.memoizedState.element; - context === Component - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - )) - : (reconcileChildren(current, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child)); - return workInProgress; - case 26: - case 27: - case 5: - return ( - pushHostContext(workInProgress), - (Component = workInProgress.pendingProps.children), - markRef$1(current, workInProgress), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 6: - return null; - case 13: - return updateSuspenseComponent(current, workInProgress, renderLanes); - case 4: - return ( - pushHostContainer( - workInProgress, - workInProgress.stateNode.containerInfo - ), - (Component = workInProgress.pendingProps), - null === current - ? (workInProgress.child = reconcileChildFibers( - workInProgress, - null, - Component, - renderLanes - )) - : reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 11: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateForwardRef( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 7: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps, - renderLanes - ), - workInProgress.child + var Component = unitOfWork.type, + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + void 0, + workInProgressRootRenderLanes ); - case 8: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child + break; + case 11: + Component = unitOfWork.type.render; + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + unitOfWork.ref, + workInProgressRootRenderLanes ); - case 12: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child + break; + case 5: + resetHooksOnUnwind(unitOfWork); + default: + unwindInterruptedWork(current, unitOfWork), + (unitOfWork = workInProgress = + resetWorkInProgress(unitOfWork, entangledRenderLanes)), + (current = beginWork(current, unitOfWork, entangledRenderLanes)); + } + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; +} +function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { + resetContextDependencies(); + resetHooksOnUnwind(unitOfWork); + thenableState$1 = null; + thenableIndexCounter$1 = 0; + var returnFiber = unitOfWork.return; + try { + if ( + throwException( + root, + returnFiber, + unitOfWork, + thrownValue, + workInProgressRootRenderLanes + ) + ) { + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + } catch (error) { + if (null !== returnFiber) throw ((workInProgress = returnFiber), error); + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (unitOfWork.flags & 32768) + a: { + root = unitOfWork; + do { + unitOfWork = unwindWork(root.alternate, root); + if (null !== unitOfWork) { + unitOfWork.flags &= 32767; + workInProgress = unitOfWork; + break a; + } + root = root.return; + null !== root && + ((root.flags |= 32768), + (root.subtreeFlags = 0), + (root.deletions = null)); + workInProgress = root; + } while (null !== root); + workInProgressRootExitStatus = 6; + workInProgress = null; + } + else completeUnitOfWork(unitOfWork); +} +function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + unitOfWork = completedWork.return; + var next = completeWork( + completedWork.alternate, + completedWork, + entangledRenderLanes + ); + if (null !== next) { + workInProgress = next; + return; + } + completedWork = completedWork.sibling; + if (null !== completedWork) { + workInProgress = completedWork; + return; + } + workInProgress = completedWork = unitOfWork; + } while (null !== completedWork); + 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +} +function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane +) { + var previousUpdateLanePriority = currentUpdatePriority, + prevTransition = ReactCurrentBatchConfig.transition; + try { + (ReactCurrentBatchConfig.transition = null), + (currentUpdatePriority = 2), + commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + previousUpdateLanePriority, + spawnedLane ); - case 10: - a: { - Component = workInProgress.type._context; - context = workInProgress.pendingProps; - hasContext = workInProgress.memoizedProps; - var newValue = context.value; - push(valueCursor, Component._currentValue); - Component._currentValue = newValue; - if (null !== hasContext) - if (objectIs(hasContext.value, newValue)) { - if ( - hasContext.children === context.children && - !didPerformWorkStackCursor.current - ) { - workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - ); - break a; - } - } else - for ( - hasContext = workInProgress.child, - null !== hasContext && (hasContext.return = workInProgress); - null !== hasContext; - - ) { - var list = hasContext.dependencies; - if (null !== list) { - newValue = hasContext.child; - for ( - var dependency = list.firstContext; - null !== dependency; - - ) { - if (dependency.context === Component) { - if (1 === hasContext.tag) { - dependency = createUpdate(renderLanes & -renderLanes); - dependency.tag = 2; - var updateQueue = hasContext.updateQueue; - if (null !== updateQueue) { - updateQueue = updateQueue.shared; - var pending = updateQueue.pending; - null === pending - ? (dependency.next = dependency) - : ((dependency.next = pending.next), - (pending.next = dependency)); - updateQueue.pending = dependency; - } - } - hasContext.lanes |= renderLanes; - dependency = hasContext.alternate; - null !== dependency && (dependency.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - hasContext.return, - renderLanes, - workInProgress - ); - list.lanes |= renderLanes; - break; - } - dependency = dependency.next; - } - } else if (10 === hasContext.tag) - newValue = - hasContext.type === workInProgress.type - ? null - : hasContext.child; - else if (18 === hasContext.tag) { - newValue = hasContext.return; - if (null === newValue) - throw Error( - "We just came from a parent so we must have had a parent. This is a bug in React." - ); - newValue.lanes |= renderLanes; - list = newValue.alternate; - null !== list && (list.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - newValue, - renderLanes, - workInProgress - ); - newValue = hasContext.sibling; - } else newValue = hasContext.child; - if (null !== newValue) newValue.return = hasContext; - else - for (newValue = hasContext; null !== newValue; ) { - if (newValue === workInProgress) { - newValue = null; - break; - } - hasContext = newValue.sibling; - if (null !== hasContext) { - hasContext.return = newValue.return; - newValue = hasContext; - break; - } - newValue = newValue.return; - } - hasContext = newValue; - } - reconcileChildren( - current, - workInProgress, - context.children, - renderLanes + } finally { + (ReactCurrentBatchConfig.transition = prevTransition), + (currentUpdatePriority = previousUpdateLanePriority); + } + return null; +} +function commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + renderPriorityLevel, + spawnedLane +) { + do flushPassiveEffects(); + while (null !== rootWithPendingPassiveEffects); + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + didIncludeRenderPhaseUpdate = root.finishedWork; + transitions = root.finishedLanes; + if (null === didIncludeRenderPhaseUpdate) return null; + root.finishedWork = null; + root.finishedLanes = 0; + if (didIncludeRenderPhaseUpdate === root.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + root.callbackNode = null; + root.callbackPriority = 0; + root.cancelPendingCommit = null; + var remainingLanes = + didIncludeRenderPhaseUpdate.lanes | didIncludeRenderPhaseUpdate.childLanes; + remainingLanes |= concurrentlyUpdatedLanes; + markRootFinished(root, remainingLanes, spawnedLane); + root === workInProgressRoot && + ((workInProgress = workInProgressRoot = null), + (workInProgressRootRenderLanes = 0)); + (0 === (didIncludeRenderPhaseUpdate.subtreeFlags & 10256) && + 0 === (didIncludeRenderPhaseUpdate.flags & 10256)) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); + return null; + })); + spawnedLane = 0 !== (didIncludeRenderPhaseUpdate.flags & 15990); + if (0 !== (didIncludeRenderPhaseUpdate.subtreeFlags & 15990) || spawnedLane) { + spawnedLane = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + remainingLanes = currentUpdatePriority; + currentUpdatePriority = 2; + var prevExecutionContext = executionContext; + executionContext |= 4; + ReactCurrentOwner.current = null; + commitBeforeMutationEffects(root, didIncludeRenderPhaseUpdate); + commitMutationEffectsOnFiber(didIncludeRenderPhaseUpdate, root); + root.current = didIncludeRenderPhaseUpdate; + commitLayoutEffectOnFiber( + root, + didIncludeRenderPhaseUpdate.alternate, + didIncludeRenderPhaseUpdate + ); + requestPaint(); + executionContext = prevExecutionContext; + currentUpdatePriority = remainingLanes; + ReactCurrentBatchConfig.transition = spawnedLane; + } else root.current = didIncludeRenderPhaseUpdate; + rootDoesHavePassiveEffects && + ((rootDoesHavePassiveEffects = !1), + (rootWithPendingPassiveEffects = root), + (pendingPassiveEffectsLanes = transitions)); + remainingLanes = root.pendingLanes; + 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); + onCommitRoot(didIncludeRenderPhaseUpdate.stateNode, renderPriorityLevel); + ensureRootIsScheduled(root); + if (null !== recoverableErrors) + for ( + renderPriorityLevel = root.onRecoverableError, + didIncludeRenderPhaseUpdate = 0; + didIncludeRenderPhaseUpdate < recoverableErrors.length; + didIncludeRenderPhaseUpdate++ + ) + (spawnedLane = recoverableErrors[didIncludeRenderPhaseUpdate]), + (remainingLanes = { + digest: spawnedLane.digest, + componentStack: spawnedLane.stack + }), + renderPriorityLevel(spawnedLane.value, remainingLanes); + if (hasUncaughtError) + throw ( + ((hasUncaughtError = !1), + (root = firstUncaughtError), + (firstUncaughtError = null), + root) + ); + 0 !== (pendingPassiveEffectsLanes & 3) && + 0 !== root.tag && + flushPassiveEffects(); + remainingLanes = root.pendingLanes; + 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) + ? root === rootWithNestedUpdates + ? nestedUpdateCount++ + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : (nestedUpdateCount = 0); + flushSyncWorkAcrossRoots_impl(!1); + return null; +} +function flushPassiveEffects() { + if (null !== rootWithPendingPassiveEffects) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), + prevTransition = ReactCurrentBatchConfig.transition, + previousPriority = currentUpdatePriority; + try { + ReactCurrentBatchConfig.transition = null; + currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; + if (null === rootWithPendingPassiveEffects) + var JSCompiler_inline_result = !1; + else { + renderPriority = rootWithPendingPassiveEffects; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = 0; + if (0 !== (executionContext & 6)) + throw Error("Cannot flush passive effects while already rendering."); + var prevExecutionContext = executionContext; + executionContext |= 4; + commitPassiveUnmountOnFiber(renderPriority.current); + commitPassiveMountOnFiber(renderPriority, renderPriority.current); + executionContext = prevExecutionContext; + flushSyncWorkAcrossRoots_impl(!1); + if ( + injectedHook && + "function" === typeof injectedHook.onPostCommitFiberRoot + ) + try { + injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); + } catch (err) {} + JSCompiler_inline_result = !0; + } + return JSCompiler_inline_result; + } finally { + (currentUpdatePriority = previousPriority), + (ReactCurrentBatchConfig.transition = prevTransition); + } + } + return !1; +} +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); + rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); + null !== rootFiber && + (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +} +function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { + if (3 === sourceFiber.tag) + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + else + for (; null !== nearestMountedAncestor; ) { + if (3 === nearestMountedAncestor.tag) { + captureCommitPhaseErrorOnRoot( + nearestMountedAncestor, + sourceFiber, + error ); - workInProgress = workInProgress.child; + break; + } else if (1 === nearestMountedAncestor.tag) { + var instance = nearestMountedAncestor.stateNode; + if ( + "function" === + typeof nearestMountedAncestor.type.getDerivedStateFromError || + ("function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + ) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createClassErrorUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + nearestMountedAncestor = enqueueUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + null !== nearestMountedAncestor && + (markRootUpdated$1(nearestMountedAncestor, 2), + ensureRootIsScheduled(nearestMountedAncestor)); + break; + } } - return workInProgress; - case 9: - return ( - (context = workInProgress.type), - (Component = workInProgress.pendingProps.children), - prepareToReadContext(workInProgress, renderLanes), - (context = readContext(context)), - (Component = Component(context)), - (workInProgress.flags |= 1), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 14: - return ( - (Component = workInProgress.type), - (context = resolveDefaultProps(Component, workInProgress.pendingProps)), - (context = resolveDefaultProps(Component.type, context)), - updateMemoComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 15: - return updateSimpleMemoComponent( - current, - workInProgress, - workInProgress.type, - workInProgress.pendingProps, - renderLanes - ); - case 17: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), - (workInProgress.tag = 1), - isContextProvider(Component) - ? ((current = !0), pushContextProvider(workInProgress)) - : (current = !1), - prepareToReadContext(workInProgress, renderLanes), - constructClassInstance(workInProgress, Component, context), - mountClassInstance(workInProgress, Component, context, renderLanes), - finishClassComponent( - null, - workInProgress, - Component, - !0, - current, - renderLanes - ) - ); + nearestMountedAncestor = nearestMountedAncestor.return; + } +} +function attachPingListener(root, wakeable, lanes) { + var pingCache = root.pingCache; + if (null === pingCache) { + pingCache = root.pingCache = new PossiblyWeakMap(); + var threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else + (threadIDs = pingCache.get(wakeable)), + void 0 === threadIDs && + ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); + threadIDs.has(lanes) || + ((workInProgressRootDidAttachPingListener = !0), + threadIDs.add(lanes), + (root = pingSuspendedRoot.bind(null, root, wakeable, lanes)), + wakeable.then(root, root)); +} +function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(wakeable); + root.pingedLanes |= root.suspendedLanes & pingedLanes; + workInProgressRoot === root && + (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && + (4 === workInProgressRootExitStatus || + (3 === workInProgressRootExitStatus && + (workInProgressRootRenderLanes & 62914560) === + workInProgressRootRenderLanes && + 300 > now() - globalMostRecentFallbackTime) + ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) + : (workInProgressRootPingedLanes |= pingedLanes)); + ensureRootIsScheduled(root); +} +function retryTimedOutBoundary(boundaryFiber, retryLane) { + 0 === retryLane && + (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); + boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + null !== boundaryFiber && + (markRootUpdated$1(boundaryFiber, retryLane), + ensureRootIsScheduled(boundaryFiber)); +} +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState, + retryLane = 0; + null !== suspenseState && (retryLane = suspenseState.retryLane); + retryTimedOutBoundary(boundaryFiber, retryLane); +} +function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = 0; + switch (boundaryFiber.tag) { + case 13: + var retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + null !== suspenseState && (retryLane = suspenseState.retryLane); + break; case 19: - return updateSuspenseListComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode; + break; case 22: - return updateOffscreenComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode._retryCache; + break; + default: + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -}; + null !== retryCache && retryCache.delete(wakeable); + retryTimedOutBoundary(boundaryFiber, retryLane); +} function scheduleCallback(priorityLevel, callback) { return scheduleCallback$2(priorityLevel, callback); } @@ -9320,6 +9003,7 @@ function createFiberFromTypeAndProps( case REACT_CONTEXT_TYPE: fiberTag = 9; break a; + case REACT_CONSUMER_TYPE: case REACT_FORWARD_REF_TYPE: fiberTag = 11; break a; @@ -9473,63 +9157,19 @@ function findHostInstance(component) { return null === component ? null : getPublicInstance(component.stateNode); } function updateContainer(element, container, parentComponent, callback) { - var current = container.current, - lane = requestUpdateLane(current); - a: if (parentComponent) { - parentComponent = parentComponent._reactInternals; - b: { - if ( - getNearestMountedFiber(parentComponent) !== parentComponent || - 1 !== parentComponent.tag - ) - throw Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); - var JSCompiler_inline_result = parentComponent; - do { - switch (JSCompiler_inline_result.tag) { - case 3: - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode.context; - break b; - case 1: - if (isContextProvider(JSCompiler_inline_result.type)) { - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode - .__reactInternalMemoizedMergedChildContext; - break b; - } - } - JSCompiler_inline_result = JSCompiler_inline_result.return; - } while (null !== JSCompiler_inline_result); - throw Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - if (1 === parentComponent.tag) { - var Component = parentComponent.type; - if (isContextProvider(Component)) { - parentComponent = processChildContext( - parentComponent, - Component, - JSCompiler_inline_result - ); - break a; - } - } - parentComponent = JSCompiler_inline_result; - } else parentComponent = emptyContextObject; + parentComponent = container.current; + var lane = requestUpdateLane(parentComponent); null === container.context - ? (container.context = parentComponent) - : (container.pendingContext = parentComponent); + ? (container.context = emptyContextObject) + : (container.pendingContext = emptyContextObject); container = createUpdate(lane); container.payload = { element: element }; callback = void 0 === callback ? null : callback; null !== callback && (container.callback = callback); - element = enqueueUpdate(current, container, lane); + element = enqueueUpdate(parentComponent, container, lane); null !== element && - (scheduleUpdateOnFiber(element, current, lane), - entangleTransitions(element, current, lane)); + (scheduleUpdateOnFiber(element, parentComponent, lane), + entangleTransitions(element, parentComponent, lane)); return lane; } function emptyFindFiberByHostInstance() { @@ -9584,10 +9224,10 @@ batchedUpdatesImpl = function (fn, a) { } }; var roots = new Map(), - devToolsConfig$jscomp$inline_1114 = { + devToolsConfig$jscomp$inline_1100 = { findFiberByHostInstance: getInstanceFromTag, bundleType: 0, - version: "18.3.0-canary-03d6f7cf0-20240209", + version: "18.3.0-canary-9372c6311-20240315", rendererPackageName: "react-native-renderer", rendererConfig: { getInspectorDataForInstance: getInspectorDataForInstance, @@ -9603,11 +9243,11 @@ var roots = new Map(), }.bind(null, findNodeHandle) } }; -var internals$jscomp$inline_1353 = { - bundleType: devToolsConfig$jscomp$inline_1114.bundleType, - version: devToolsConfig$jscomp$inline_1114.version, - rendererPackageName: devToolsConfig$jscomp$inline_1114.rendererPackageName, - rendererConfig: devToolsConfig$jscomp$inline_1114.rendererConfig, +var internals$jscomp$inline_1342 = { + bundleType: devToolsConfig$jscomp$inline_1100.bundleType, + version: devToolsConfig$jscomp$inline_1100.version, + rendererPackageName: devToolsConfig$jscomp$inline_1100.rendererPackageName, + rendererConfig: devToolsConfig$jscomp$inline_1100.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, @@ -9623,26 +9263,26 @@ var internals$jscomp$inline_1353 = { return null === fiber ? null : fiber.stateNode; }, findFiberByHostInstance: - devToolsConfig$jscomp$inline_1114.findFiberByHostInstance || + devToolsConfig$jscomp$inline_1100.findFiberByHostInstance || emptyFindFiberByHostInstance, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-canary-03d6f7cf0-20240209" + reconcilerVersion: "18.3.0-canary-9372c6311-20240315" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { - var hook$jscomp$inline_1354 = __REACT_DEVTOOLS_GLOBAL_HOOK__; + var hook$jscomp$inline_1343 = __REACT_DEVTOOLS_GLOBAL_HOOK__; if ( - !hook$jscomp$inline_1354.isDisabled && - hook$jscomp$inline_1354.supportsFiber + !hook$jscomp$inline_1343.isDisabled && + hook$jscomp$inline_1343.supportsFiber ) try { - (rendererID = hook$jscomp$inline_1354.inject( - internals$jscomp$inline_1353 + (rendererID = hook$jscomp$inline_1343.inject( + internals$jscomp$inline_1342 )), - (injectedHook = hook$jscomp$inline_1354); + (injectedHook = hook$jscomp$inline_1343); } catch (err) {} } exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = { diff --git a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js index c67b0c4dbd76ee..7e31d29013403a 100644 --- a/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js +++ b/packages/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js @@ -8,7 +8,7 @@ * @nolint * @providesModule ReactNativeRenderer-profiling * @preventMunge - * @generated SignedSource<<5df973db061e36edfd192d75fab51c36>> + * @generated SignedSource<<7ad664bd0b8a14a802c352b7131a3eb2>> */ "use strict"; @@ -19,69 +19,26 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), - Scheduler = require("scheduler"); -function invokeGuardedCallbackImpl(name, func, context) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } -} -var hasError = !1, + Scheduler = require("scheduler"), + isArrayImpl = Array.isArray, + hasError = !1, caughtError = null, - hasRethrowError = !1, - rethrowError = null, - reporter = { - onError: function (error) { - hasError = !0; - caughtError = error; - } - }; -function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = !1; - caughtError = null; - invokeGuardedCallbackImpl.apply(reporter, arguments); -} -function invokeGuardedCallbackAndCatchFirstError( - name, - func, - context, - a, - b, - c, - d, - e, - f -) { - invokeGuardedCallback.apply(this, arguments); - if (hasError) { - if (hasError) { - var error = caughtError; - hasError = !1; - caughtError = null; - } else - throw Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ); - hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); - } -} -var isArrayImpl = Array.isArray, getFiberCurrentPropsFromNode$1 = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { - var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event); + try { + listener(event); + } catch (error) { + hasError || ((hasError = !0), (caughtError = error)); + } event.currentTarget = null; } function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - if (isArrayImpl(dispatchListener)) - throw Error("executeDirectDispatch(...): Invalid `event`."); + if (isArrayImpl(dispatchListener)) throw Error("Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -340,9 +297,7 @@ var instrumentationCallback, }; function accumulate(current, next) { if (null == next) - throw Error( - "accumulate(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); return null == current ? next : isArrayImpl(current) @@ -353,9 +308,7 @@ function accumulate(current, next) { } function accumulateInto(current, next) { if (null == next) - throw Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + throw Error("Accumulated items must not be null or undefined."); if (null == current) return next; if (isArrayImpl(current)) { if (isArrayImpl(next)) return current.push.apply(current, next), current; @@ -944,7 +897,7 @@ eventPluginOrder = Array.prototype.slice.call([ "ReactNativeBridgeEventPlugin" ]); recomputePluginOrdering(); -var injectedNamesToPlugins$jscomp$inline_253 = { +var injectedNamesToPlugins$jscomp$inline_249 = { ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: { eventTypes: {}, @@ -990,32 +943,32 @@ var injectedNamesToPlugins$jscomp$inline_253 = { } } }, - isOrderingDirty$jscomp$inline_254 = !1, - pluginName$jscomp$inline_255; -for (pluginName$jscomp$inline_255 in injectedNamesToPlugins$jscomp$inline_253) + isOrderingDirty$jscomp$inline_250 = !1, + pluginName$jscomp$inline_251; +for (pluginName$jscomp$inline_251 in injectedNamesToPlugins$jscomp$inline_249) if ( - injectedNamesToPlugins$jscomp$inline_253.hasOwnProperty( - pluginName$jscomp$inline_255 + injectedNamesToPlugins$jscomp$inline_249.hasOwnProperty( + pluginName$jscomp$inline_251 ) ) { - var pluginModule$jscomp$inline_256 = - injectedNamesToPlugins$jscomp$inline_253[pluginName$jscomp$inline_255]; + var pluginModule$jscomp$inline_252 = + injectedNamesToPlugins$jscomp$inline_249[pluginName$jscomp$inline_251]; if ( - !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_255) || - namesToPlugins[pluginName$jscomp$inline_255] !== - pluginModule$jscomp$inline_256 + !namesToPlugins.hasOwnProperty(pluginName$jscomp$inline_251) || + namesToPlugins[pluginName$jscomp$inline_251] !== + pluginModule$jscomp$inline_252 ) { - if (namesToPlugins[pluginName$jscomp$inline_255]) + if (namesToPlugins[pluginName$jscomp$inline_251]) throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - (pluginName$jscomp$inline_255 + "`.") + (pluginName$jscomp$inline_251 + "`.") ); - namesToPlugins[pluginName$jscomp$inline_255] = - pluginModule$jscomp$inline_256; - isOrderingDirty$jscomp$inline_254 = !0; + namesToPlugins[pluginName$jscomp$inline_251] = + pluginModule$jscomp$inline_252; + isOrderingDirty$jscomp$inline_250 = !0; } } -isOrderingDirty$jscomp$inline_254 && recomputePluginOrdering(); +isOrderingDirty$jscomp$inline_250 && recomputePluginOrdering(); var instanceCache = new Map(), instanceProps = new Map(); function getInstanceFromTag(tag) { @@ -1091,11 +1044,11 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); - if (hasRethrowError) + if (hasError) throw ( - ((JSCompiler_inline_result = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), + ((JSCompiler_inline_result = caughtError), + (hasError = !1), + (caughtError = null), JSCompiler_inline_result) ); } @@ -1169,6 +1122,7 @@ var ReactSharedInternals = REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), @@ -1189,115 +1143,7 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } -var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); -function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE - ? null - : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if ("object" === typeof type) - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - return (type.displayName || "Context") + ".Consumer"; - case REACT_PROVIDER_TYPE: - return (type._context.displayName || "Context") + ".Provider"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || - ((type = innerType.displayName || innerType.name || ""), - (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); - return type; - case REACT_MEMO_TYPE: - return ( - (innerType = type.displayName || null), - null !== innerType - ? innerType - : getComponentNameFromType(type.type) || "Memo" - ); - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) {} - } - return null; -} -function getComponentNameFromFiber(fiber) { - var type = fiber.type; - switch (fiber.tag) { - case 24: - return "Cache"; - case 9: - return (type.displayName || "Context") + ".Consumer"; - case 10: - return (type._context.displayName || "Context") + ".Provider"; - case 18: - return "DehydratedFragment"; - case 11: - return ( - (fiber = type.render), - (fiber = fiber.displayName || fiber.name || ""), - type.displayName || - ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef") - ); - case 7: - return "Fragment"; - case 26: - case 27: - case 5: - return type; - case 4: - return "Portal"; - case 3: - return "Root"; - case 6: - return "Text"; - case 16: - return getComponentNameFromType(type); - case 8: - return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode"; - case 22: - return "Offscreen"; - case 12: - return "Profiler"; - case 21: - return "Scope"; - case 13: - return "Suspense"; - case 19: - return "SuspenseList"; - case 25: - return "TracingMarker"; - case 1: - case 0: - case 17: - case 2: - case 14: - case 15: - if ("function" === typeof type) - return type.displayName || type.name || null; - if ("string" === typeof type) return type; - } - return null; -} +Symbol.for("react.client.reference"); function getNearestMountedFiber(fiber) { var node = fiber, nearestMounted = fiber; @@ -1887,7 +1733,7 @@ function createLaneMap(initial) { for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial); return laneMap; } -function markRootUpdated(root, updateLane) { +function markRootUpdated$1(root, updateLane) { root.pendingLanes |= updateLane; 268435456 !== updateLane && ((root.suspendedLanes = 0), (root.pingedLanes = 0)); @@ -2028,18 +1874,7 @@ function getPublicInstance(instance) { : instance; } var scheduleTimeout = setTimeout, - cancelTimeout = clearTimeout; -function describeComponentFrame(name, ownerName) { - var sourceInfo = ""; - ownerName && (sourceInfo = " (created by " + ownerName + ")"); - return "\n in " + (name || "Unknown") + sourceInfo; -} -function describeFunctionComponentFrame(fn) { - return fn - ? describeComponentFrame(fn.displayName || fn.name || null, null) - : ""; -} -var hasOwnProperty = Object.prototype.hasOwnProperty, + cancelTimeout = clearTimeout, valueStack = [], index = -1; function createCursor(defaultValue) { @@ -2054,89 +1889,7 @@ function push(cursor, value) { valueStack[index] = cursor.current; cursor.current = value; } -var emptyContextObject = {}, - contextStackCursor$1 = createCursor(emptyContextObject), - didPerformWorkStackCursor = createCursor(!1), - previousContext = emptyContextObject; -function getMaskedContext(workInProgress, unmaskedContext) { - var contextTypes = workInProgress.type.contextTypes; - if (!contextTypes) return emptyContextObject; - var instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) - return instance.__reactInternalMemoizedMaskedChildContext; - var context = {}, - key; - for (key in contextTypes) context[key] = unmaskedContext[key]; - instance && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); - return context; -} -function isContextProvider(type) { - type = type.childContextTypes; - return null !== type && void 0 !== type; -} -function popContext() { - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); -} -function pushTopLevelContextObject(fiber, context, didChange) { - if (contextStackCursor$1.current !== emptyContextObject) - throw Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); - push(contextStackCursor$1, context); - push(didPerformWorkStackCursor, didChange); -} -function processChildContext(fiber, type, parentContext) { - var instance = fiber.stateNode; - type = type.childContextTypes; - if ("function" !== typeof instance.getChildContext) return parentContext; - instance = instance.getChildContext(); - for (var contextKey in instance) - if (!(contextKey in type)) - throw Error( - (getComponentNameFromFiber(fiber) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ); - return assign({}, parentContext, instance); -} -function pushContextProvider(workInProgress) { - workInProgress = - ((workInProgress = workInProgress.stateNode) && - workInProgress.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - previousContext = contextStackCursor$1.current; - push(contextStackCursor$1, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current); - return !0; -} -function invalidateContextProvider(workInProgress, type, didChange) { - var instance = workInProgress.stateNode; - if (!instance) - throw Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ); - didChange - ? ((workInProgress = processChildContext( - workInProgress, - type, - previousContext - )), - (instance.__reactInternalMemoizedMergedChildContext = workInProgress), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - push(contextStackCursor$1, workInProgress)) - : pop(didPerformWorkStackCursor); - push(didPerformWorkStackCursor, didChange); -} +var emptyContextObject = {}; function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } @@ -2345,6 +2098,7 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy) { workInProgressRootRenderLanes$13, workInProgressRootRecoverableErrors, workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane )); } @@ -2699,6 +2453,7 @@ function commitCallbacks(updateQueue, context) { ) callCallback(callbacks[updateQueue], context); } +var hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { if (objectIs(objA, objB)) return !0; if ( @@ -2721,6 +2476,16 @@ function shallowEqual(objA, objB) { } return !0; } +function describeComponentFrame(name, ownerName) { + var sourceInfo = ""; + ownerName && (sourceInfo = " (created by " + ownerName + ")"); + return "\n in " + (name || "Unknown") + sourceInfo; +} +function describeFunctionComponentFrame(fn) { + return fn + ? describeComponentFrame(fn.displayName || fn.name || null, null) + : ""; +} function describeFiber(fiber) { switch (fiber.tag) { case 26: @@ -2809,16 +2574,16 @@ function trackUsedThenable(thenableState, thenable, index) { } } ); - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw ( - ((thenableState = thenable.reason), - checkIfUseWrappedInAsyncCatch(thenableState), - thenableState) - ); - } + } + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw ( + ((thenableState = thenable.reason), + checkIfUseWrappedInAsyncCatch(thenableState), + thenableState) + ); } suspendedThenable = thenable; throw SuspenseException; @@ -2848,56 +2613,54 @@ function unwrapThenable(thenable) { null === thenableState$1 && (thenableState$1 = []); return trackUsedThenable(thenableState$1, thenable, index); } -function coerceRef(returnFiber, current, element) { - returnFiber = element.ref; - if ( - null !== returnFiber && - "function" !== typeof returnFiber && - "object" !== typeof returnFiber - ) { - if (element._owner) { - element = element._owner; - if (element) { - if (1 !== element.tag) - throw Error( - "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref" - ); - var inst = element.stateNode; - } - if (!inst) - throw Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ); - var resolvedInst = inst, - stringRef = "" + returnFiber; - if ( - null !== current && - null !== current.ref && - "function" === typeof current.ref && - current.ref._stringRef === stringRef - ) - return current.ref; - current = function (value) { - var refs = resolvedInst.refs; - null === value ? delete refs[stringRef] : (refs[stringRef] = value); - }; - current._stringRef = stringRef; - return current; - } - if ("string" !== typeof returnFiber) - throw Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - if (!element._owner) - throw Error( - "Element ref was specified as a string (" + - returnFiber + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information." - ); +function convertStringRefToCallbackRef( + returnFiber, + current, + element, + mixedRef +) { + function ref(value) { + var refs = inst.refs; + null === value ? delete refs[stringRef] : (refs[stringRef] = value); } - return returnFiber; + var stringRef = "" + mixedRef; + returnFiber = element._owner; + if (!returnFiber) + throw Error( + "Element ref was specified as a string (" + + stringRef + + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://react.dev/link/refs-must-have-owner for more information." + ); + if (1 !== returnFiber.tag) + throw Error( + "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://react.dev/link/strict-mode-string-ref" + ); + var inst = returnFiber.stateNode; + if (!inst) + throw Error( + "Missing owner for string ref " + + stringRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + if ( + null !== current && + null !== current.ref && + "function" === typeof current.ref && + current.ref._stringRef === stringRef + ) + return current.ref; + ref._stringRef = stringRef; + return ref; +} +function coerceRef(returnFiber, current, workInProgress, element) { + var mixedRef = element.ref; + returnFiber = + "string" === typeof mixedRef || + "number" === typeof mixedRef || + "boolean" === typeof mixedRef + ? convertStringRefToCallbackRef(returnFiber, current, element, mixedRef) + : mixedRef; + workInProgress.ref = returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { returnFiber = Object.prototype.toString.call(newChild); @@ -2929,13 +2692,13 @@ function createChildReconciler(shouldTrackSideEffects) { (currentFirstChild = currentFirstChild.sibling); return null; } - function mapRemainingChildren(returnFiber, currentFirstChild) { - for (returnFiber = new Map(); null !== currentFirstChild; ) + function mapRemainingChildren(currentFirstChild) { + for (var existingChildren = new Map(); null !== currentFirstChild; ) null !== currentFirstChild.key - ? returnFiber.set(currentFirstChild.key, currentFirstChild) - : returnFiber.set(currentFirstChild.index, currentFirstChild), + ? existingChildren.set(currentFirstChild.key, currentFirstChild) + : existingChildren.set(currentFirstChild.index, currentFirstChild), (currentFirstChild = currentFirstChild.sibling); - return returnFiber; + return existingChildren; } function useFiber(fiber, pendingProps) { fiber = createWorkInProgress(fiber, pendingProps); @@ -2995,7 +2758,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) return ( (lanes = useFiber(current, element.props)), - (lanes.ref = coerceRef(returnFiber, current, element)), + coerceRef(returnFiber, current, lanes, element), (lanes.return = returnFiber), lanes ); @@ -3007,7 +2770,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes ); - lanes.ref = coerceRef(returnFiber, current, element); + coerceRef(returnFiber, current, lanes, element); lanes.return = returnFiber; return lanes; } @@ -3069,7 +2832,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef(returnFiber, null, newChild)), + coerceRef(returnFiber, null, lanes, newChild), (lanes.return = returnFiber), lanes ); @@ -3103,7 +2866,7 @@ function createChildReconciler(shouldTrackSideEffects) { if (newChild.$$typeof === REACT_CONTEXT_TYPE) return createChild( returnFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3150,7 +2913,7 @@ function createChildReconciler(shouldTrackSideEffects) { return updateSlot( returnFiber, oldFiber, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3218,7 +2981,7 @@ function createChildReconciler(shouldTrackSideEffects) { existingChildren, returnFiber, newIdx, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3284,7 +3047,7 @@ function createChildReconciler(shouldTrackSideEffects) { return resultingFirstChild; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++ ) @@ -3372,7 +3135,7 @@ function createChildReconciler(shouldTrackSideEffects) { return iteratorFn; } for ( - oldFiber = mapRemainingChildren(returnFiber, oldFiber); + oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildrenIterable.next() ) @@ -3434,11 +3197,7 @@ function createChildReconciler(shouldTrackSideEffects) { ) { deleteRemainingChildren(returnFiber, child.sibling); currentFirstChild = useFiber(child, newChild.props); - currentFirstChild.ref = coerceRef( - returnFiber, - child, - newChild - ); + coerceRef(returnFiber, child, currentFirstChild, newChild); currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; @@ -3465,11 +3224,7 @@ function createChildReconciler(shouldTrackSideEffects) { returnFiber.mode, lanes )), - (lanes.ref = coerceRef( - returnFiber, - currentFirstChild, - newChild - )), + coerceRef(returnFiber, currentFirstChild, lanes, newChild), (lanes.return = returnFiber), (returnFiber = lanes)); } @@ -3515,7 +3270,7 @@ function createChildReconciler(shouldTrackSideEffects) { case REACT_LAZY_TYPE: return ( (child = newChild._init), - reconcileChildFibers( + reconcileChildFibersImpl( returnFiber, currentFirstChild, child(newChild._payload), @@ -3548,7 +3303,7 @@ function createChildReconciler(shouldTrackSideEffects) { return reconcileChildFibersImpl( returnFiber, currentFirstChild, - readContextDuringReconcilation(returnFiber, newChild, lanes), + readContextDuringReconciliation(returnFiber, newChild, lanes), lanes ); throwOnInvalidObjectType(returnFiber, newChild); @@ -3572,12 +3327,7 @@ function createChildReconciler(shouldTrackSideEffects) { placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild); } - function reconcileChildFibers( - returnFiber, - currentFirstChild, - newChild, - lanes - ) { + return function (returnFiber, currentFirstChild, newChild, lanes) { thenableIndexCounter$1 = 0; returnFiber = reconcileChildFibersImpl( returnFiber, @@ -3587,8 +3337,7 @@ function createChildReconciler(shouldTrackSideEffects) { ); thenableState$1 = null; return returnFiber; - } - return reconcileChildFibers; + }; } var reconcileChildFibers = createChildReconciler(!0), mountChildFibers = createChildReconciler(!1), @@ -3681,7 +3430,7 @@ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, globalClientIdCounter = 0; function throwInvalidHookError() { throw Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." ); } function areHookInputsEqual(nextDeps, prevDeps) { @@ -4632,30 +4381,17 @@ function checkShouldComponentUpdate( : !0; } function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = !1, - unmaskedContext = emptyContextObject; - var context = ctor.contextType; - "object" === typeof context && null !== context - ? (context = readContext(context)) - : ((unmaskedContext = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (isLegacyContextConsumer = ctor.contextTypes), - (context = (isLegacyContextConsumer = - null !== isLegacyContextConsumer && void 0 !== isLegacyContextConsumer) - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject)); + var context = emptyContextObject, + contextType = ctor.contextType; + "object" === typeof contextType && + null !== contextType && + (context = readContext(contextType)); ctor = new ctor(props, context); workInProgress.memoizedState = null !== ctor.state && void 0 !== ctor.state ? ctor.state : null; ctor.updater = classComponentUpdater; workInProgress.stateNode = ctor; ctor._reactInternals = workInProgress; - isLegacyContextConsumer && - ((workInProgress = workInProgress.stateNode), - (workInProgress.__reactInternalMemoizedUnmaskedChildContext = - unmaskedContext), - (workInProgress.__reactInternalMemoizedMaskedChildContext = context)); return ctor; } function callComponentWillReceiveProps( @@ -4679,12 +4415,10 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { instance.refs = {}; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; - "object" === typeof contextType && null !== contextType - ? (instance.context = readContext(contextType)) - : ((contextType = isContextProvider(ctor) - ? previousContext - : contextStackCursor$1.current), - (instance.context = getMaskedContext(workInProgress, contextType))); + instance.context = + "object" === typeof contextType && null !== contextType + ? readContext(contextType) + : emptyContextObject; instance.state = workInProgress.memoizedState; contextType = ctor.getDerivedStateFromProps; "function" === typeof contextType && @@ -4706,12 +4440,23 @@ function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { "function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308); } +var CapturedStacks = new WeakMap(); function createCapturedValueAtFiber(value, source) { + if ("object" === typeof value && null !== value) { + var stack = CapturedStacks.get(value); + "string" !== typeof stack && + ((stack = getStackByFiberInDevAndProd(source)), + CapturedStacks.set(value, stack)); + } else stack = getStackByFiberInDevAndProd(source); + return { value: value, source: source, stack: stack, digest: null }; +} +function createCapturedValueFromError(value, digest, stack) { + "string" === typeof stack && CapturedStacks.set(value, stack); return { value: value, - source: source, - stack: getStackByFiberInDevAndProd(source), - digest: null + source: null, + stack: null != stack ? stack : null, + digest: null != digest ? digest : null }; } if ( @@ -5058,7 +4803,7 @@ function updateOffscreenComponent(current, workInProgress, renderLanes) { nextChildren = nextProps.children, nextIsDetached = 0 !== (workInProgress.stateNode._pendingVisibility & 2), prevState = null !== current ? current.memoizedState : null; - markRef$1(current, workInProgress); + markRef(current, workInProgress); if ("hidden" === nextProps.mode || nextIsDetached) { if (0 !== (workInProgress.flags & 128)) { renderLanes = @@ -5112,13 +4857,20 @@ function deferHiddenOffscreenComponent(current, workInProgress, nextBaseLanes) { pushOffscreenSuspenseHandler(workInProgress); return null; } -function markRef$1(current, workInProgress) { +function markRef(current, workInProgress) { var ref = workInProgress.ref; - if ( - (null === current && null !== ref) || - (null !== current && current.ref !== ref) - ) - (workInProgress.flags |= 512), (workInProgress.flags |= 2097152); + if (null === ref) + null !== current && + null !== current.ref && + (workInProgress.flags |= 2097664); + else { + if ("function" !== typeof ref && "object" !== typeof ref) + throw Error( + "Expected ref to be a function, an object returned by React.createRef(), or undefined/null." + ); + if (null === current || current.ref !== ref) + workInProgress.flags |= 2097664; + } } function updateFunctionComponent( current, @@ -5127,17 +4879,13 @@ function updateFunctionComponent( nextProps, renderLanes ) { - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(workInProgress, context); prepareToReadContext(workInProgress, renderLanes); Component = renderWithHooks( current, workInProgress, Component, nextProps, - context, + void 0, renderLanes ); if (null !== current && !didReceiveUpdate) @@ -5181,10 +4929,6 @@ function updateClassComponent( nextProps, renderLanes ) { - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; prepareToReadContext(workInProgress, renderLanes); if (null === workInProgress.stateNode) resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), @@ -5196,36 +4940,30 @@ function updateClassComponent( oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context, - contextType = Component.contextType; - "object" === typeof contextType && null !== contextType - ? (contextType = readContext(contextType)) - : ((contextType = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (contextType = getMaskedContext(workInProgress, contextType))); - var getDerivedStateFromProps = Component.getDerivedStateFromProps, - hasNewLifecycles = - "function" === typeof getDerivedStateFromProps || - "function" === typeof instance.getSnapshotBeforeUpdate; - hasNewLifecycles || + contextType = Component.contextType, + nextContext = emptyContextObject; + "object" === typeof contextType && + null !== contextType && + (nextContext = readContext(contextType)); + var getDerivedStateFromProps = Component.getDerivedStateFromProps; + (contextType = + "function" === typeof getDerivedStateFromProps || + "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== nextProps || oldContext !== contextType) && + ((oldProps !== nextProps || oldContext !== nextContext) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - contextType + nextContext )); hasForceUpdate = !1; var oldState = workInProgress.memoizedState; instance.state = oldState; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); oldContext = workInProgress.memoizedState; - oldProps !== nextProps || - oldState !== oldContext || - didPerformWorkStackCursor.current || - hasForceUpdate + oldProps !== nextProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps( workInProgress, @@ -5243,9 +4981,9 @@ function updateClassComponent( nextProps, oldState, oldContext, - contextType + nextContext )) - ? (hasNewLifecycles || + ? (contextType || ("function" !== typeof instance.UNSAFE_componentWillMount && "function" !== typeof instance.componentWillMount) || ("function" === typeof instance.componentWillMount && @@ -5260,7 +4998,7 @@ function updateClassComponent( (workInProgress.memoizedState = oldContext)), (instance.props = nextProps), (instance.state = oldContext), - (instance.context = contextType), + (instance.context = nextContext), (nextProps = oldProps)) : ("function" === typeof instance.componentDidMount && (workInProgress.flags |= 4194308), @@ -5268,48 +5006,46 @@ function updateClassComponent( } else { instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); - oldProps = workInProgress.memoizedProps; + nextContext = workInProgress.memoizedProps; contextType = workInProgress.type === workInProgress.elementType - ? oldProps - : resolveDefaultProps(workInProgress.type, oldProps); + ? nextContext + : resolveDefaultProps(workInProgress.type, nextContext); instance.props = contextType; - hasNewLifecycles = workInProgress.pendingProps; - oldState = instance.context; + getDerivedStateFromProps = workInProgress.pendingProps; + var oldContext$jscomp$0 = instance.context; oldContext = Component.contextType; - "object" === typeof oldContext && null !== oldContext - ? (oldContext = readContext(oldContext)) - : ((oldContext = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current), - (oldContext = getMaskedContext(workInProgress, oldContext))); - var getDerivedStateFromProps$jscomp$0 = Component.getDerivedStateFromProps; - (getDerivedStateFromProps = - "function" === typeof getDerivedStateFromProps$jscomp$0 || + oldProps = emptyContextObject; + "object" === typeof oldContext && + null !== oldContext && + (oldProps = readContext(oldContext)); + oldState = Component.getDerivedStateFromProps; + (oldContext = + "function" === typeof oldState || "function" === typeof instance.getSnapshotBeforeUpdate) || ("function" !== typeof instance.UNSAFE_componentWillReceiveProps && "function" !== typeof instance.componentWillReceiveProps) || - ((oldProps !== hasNewLifecycles || oldState !== oldContext) && + ((nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== oldProps) && callComponentWillReceiveProps( workInProgress, instance, nextProps, - oldContext + oldProps )); hasForceUpdate = !1; - oldState = workInProgress.memoizedState; - instance.state = oldState; + oldContext$jscomp$0 = workInProgress.memoizedState; + instance.state = oldContext$jscomp$0; processUpdateQueue(workInProgress, nextProps, instance, renderLanes); var newState = workInProgress.memoizedState; - oldProps !== hasNewLifecycles || - oldState !== newState || - didPerformWorkStackCursor.current || + nextContext !== getDerivedStateFromProps || + oldContext$jscomp$0 !== newState || hasForceUpdate - ? ("function" === typeof getDerivedStateFromProps$jscomp$0 && + ? ("function" === typeof oldState && (applyDerivedStateFromProps( workInProgress, Component, - getDerivedStateFromProps$jscomp$0, + oldState, nextProps ), (newState = workInProgress.memoizedState)), @@ -5320,47 +5056,47 @@ function updateClassComponent( Component, contextType, nextProps, - oldState, + oldContext$jscomp$0, newState, - oldContext + oldProps ) || !1) - ? (getDerivedStateFromProps || + ? (oldContext || ("function" !== typeof instance.UNSAFE_componentWillUpdate && "function" !== typeof instance.componentWillUpdate) || ("function" === typeof instance.componentWillUpdate && - instance.componentWillUpdate(nextProps, newState, oldContext), + instance.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof instance.UNSAFE_componentWillUpdate && instance.UNSAFE_componentWillUpdate( nextProps, newState, - oldContext + oldProps )), "function" === typeof instance.componentDidUpdate && (workInProgress.flags |= 4), "function" === typeof instance.getSnapshotBeforeUpdate && (workInProgress.flags |= 1024)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (workInProgress.memoizedProps = nextProps), (workInProgress.memoizedState = newState)), (instance.props = nextProps), (instance.state = newState), - (instance.context = oldContext), + (instance.context = oldProps), (nextProps = contextType)) : ("function" !== typeof instance.componentDidUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 4), "function" !== typeof instance.getSnapshotBeforeUpdate || - (oldProps === current.memoizedProps && - oldState === current.memoizedState) || + (nextContext === current.memoizedProps && + oldContext$jscomp$0 === current.memoizedState) || (workInProgress.flags |= 1024), (nextProps = !1)); } @@ -5369,7 +5105,7 @@ function updateClassComponent( workInProgress, Component, nextProps, - hasContext, + !1, renderLanes ); } @@ -5381,26 +5117,18 @@ function finishClassComponent( hasContext, renderLanes ) { - markRef$1(current, workInProgress); - var didCaptureError = 0 !== (workInProgress.flags & 128); - if (!shouldUpdate && !didCaptureError) - return ( - hasContext && invalidateContextProvider(workInProgress, Component, !1), - bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) - ); + markRef(current, workInProgress); + hasContext = 0 !== (workInProgress.flags & 128); + if (!shouldUpdate && !hasContext) + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); shouldUpdate = workInProgress.stateNode; ReactCurrentOwner$1.current = workInProgress; - if ( - didCaptureError && - "function" !== typeof Component.getDerivedStateFromError - ) { - var nextChildren = null; - profilerStartTime = -1; - } else nextChildren = shouldUpdate.render(); + hasContext && "function" !== typeof Component.getDerivedStateFromError + ? ((Component = null), (profilerStartTime = -1)) + : (Component = shouldUpdate.render()); workInProgress.flags |= 1; - null !== current && didCaptureError - ? ((didCaptureError = nextChildren), - (workInProgress.child = reconcileChildFibers( + null !== current && hasContext + ? ((workInProgress.child = reconcileChildFibers( workInProgress, current.child, null, @@ -5409,26 +5137,13 @@ function finishClassComponent( (workInProgress.child = reconcileChildFibers( workInProgress, null, - didCaptureError, + Component, renderLanes ))) - : reconcileChildren(current, workInProgress, nextChildren, renderLanes); + : reconcileChildren(current, workInProgress, Component, renderLanes); workInProgress.memoizedState = shouldUpdate.state; - hasContext && invalidateContextProvider(workInProgress, Component, !0); return workInProgress.child; } -function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - root.pendingContext - ? pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context - ) - : root.context && - pushTopLevelContextObject(workInProgress, root.context, !1); - pushHostContainer(workInProgress, root.containerInfo); -} var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: null }; @@ -5632,18 +5347,16 @@ function updateDehydratedSuspenseComponent( return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags &= -257), + (didPrimaryChildrenDefer = createCapturedValueFromError( + Error( + "There was an error while hydrating this Suspense boundary. Switched to client rendering." + ) + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: Error( - "There was an error while hydrating this Suspense boundary. Switched to client rendering." - ), - source: null, - stack: null, - digest: null - } + didPrimaryChildrenDefer ) ); if (null !== workInProgress.memoizedState) @@ -5700,17 +5413,16 @@ function updateDehydratedSuspenseComponent( "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering." )), (suspenseState.digest = didPrimaryChildrenDefer), + (didPrimaryChildrenDefer = createCapturedValueFromError( + suspenseState, + didPrimaryChildrenDefer, + void 0 + )), retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, - { - value: suspenseState, - source: null, - stack: null, - digest: - null != didPrimaryChildrenDefer ? didPrimaryChildrenDefer : null - } + didPrimaryChildrenDefer ) ); didPrimaryChildrenDefer = 0 !== (renderLanes & current.childLanes); @@ -5941,36 +5653,32 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ) { switch (workInProgress.tag) { case 3: - pushHostRootContext(workInProgress); + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 27: case 5: pushHostContext(workInProgress); break; - case 1: - isContextProvider(workInProgress.type) && - pushContextProvider(workInProgress); - break; case 4: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case 10: - var context = workInProgress.type._context, - nextValue = workInProgress.memoizedProps.value; + var newValue = workInProgress.memoizedProps.value, + context = workInProgress.type._context; push(valueCursor, context._currentValue); - context._currentValue = nextValue; + context._currentValue = newValue; break; case 12: 0 !== (renderLanes & workInProgress.childLanes) && (workInProgress.flags |= 4); - context = workInProgress.stateNode; - context.effectDuration = 0; - context.passiveEffectDuration = 0; + newValue = workInProgress.stateNode; + newValue.effectDuration = 0; + newValue.passiveEffectDuration = 0; break; case 13: - context = workInProgress.memoizedState; - if (null !== context) { - if (null !== context.dehydrated) + newValue = workInProgress.memoizedState; + if (null !== newValue) { + if (null !== newValue.dehydrated) return ( pushPrimaryTreeSuspenseHandler(workInProgress), (workInProgress.flags |= 128), @@ -5989,9 +5697,9 @@ function attemptEarlyBailoutIfNoScheduledUpdate( pushPrimaryTreeSuspenseHandler(workInProgress); break; case 19: - context = 0 !== (renderLanes & workInProgress.childLanes); + newValue = 0 !== (renderLanes & workInProgress.childLanes); if (0 !== (current.flags & 128)) { - if (context) + if (newValue) return updateSuspenseListComponent( current, workInProgress, @@ -5999,13 +5707,13 @@ function attemptEarlyBailoutIfNoScheduledUpdate( ); workInProgress.flags |= 128; } - nextValue = workInProgress.memoizedState; - null !== nextValue && - ((nextValue.rendering = null), - (nextValue.tail = null), - (nextValue.lastEffect = null)); + context = workInProgress.memoizedState; + null !== context && + ((context.rendering = null), + (context.tail = null), + (context.lastEffect = null)); push(suspenseStackCursor, suspenseStackCursor.current); - if (context) break; + if (newValue) break; else return null; case 22: case 23: @@ -6016,3637 +5724,3603 @@ function attemptEarlyBailoutIfNoScheduledUpdate( } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } -var valueCursor = createCursor(null), - currentlyRenderingFiber = null, - lastContextDependency = null, - lastFullyObservedContext = null; -function resetContextDependencies() { - lastFullyObservedContext = - lastContextDependency = - currentlyRenderingFiber = - null; -} -function popProvider(context) { - context._currentValue = valueCursor.current; - pop(valueCursor); -} -function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - for (; null !== parent; ) { - var alternate = parent.alternate; - (parent.childLanes & renderLanes) !== renderLanes - ? ((parent.childLanes |= renderLanes), - null !== alternate && (alternate.childLanes |= renderLanes)) - : null !== alternate && - (alternate.childLanes & renderLanes) !== renderLanes && - (alternate.childLanes |= renderLanes); - if (parent === propagationRoot) break; - parent = parent.return; - } -} -function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastFullyObservedContext = lastContextDependency = null; - workInProgress = workInProgress.dependencies; - null !== workInProgress && - null !== workInProgress.firstContext && - (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), - (workInProgress.firstContext = null)); -} -function readContext(context) { - return readContextForConsumer(currentlyRenderingFiber, context); -} -function readContextDuringReconcilation(consumer, context, renderLanes) { - null === currentlyRenderingFiber && - prepareToReadContext(consumer, renderLanes); - return readContextForConsumer(consumer, context); -} -function readContextForConsumer(consumer, context) { - var value = context._currentValue; - if (lastFullyObservedContext !== context) - if ( - ((context = { context: context, memoizedValue: value, next: null }), - null === lastContextDependency) - ) { - if (null === consumer) - throw Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." +function beginWork(current, workInProgress, renderLanes) { + if (null !== current) + if (current.memoizedProps !== workInProgress.pendingProps) + didReceiveUpdate = !0; + else { + if ( + 0 === (current.lanes & renderLanes) && + 0 === (workInProgress.flags & 128) + ) + return ( + (didReceiveUpdate = !1), + attemptEarlyBailoutIfNoScheduledUpdate( + current, + workInProgress, + renderLanes + ) ); - lastContextDependency = context; - consumer.dependencies = { lanes: 0, firstContext: context }; - } else lastContextDependency = lastContextDependency.next = context; - return value; -} -var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; -function handleAsyncAction() {} -function scheduleRetryEffect(workInProgress, retryQueue) { - null !== retryQueue - ? (workInProgress.flags |= 4) - : workInProgress.flags & 16384 && - ((retryQueue = - 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), - (workInProgress.lanes |= retryQueue)); -} -function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - switch (renderState.tailMode) { - case "hidden": - hasRenderedATailFallback = renderState.tail; - for (var lastTailNode = null; null !== hasRenderedATailFallback; ) - null !== hasRenderedATailFallback.alternate && - (lastTailNode = hasRenderedATailFallback), - (hasRenderedATailFallback = hasRenderedATailFallback.sibling); - null === lastTailNode - ? (renderState.tail = null) - : (lastTailNode.sibling = null); - break; - case "collapsed": - lastTailNode = renderState.tail; - for (var lastTailNode$64 = null; null !== lastTailNode; ) - null !== lastTailNode.alternate && (lastTailNode$64 = lastTailNode), - (lastTailNode = lastTailNode.sibling); - null === lastTailNode$64 - ? hasRenderedATailFallback || null === renderState.tail - ? (renderState.tail = null) - : (renderState.tail.sibling = null) - : (lastTailNode$64.sibling = null); - } -} -function bubbleProperties(completedWork) { - var didBailout = - null !== completedWork.alternate && - completedWork.alternate.child === completedWork.child, - newChildLanes = 0, - subtreeFlags = 0; - if (didBailout) - if (0 !== (completedWork.mode & 2)) { - for ( - var treeBaseDuration$66 = completedWork.selfBaseDuration, - child$67 = completedWork.child; - null !== child$67; - - ) - (newChildLanes |= child$67.lanes | child$67.childLanes), - (subtreeFlags |= child$67.subtreeFlags & 31457280), - (subtreeFlags |= child$67.flags & 31457280), - (treeBaseDuration$66 += child$67.treeBaseDuration), - (child$67 = child$67.sibling); - completedWork.treeBaseDuration = treeBaseDuration$66; - } else - for ( - treeBaseDuration$66 = completedWork.child; - null !== treeBaseDuration$66; - - ) - (newChildLanes |= - treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), - (subtreeFlags |= treeBaseDuration$66.subtreeFlags & 31457280), - (subtreeFlags |= treeBaseDuration$66.flags & 31457280), - (treeBaseDuration$66.return = completedWork), - (treeBaseDuration$66 = treeBaseDuration$66.sibling); - else if (0 !== (completedWork.mode & 2)) { - treeBaseDuration$66 = completedWork.actualDuration; - child$67 = completedWork.selfBaseDuration; - for (var child = completedWork.child; null !== child; ) - (newChildLanes |= child.lanes | child.childLanes), - (subtreeFlags |= child.subtreeFlags), - (subtreeFlags |= child.flags), - (treeBaseDuration$66 += child.actualDuration), - (child$67 += child.treeBaseDuration), - (child = child.sibling); - completedWork.actualDuration = treeBaseDuration$66; - completedWork.treeBaseDuration = child$67; - } else - for ( - treeBaseDuration$66 = completedWork.child; - null !== treeBaseDuration$66; - - ) - (newChildLanes |= - treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), - (subtreeFlags |= treeBaseDuration$66.subtreeFlags), - (subtreeFlags |= treeBaseDuration$66.flags), - (treeBaseDuration$66.return = completedWork), - (treeBaseDuration$66 = treeBaseDuration$66.sibling); - completedWork.subtreeFlags |= subtreeFlags; - completedWork.childLanes = newChildLanes; - return didBailout; -} -function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; + didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; + } + else didReceiveUpdate = !1; + workInProgress.lanes = 0; switch (workInProgress.tag) { case 2: + var Component = workInProgress.type; + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + prepareToReadContext(workInProgress, renderLanes); + var value = renderWithHooks( + null, + workInProgress, + Component, + current, + void 0, + renderLanes + ); + workInProgress.flags |= 1; + "object" === typeof value && + null !== value && + "function" === typeof value.render && + void 0 === value.$$typeof + ? ((workInProgress.tag = 1), + (workInProgress.memoizedState = null), + (workInProgress.updateQueue = null), + (workInProgress.memoizedState = + null !== value.state && void 0 !== value.state + ? value.state + : null), + initializeUpdateQueue(workInProgress), + (value.updater = classComponentUpdater), + (workInProgress.stateNode = value), + (value._reactInternals = workInProgress), + mountClassInstance(workInProgress, Component, current, renderLanes), + (workInProgress = finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ))) + : ((workInProgress.tag = 0), + reconcileChildren(null, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 16: - case 15: + Component = workInProgress.elementType; + a: { + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); + current = workInProgress.pendingProps; + value = Component._init; + Component = value(Component._payload); + workInProgress.type = Component; + value = workInProgress.tag = resolveLazyComponentTag(Component); + current = resolveDefaultProps(Component, current); + switch (value) { + case 0: + workInProgress = updateFunctionComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 1: + workInProgress = updateClassComponent( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 11: + workInProgress = updateForwardRef( + null, + workInProgress, + Component, + current, + renderLanes + ); + break a; + case 14: + workInProgress = updateMemoComponent( + null, + workInProgress, + Component, + resolveDefaultProps(Component.type, current), + renderLanes + ); + break a; + } + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + ); + } + return workInProgress; case 0: - case 11: - case 7: - case 8: - case 12: - case 9: - case 14: - return bubbleProperties(workInProgress), null; - case 1: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateFunctionComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); - case 3: + case 1: return ( - (renderLanes = workInProgress.stateNode), - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - renderLanes.pendingContext && - ((renderLanes.context = renderLanes.pendingContext), - (renderLanes.pendingContext = null)), - (null !== current && null !== current.child) || - null === current || - (current.memoizedState.isDehydrated && - 0 === (workInProgress.flags & 256)) || - ((workInProgress.flags |= 1024), - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), - (hydrationErrors = null))), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateClassComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) ); + case 3: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + if (null === current) + throw Error("Should have a current fiber. This is a bug in React."); + value = workInProgress.pendingProps; + Component = workInProgress.memoizedState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, value, null, renderLanes); + value = workInProgress.memoizedState.element; + value === Component + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + )) + : (reconcileChildren(current, workInProgress, value, renderLanes), + (workInProgress = workInProgress.child)); + return workInProgress; case 26: case 27: case 5: - popHostContext(workInProgress); - var type = workInProgress.type; - if (null !== current && null != workInProgress.stateNode) - current.memoizedProps !== newProps && (workInProgress.flags |= 4), - current.ref !== workInProgress.ref && - (workInProgress.flags |= 2097664); - else { - if (!newProps) { - if (null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - bubbleProperties(workInProgress); - return null; - } - current = rootInstanceStackCursor.current; - renderLanes = allocateTag(); - type = getViewConfigForType(type); - var updatePayload = diffProperties( - null, - emptyObject, - newProps, - type.validAttributes - ); - ReactNativePrivateInterface.UIManager.createView( - renderLanes, - type.uiViewClassName, - current, - updatePayload - ); - current = new ReactNativeFiberHostComponent( - renderLanes, - type, - workInProgress - ); - instanceCache.set(renderLanes, workInProgress); - instanceProps.set(renderLanes, newProps); - a: for (renderLanes = workInProgress.child; null !== renderLanes; ) { - if (5 === renderLanes.tag || 6 === renderLanes.tag) - current._children.push(renderLanes.stateNode); - else if (4 !== renderLanes.tag && null !== renderLanes.child) { - renderLanes.child.return = renderLanes; - renderLanes = renderLanes.child; - continue; - } - if (renderLanes === workInProgress) break a; - for (; null === renderLanes.sibling; ) { - if ( - null === renderLanes.return || - renderLanes.return === workInProgress - ) - break a; - renderLanes = renderLanes.return; - } - renderLanes.sibling.return = renderLanes.return; - renderLanes = renderLanes.sibling; - } - workInProgress.stateNode = current; - finalizeInitialChildren(current) && (workInProgress.flags |= 4); - null !== workInProgress.ref && (workInProgress.flags |= 2097664); - } - bubbleProperties(workInProgress); - workInProgress.flags &= -16777217; - return null; + return ( + pushHostContext(workInProgress), + (Component = workInProgress.pendingProps.children), + markRef(current, workInProgress), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); case 6: - if (current && null != workInProgress.stateNode) - current.memoizedProps !== newProps && (workInProgress.flags |= 4); - else { - if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ); - renderLanes = rootInstanceStackCursor.current; - if (!contextStackCursor.current.isInAParentText) - throw Error( - "Text strings must be rendered within a component." - ); - current = allocateTag(); - ReactNativePrivateInterface.UIManager.createView( - current, - "RCTRawText", - renderLanes, - { text: newProps } - ); - instanceCache.set(current, workInProgress); - workInProgress.stateNode = current; - } - bubbleProperties(workInProgress); return null; case 13: - popSuspenseHandler(workInProgress); - newProps = workInProgress.memoizedState; - if ( - null === current || - (null !== current.memoizedState && - null !== current.memoizedState.dehydrated) - ) { - if (null !== newProps && null !== newProps.dehydrated) { - if (null === current) { - throw Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ); - throw Error( - "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ); - } - 0 === (workInProgress.flags & 128) && - (workInProgress.memoizedState = null); - workInProgress.flags |= 4; - bubbleProperties(workInProgress); - 0 !== (workInProgress.mode & 2) && - null !== newProps && - ((type = workInProgress.child), - null !== type && - (workInProgress.treeBaseDuration -= type.treeBaseDuration)); - type = !1; - } else - null !== hydrationErrors && - (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), - (type = !0); - if (!type) return workInProgress.flags & 256 ? workInProgress : null; - } - if (0 !== (workInProgress.flags & 128)) - return ( - (workInProgress.lanes = renderLanes), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress - ); - renderLanes = null !== newProps; - renderLanes !== (null !== current && null !== current.memoizedState) && - renderLanes && - (workInProgress.child.flags |= 8192); - scheduleRetryEffect(workInProgress, workInProgress.updateQueue); - bubbleProperties(workInProgress); - 0 !== (workInProgress.mode & 2) && - renderLanes && - ((renderLanes = workInProgress.child), - null !== renderLanes && - (workInProgress.treeBaseDuration -= renderLanes.treeBaseDuration)); - return null; + return updateSuspenseComponent(current, workInProgress, renderLanes); case 4: - return popHostContainer(), bubbleProperties(workInProgress), null; - case 10: return ( - popProvider(workInProgress.type._context), - bubbleProperties(workInProgress), - null + pushHostContainer( + workInProgress, + workInProgress.stateNode.containerInfo + ), + (Component = workInProgress.pendingProps), + null === current + ? (workInProgress.child = reconcileChildFibers( + workInProgress, + null, + Component, + renderLanes + )) + : reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child ); - case 17: + case 11: return ( - isContextProvider(workInProgress.type) && popContext(), - bubbleProperties(workInProgress), - null + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + updateForwardRef(current, workInProgress, Component, value, renderLanes) ); - case 19: - pop(suspenseStackCursor); - type = workInProgress.memoizedState; - if (null === type) return bubbleProperties(workInProgress), null; - newProps = 0 !== (workInProgress.flags & 128); - updatePayload = type.rendering; - if (null === updatePayload) - if (newProps) cutOffTailIfNeeded(type, !1); - else { - if ( - 0 !== workInProgressRootExitStatus || - (null !== current && 0 !== (current.flags & 128)) - ) - for (current = workInProgress.child; null !== current; ) { - updatePayload = findFirstSuspended(current); - if (null !== updatePayload) { - workInProgress.flags |= 128; - cutOffTailIfNeeded(type, !1); - current = updatePayload.updateQueue; - workInProgress.updateQueue = current; - scheduleRetryEffect(workInProgress, current); - workInProgress.subtreeFlags = 0; - for (current = workInProgress.child; null !== current; ) - resetWorkInProgress(current, renderLanes), - (current = current.sibling); - push( - suspenseStackCursor, - (suspenseStackCursor.current & 1) | 2 - ); - return workInProgress.child; - } - current = current.sibling; - } - null !== type.tail && - now$1() > workInProgressRootRenderTargetTime && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(type, !1), - (workInProgress.lanes = 4194304)); - } - else { - if (!newProps) - if ( - ((current = findFirstSuspended(updatePayload)), null !== current) - ) { - if ( - ((workInProgress.flags |= 128), - (newProps = !0), - (renderLanes = current.updateQueue), - (workInProgress.updateQueue = renderLanes), - scheduleRetryEffect(workInProgress, renderLanes), - cutOffTailIfNeeded(type, !0), - null === type.tail && - "hidden" === type.tailMode && - !updatePayload.alternate) - ) - return bubbleProperties(workInProgress), null; - } else - 2 * now$1() - type.renderingStartTime > - workInProgressRootRenderTargetTime && - 536870912 !== renderLanes && - ((workInProgress.flags |= 128), - (newProps = !0), - cutOffTailIfNeeded(type, !1), - (workInProgress.lanes = 4194304)); - type.isBackwards - ? ((updatePayload.sibling = workInProgress.child), - (workInProgress.child = updatePayload)) - : ((renderLanes = type.last), - null !== renderLanes - ? (renderLanes.sibling = updatePayload) - : (workInProgress.child = updatePayload), - (type.last = updatePayload)); - } - if (null !== type.tail) - return ( - (workInProgress = type.tail), - (type.rendering = workInProgress), - (type.tail = workInProgress.sibling), - (type.renderingStartTime = now$1()), - (workInProgress.sibling = null), - (renderLanes = suspenseStackCursor.current), - push( - suspenseStackCursor, - newProps ? (renderLanes & 1) | 2 : renderLanes & 1 - ), - workInProgress - ); - bubbleProperties(workInProgress); - return null; - case 22: - case 23: + case 7: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (newProps = null !== workInProgress.memoizedState), - null !== current - ? (null !== current.memoizedState) !== newProps && - (workInProgress.flags |= 8192) - : newProps && (workInProgress.flags |= 8192), - newProps && 0 !== (workInProgress.mode & 1) - ? 0 !== (renderLanes & 536870912) && - 0 === (workInProgress.flags & 128) && - (bubbleProperties(workInProgress), - workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) - : bubbleProperties(workInProgress), - (renderLanes = workInProgress.updateQueue), - null !== renderLanes && - scheduleRetryEffect(workInProgress, renderLanes.retryQueue), - null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps, + renderLanes + ), + workInProgress.child ); - case 24: - return null; - case 25: - return null; - } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -} -function unwindWork(current, workInProgress) { - switch (workInProgress.tag) { - case 1: + case 8: return ( - isContextProvider(workInProgress.type) && popContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child ); - case 3: + case 12: return ( - popHostContainer(), - pop(didPerformWorkStackCursor), - pop(contextStackCursor$1), - (current = workInProgress.flags), - 0 !== (current & 65536) && 0 === (current & 128) - ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) - : null + (workInProgress.flags |= 4), + (Component = workInProgress.stateNode), + (Component.effectDuration = 0), + (Component.passiveEffectDuration = 0), + reconcileChildren( + current, + workInProgress, + workInProgress.pendingProps.children, + renderLanes + ), + workInProgress.child ); - case 26: - case 27: - case 5: - return popHostContext(workInProgress), null; - case 13: - popSuspenseHandler(workInProgress); - current = workInProgress.memoizedState; - if ( - null !== current && - null !== current.dehydrated && - null === workInProgress.alternate - ) - throw Error( - "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." - ); - current = workInProgress.flags; - return current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null; - case 19: - return pop(suspenseStackCursor), null; - case 4: - return popHostContainer(), null; case 10: - return popProvider(workInProgress.type._context), null; - case 22: - case 23: + a: { + Component = workInProgress.type._context; + value = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps, + newValue = value.value; + push(valueCursor, Component._currentValue); + Component._currentValue = newValue; + if (null !== oldProps) + if (objectIs(oldProps.value, newValue)) { + if (oldProps.children === value.children) { + workInProgress = bailoutOnAlreadyFinishedWork( + current, + workInProgress, + renderLanes + ); + break a; + } + } else + for ( + oldProps = workInProgress.child, + null !== oldProps && (oldProps.return = workInProgress); + null !== oldProps; + + ) { + var list = oldProps.dependencies; + if (null !== list) { + newValue = oldProps.child; + for ( + var dependency = list.firstContext; + null !== dependency; + + ) { + if (dependency.context === Component) { + if (1 === oldProps.tag) { + dependency = createUpdate(renderLanes & -renderLanes); + dependency.tag = 2; + var updateQueue = oldProps.updateQueue; + if (null !== updateQueue) { + updateQueue = updateQueue.shared; + var pending = updateQueue.pending; + null === pending + ? (dependency.next = dependency) + : ((dependency.next = pending.next), + (pending.next = dependency)); + updateQueue.pending = dependency; + } + } + oldProps.lanes |= renderLanes; + dependency = oldProps.alternate; + null !== dependency && (dependency.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + oldProps.return, + renderLanes, + workInProgress + ); + list.lanes |= renderLanes; + break; + } + dependency = dependency.next; + } + } else if (10 === oldProps.tag) + newValue = + oldProps.type === workInProgress.type ? null : oldProps.child; + else if (18 === oldProps.tag) { + newValue = oldProps.return; + if (null === newValue) + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + newValue.lanes |= renderLanes; + list = newValue.alternate; + null !== list && (list.lanes |= renderLanes); + scheduleContextWorkOnParentPath( + newValue, + renderLanes, + workInProgress + ); + newValue = oldProps.sibling; + } else newValue = oldProps.child; + if (null !== newValue) newValue.return = oldProps; + else + for (newValue = oldProps; null !== newValue; ) { + if (newValue === workInProgress) { + newValue = null; + break; + } + oldProps = newValue.sibling; + if (null !== oldProps) { + oldProps.return = newValue.return; + newValue = oldProps; + break; + } + newValue = newValue.return; + } + oldProps = newValue; + } + reconcileChildren(current, workInProgress, value.children, renderLanes); + workInProgress = workInProgress.child; + } + return workInProgress; + case 9: return ( - popSuspenseHandler(workInProgress), - popHiddenContext(), - (current = workInProgress.flags), - current & 65536 - ? ((workInProgress.flags = (current & -65537) | 128), - 0 !== (workInProgress.mode & 2) && - transferActualDuration(workInProgress), - workInProgress) - : null + (value = workInProgress.type), + (Component = workInProgress.pendingProps.children), + prepareToReadContext(workInProgress, renderLanes), + (value = readContext(value)), + (Component = Component(value)), + (workInProgress.flags |= 1), + reconcileChildren(current, workInProgress, Component, renderLanes), + workInProgress.child + ); + case 14: + return ( + (Component = workInProgress.type), + (value = resolveDefaultProps(Component, workInProgress.pendingProps)), + (value = resolveDefaultProps(Component.type, value)), + updateMemoComponent( + current, + workInProgress, + Component, + value, + renderLanes + ) + ); + case 15: + return updateSimpleMemoComponent( + current, + workInProgress, + workInProgress.type, + workInProgress.pendingProps, + renderLanes + ); + case 17: + return ( + (Component = workInProgress.type), + (value = workInProgress.pendingProps), + (value = + workInProgress.elementType === Component + ? value + : resolveDefaultProps(Component, value)), + resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), + (workInProgress.tag = 1), + prepareToReadContext(workInProgress, renderLanes), + constructClassInstance(workInProgress, Component, value), + mountClassInstance(workInProgress, Component, value, renderLanes), + finishClassComponent( + null, + workInProgress, + Component, + !0, + !1, + renderLanes + ) ); - case 24: - return null; - case 25: - return null; - default: - return null; - } -} -function unwindInterruptedWork(current, interruptedWork) { - switch (interruptedWork.tag) { - case 1: - current = interruptedWork.type.childContextTypes; - null !== current && void 0 !== current && popContext(); - break; - case 3: - popHostContainer(); - pop(didPerformWorkStackCursor); - pop(contextStackCursor$1); - break; - case 26: - case 27: - case 5: - popHostContext(interruptedWork); - break; - case 4: - popHostContainer(); - break; - case 13: - popSuspenseHandler(interruptedWork); - break; case 19: - pop(suspenseStackCursor); - break; - case 10: - popProvider(interruptedWork.type._context); - break; + return updateSuspenseListComponent(current, workInProgress, renderLanes); case 22: - case 23: - popSuspenseHandler(interruptedWork), popHiddenContext(); + return updateOffscreenComponent(current, workInProgress, renderLanes); } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); } -var offscreenSubtreeIsHidden = !1, - offscreenSubtreeWasHidden = !1, - PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, - nextEffect = null, - inProgressLanes = null, - inProgressRoot = null; -function shouldProfile(current) { - return 0 !== (current.mode & 2) && 0 !== (executionContext & 4); +var valueCursor = createCursor(null), + currentlyRenderingFiber = null, + lastContextDependency = null, + lastFullyObservedContext = null; +function resetContextDependencies() { + lastFullyObservedContext = + lastContextDependency = + currentlyRenderingFiber = + null; } -function callComponentWillUnmountWithTimer(current, instance) { - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current); - } - else instance.componentWillUnmount(); +function popProvider(context) { + context._currentValue = valueCursor.current; + pop(valueCursor); } -function safelyAttachRef(current, nearestMountedAncestor) { - try { - var ref = current.ref; - if (null !== ref) { - var instance = current.stateNode; - switch (current.tag) { - case 26: - case 27: - case 5: - var instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - if ("function" === typeof ref) - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), (current.refCleanup = ref(instanceToUse)); - } finally { - recordLayoutEffectDuration(current); - } - else current.refCleanup = ref(instanceToUse); - else ref.current = instanceToUse; - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); +function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + for (; null !== parent; ) { + var alternate = parent.alternate; + (parent.childLanes & renderLanes) !== renderLanes + ? ((parent.childLanes |= renderLanes), + null !== alternate && (alternate.childLanes |= renderLanes)) + : null !== alternate && + (alternate.childLanes & renderLanes) !== renderLanes && + (alternate.childLanes |= renderLanes); + if (parent === propagationRoot) break; + parent = parent.return; } } -function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref, - refCleanup = current.refCleanup; - if (null !== ref) - if ("function" === typeof refCleanup) - try { - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), refCleanup(); - } finally { - recordLayoutEffectDuration(current); - } - else refCleanup(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } finally { - (current.refCleanup = null), - (current = current.alternate), - null != current && (current.refCleanup = null); - } - else if ("function" === typeof ref) - try { - if (shouldProfile(current)) - try { - startLayoutEffectTimer(), ref(null); - } finally { - recordLayoutEffectDuration(current); - } - else ref(null); - } catch (error$85) { - captureCommitPhaseError(current, nearestMountedAncestor, error$85); - } - else ref.current = null; -} -function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } +function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastFullyObservedContext = lastContextDependency = null; + workInProgress = workInProgress.dependencies; + null !== workInProgress && + null !== workInProgress.firstContext && + (0 !== (workInProgress.lanes & renderLanes) && (didReceiveUpdate = !0), + (workInProgress.firstContext = null)); } -var shouldFireAfterActiveInstanceBlur = !1; -function commitBeforeMutationEffects(root, firstChild) { - for (nextEffect = firstChild; null !== nextEffect; ) - if ( - ((root = nextEffect), - (firstChild = root.child), - 0 !== (root.subtreeFlags & 1028) && null !== firstChild) - ) - (firstChild.return = root), (nextEffect = firstChild); - else - for (; null !== nextEffect; ) { - root = nextEffect; - try { - var current = root.alternate, - flags = root.flags; - switch (root.tag) { - case 0: - break; - case 11: - case 15: - break; - case 1: - if (0 !== (flags & 1024) && null !== current) { - var prevProps = current.memoizedProps, - prevState = current.memoizedState, - instance = root.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - root.elementType === root.type - ? prevProps - : resolveDefaultProps(root.type, prevProps), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - break; - case 5: - case 26: - case 27: - case 6: - case 4: - case 17: - break; - default: - if (0 !== (flags & 1024)) - throw Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ); - } - } catch (error) { - captureCommitPhaseError(root, root.return, error); - } - firstChild = root.sibling; - if (null !== firstChild) { - firstChild.return = root.return; - nextEffect = firstChild; - break; - } - nextEffect = root.return; - } - current = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = !1; - return current; +function readContext(context) { + return readContextForConsumer(currentlyRenderingFiber, context); } -function commitHookEffectListUnmount( - flags, - finishedWork, - nearestMountedAncestor -) { - var updateQueue = finishedWork.updateQueue; - updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; - if (null !== updateQueue) { - var effect = (updateQueue = updateQueue.next); - do { - if ((effect.tag & flags) === flags) { - var inst = effect.inst, - destroy = inst.destroy; - void 0 !== destroy && - ((inst.destroy = void 0), - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); - } - effect = effect.next; - } while (effect !== updateQueue); - } +function readContextDuringReconciliation(consumer, context, renderLanes) { + null === currentlyRenderingFiber && + prepareToReadContext(consumer, renderLanes); + return readContextForConsumer(consumer, context); } -function commitHookEffectListMount(flags, finishedWork) { - finishedWork = finishedWork.updateQueue; - finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; - if (null !== finishedWork) { - var effect = (finishedWork = finishedWork.next); - do { - if ((effect.tag & flags) === flags) { - var create$86 = effect.create, - inst = effect.inst; - create$86 = create$86(); - inst.destroy = create$86; - } - effect = effect.next; - } while (effect !== finishedWork); - } +function readContextForConsumer(consumer, context) { + var value = context._currentValue; + if (lastFullyObservedContext !== context) + if ( + ((context = { context: context, memoizedValue: value, next: null }), + null === lastContextDependency) + ) { + if (null === consumer) + throw Error( + "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." + ); + lastContextDependency = context; + consumer.dependencies = { lanes: 0, firstContext: context }; + } else lastContextDependency = lastContextDependency.next = context; + return value; } -function commitHookLayoutEffects(finishedWork, hookFlags) { - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error$88) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$88); - } +var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; +function handleAsyncAction() {} +function scheduleRetryEffect(workInProgress, retryQueue) { + null !== retryQueue + ? (workInProgress.flags |= 4) + : workInProgress.flags & 16384 && + ((retryQueue = + 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912), + (workInProgress.lanes |= retryQueue)); } -function commitClassCallbacks(finishedWork) { - var updateQueue = finishedWork.updateQueue; - if (null !== updateQueue) { - var instance = finishedWork.stateNode; - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + switch (renderState.tailMode) { + case "hidden": + hasRenderedATailFallback = renderState.tail; + for (var lastTailNode = null; null !== hasRenderedATailFallback; ) + null !== hasRenderedATailFallback.alternate && + (lastTailNode = hasRenderedATailFallback), + (hasRenderedATailFallback = hasRenderedATailFallback.sibling); + null === lastTailNode + ? (renderState.tail = null) + : (lastTailNode.sibling = null); + break; + case "collapsed": + lastTailNode = renderState.tail; + for (var lastTailNode$64 = null; null !== lastTailNode; ) + null !== lastTailNode.alternate && (lastTailNode$64 = lastTailNode), + (lastTailNode = lastTailNode.sibling); + null === lastTailNode$64 + ? hasRenderedATailFallback || null === renderState.tail + ? (renderState.tail = null) + : (renderState.tail.sibling = null) + : (lastTailNode$64.sibling = null); } } -function commitProfilerUpdate(finishedWork, current) { - if (executionContext & 4) - try { - var _finishedWork$memoize2 = finishedWork.memoizedProps, - onCommit = _finishedWork$memoize2.onCommit, - onRender = _finishedWork$memoize2.onRender, - effectDuration = finishedWork.stateNode.effectDuration; - _finishedWork$memoize2 = commitTime; - current = null === current ? "mount" : "update"; - currentUpdateIsNested && (current = "nested-update"); - "function" === typeof onRender && - onRender( - finishedWork.memoizedProps.id, - current, - finishedWork.actualDuration, - finishedWork.treeBaseDuration, - finishedWork.actualStartTime, - _finishedWork$memoize2 - ); - "function" === typeof onCommit && - onCommit( - finishedWork.memoizedProps.id, - current, - effectDuration, - _finishedWork$memoize2 - ); - enqueuePendingPassiveProfilerEffect(finishedWork); - var parentFiber = finishedWork.return; - a: for (; null !== parentFiber; ) { - switch (parentFiber.tag) { - case 3: - parentFiber.stateNode.effectDuration += effectDuration; - break a; - case 12: - parentFiber.stateNode.effectDuration += effectDuration; - break a; - } - parentFiber = parentFiber.return; - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } +function bubbleProperties(completedWork) { + var didBailout = + null !== completedWork.alternate && + completedWork.alternate.child === completedWork.child, + newChildLanes = 0, + subtreeFlags = 0; + if (didBailout) + if (0 !== (completedWork.mode & 2)) { + for ( + var treeBaseDuration$66 = completedWork.selfBaseDuration, + child$67 = completedWork.child; + null !== child$67; + + ) + (newChildLanes |= child$67.lanes | child$67.childLanes), + (subtreeFlags |= child$67.subtreeFlags & 31457280), + (subtreeFlags |= child$67.flags & 31457280), + (treeBaseDuration$66 += child$67.treeBaseDuration), + (child$67 = child$67.sibling); + completedWork.treeBaseDuration = treeBaseDuration$66; + } else + for ( + treeBaseDuration$66 = completedWork.child; + null !== treeBaseDuration$66; + + ) + (newChildLanes |= + treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), + (subtreeFlags |= treeBaseDuration$66.subtreeFlags & 31457280), + (subtreeFlags |= treeBaseDuration$66.flags & 31457280), + (treeBaseDuration$66.return = completedWork), + (treeBaseDuration$66 = treeBaseDuration$66.sibling); + else if (0 !== (completedWork.mode & 2)) { + treeBaseDuration$66 = completedWork.actualDuration; + child$67 = completedWork.selfBaseDuration; + for (var child = completedWork.child; null !== child; ) + (newChildLanes |= child.lanes | child.childLanes), + (subtreeFlags |= child.subtreeFlags), + (subtreeFlags |= child.flags), + (treeBaseDuration$66 += child.actualDuration), + (child$67 += child.treeBaseDuration), + (child = child.sibling); + completedWork.actualDuration = treeBaseDuration$66; + completedWork.treeBaseDuration = child$67; + } else + for ( + treeBaseDuration$66 = completedWork.child; + null !== treeBaseDuration$66; + + ) + (newChildLanes |= + treeBaseDuration$66.lanes | treeBaseDuration$66.childLanes), + (subtreeFlags |= treeBaseDuration$66.subtreeFlags), + (subtreeFlags |= treeBaseDuration$66.flags), + (treeBaseDuration$66.return = completedWork), + (treeBaseDuration$66 = treeBaseDuration$66.sibling); + completedWork.subtreeFlags |= subtreeFlags; + completedWork.childLanes = newChildLanes; + return didBailout; } -function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { - var flags = finishedWork.flags; - switch (finishedWork.tag) { +function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; + switch (workInProgress.tag) { + case 2: + case 16: + case 15: case 0: case 11: - case 15: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitHookLayoutEffects(finishedWork, 5); - break; + case 7: + case 8: + case 12: + case 9: + case 14: + return bubbleProperties(workInProgress), null; case 1: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 4) - if (((finishedRoot = finishedWork.stateNode), null === current)) - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - finishedRoot.componentDidMount(); - } catch (error$89) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$89 - ); - } - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current.memoizedProps - : resolveDefaultProps(finishedWork.type, current.memoizedProps); - current = current.memoizedState; - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$90) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$90 - ); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - finishedRoot.componentDidUpdate( - prevProps, - current, - finishedRoot.__reactInternalSnapshotBeforeUpdate - ); - } catch (error$91) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$91 - ); - } - } - flags & 64 && commitClassCallbacks(finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; + return bubbleProperties(workInProgress), null; case 3: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { - finishedRoot = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 27: - case 5: - finishedRoot = getPublicInstance(finishedWork.child.stateNode); - break; - case 1: - finishedRoot = finishedWork.child.stateNode; - } - try { - commitCallbacks(flags, finishedRoot); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - break; + return ( + (renderLanes = workInProgress.stateNode), + popHostContainer(), + renderLanes.pendingContext && + ((renderLanes.context = renderLanes.pendingContext), + (renderLanes.pendingContext = null)), + (null !== current && null !== current.child) || + null === current || + (current.memoizedState.isDehydrated && + 0 === (workInProgress.flags & 256)) || + ((workInProgress.flags |= 1024), + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), + (hydrationErrors = null))), + bubbleProperties(workInProgress), + null + ); case 26: case 27: case 5: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 4 && commitProfilerUpdate(finishedWork, current); - break; - case 13: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - break; - case 22: - if (0 !== (finishedWork.mode & 1)) { - if ( - ((prevProps = - null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), - !prevProps) - ) { - current = - (null !== current && null !== current.memoizedState) || - offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevProps; - (offscreenSubtreeWasHidden = current) && - !prevOffscreenSubtreeWasHidden - ? recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - 0 !== (finishedWork.subtreeFlags & 8772) - ) - : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + popHostContext(workInProgress); + var type = workInProgress.type; + if (null !== current && null != workInProgress.stateNode) + current.memoizedProps !== newProps && (workInProgress.flags |= 4); + else { + if (!newProps) { + if (null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + bubbleProperties(workInProgress); + return null; } - } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - flags & 512 && - ("manual" === finishedWork.memoizedProps.mode - ? safelyAttachRef(finishedWork, finishedWork.return) - : safelyDetachRef(finishedWork, finishedWork.return)); - break; - default: - recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); - } -} -function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - null !== alternate && - ((fiber.alternate = null), detachFiberAfterEffects(alternate)); - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - fiber.stateNode = null; - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - fiber.updateQueue = null; -} -function isHostParent(fiber) { - return 5 === fiber.tag || 3 === fiber.tag || 4 === fiber.tag; -} -function getHostSibling(fiber) { - a: for (;;) { - for (; null === fiber.sibling; ) { - if (null === fiber.return || isHostParent(fiber.return)) return null; - fiber = fiber.return; - } - fiber.sibling.return = fiber.return; - for ( - fiber = fiber.sibling; - 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; - - ) { - if (fiber.flags & 2) continue a; - if (null === fiber.child || 4 === fiber.tag) continue a; - else (fiber.child.return = fiber), (fiber = fiber.child); - } - if (!(fiber.flags & 2)) return fiber.stateNode; - } -} -function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { - var tag = node.tag; - if (5 === tag || 6 === tag) - if (((node = node.stateNode), before)) { - if ("number" === typeof parent) - throw Error("Container does not support insertBefore operation"); - } else - ReactNativePrivateInterface.UIManager.setChildren(parent, [ - "number" === typeof node ? node : node._nativeTag - ]); - else if (4 !== tag && ((node = node.child), null !== node)) - for ( - insertOrAppendPlacementNodeIntoContainer(node, before, parent), - node = node.sibling; - null !== node; - - ) - insertOrAppendPlacementNodeIntoContainer(node, before, parent), - (node = node.sibling); -} -function insertOrAppendPlacementNode(node, before, parent) { - var tag = node.tag; - if (5 === tag || 6 === tag) - if (((node = node.stateNode), before)) { - tag = parent._children; - var index = tag.indexOf(node); - 0 <= index - ? (tag.splice(index, 1), - (before = tag.indexOf(before)), - tag.splice(before, 0, node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [index], - [before], - [], - [], - [] - )) - : ((before = tag.indexOf(before)), - tag.splice(before, 0, node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [], - [], - ["number" === typeof node ? node : node._nativeTag], - [before], - [] - )); - } else - (before = "number" === typeof node ? node : node._nativeTag), - (tag = parent._children), - (index = tag.indexOf(node)), - 0 <= index - ? (tag.splice(index, 1), - tag.push(node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [index], - [tag.length - 1], - [], - [], - [] - )) - : (tag.push(node), - ReactNativePrivateInterface.UIManager.manageChildren( - parent._nativeTag, - [], - [], - [before], - [tag.length - 1], - [] - )); - else if (4 !== tag && ((node = node.child), null !== node)) - for ( - insertOrAppendPlacementNode(node, before, parent), node = node.sibling; - null !== node; - - ) - insertOrAppendPlacementNode(node, before, parent), (node = node.sibling); -} -var hostParent = null, - hostParentIsContainer = !1; -function recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - parent -) { - for (parent = parent.child; null !== parent; ) - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), - (parent = parent.sibling); -} -function commitDeletionEffectsOnFiber( - finishedRoot, - nearestMountedAncestor, - deletedFiber -) { - if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) - try { - injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); - } catch (err) {} - switch (deletedFiber.tag) { - case 26: - case 27: - case 5: - offscreenSubtreeWasHidden || - safelyDetachRef(deletedFiber, nearestMountedAncestor); - case 6: - var prevHostParent = hostParent, - prevHostParentIsContainer = hostParentIsContainer; - hostParent = null; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - null !== hostParent && - (hostParentIsContainer - ? ((finishedRoot = hostParent), - recursivelyUncacheFiberNode(deletedFiber.stateNode), - ReactNativePrivateInterface.UIManager.manageChildren( - finishedRoot, - [], - [], - [], - [], - [0] - )) - : ((finishedRoot = hostParent), - (nearestMountedAncestor = deletedFiber.stateNode), - recursivelyUncacheFiberNode(nearestMountedAncestor), - (deletedFiber = finishedRoot._children), - (nearestMountedAncestor = deletedFiber.indexOf( - nearestMountedAncestor - )), - deletedFiber.splice(nearestMountedAncestor, 1), - ReactNativePrivateInterface.UIManager.manageChildren( - finishedRoot._nativeTag, - [], - [], - [], - [], - [nearestMountedAncestor] - ))); - break; - case 18: - null !== hostParent && shim$1(); - break; - case 4: - prevHostParent = hostParent; - prevHostParentIsContainer = hostParentIsContainer; - hostParent = deletedFiber.stateNode.containerInfo; - hostParentIsContainer = !0; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - break; - case 0: - case 11: - case 14: - case 15: - if ( - !offscreenSubtreeWasHidden && - ((prevHostParent = deletedFiber.updateQueue), - null !== prevHostParent && - ((prevHostParent = prevHostParent.lastEffect), - null !== prevHostParent)) - ) { - prevHostParentIsContainer = prevHostParent = prevHostParent.next; - do { - var tag = prevHostParentIsContainer.tag, - inst = prevHostParentIsContainer.inst, - destroy = inst.destroy; - void 0 !== destroy && - (0 !== (tag & 2) - ? ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )) - : 0 !== (tag & 4) && - (shouldProfile(deletedFiber) - ? (startLayoutEffectTimer(), - (inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - ), - recordLayoutEffectDuration(deletedFiber)) - : ((inst.destroy = void 0), - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy - )))); - prevHostParentIsContainer = prevHostParentIsContainer.next; - } while (prevHostParentIsContainer !== prevHostParent); + current = rootInstanceStackCursor.current; + renderLanes = allocateTag(); + type = getViewConfigForType(type); + var updatePayload = diffProperties( + null, + emptyObject, + newProps, + type.validAttributes + ); + ReactNativePrivateInterface.UIManager.createView( + renderLanes, + type.uiViewClassName, + current, + updatePayload + ); + current = new ReactNativeFiberHostComponent( + renderLanes, + type, + workInProgress + ); + instanceCache.set(renderLanes, workInProgress); + instanceProps.set(renderLanes, newProps); + a: for (renderLanes = workInProgress.child; null !== renderLanes; ) { + if (5 === renderLanes.tag || 6 === renderLanes.tag) + current._children.push(renderLanes.stateNode); + else if (4 !== renderLanes.tag && null !== renderLanes.child) { + renderLanes.child.return = renderLanes; + renderLanes = renderLanes.child; + continue; + } + if (renderLanes === workInProgress) break a; + for (; null === renderLanes.sibling; ) { + if ( + null === renderLanes.return || + renderLanes.return === workInProgress + ) + break a; + renderLanes = renderLanes.return; + } + renderLanes.sibling.return = renderLanes.return; + renderLanes = renderLanes.sibling; + } + workInProgress.stateNode = current; + finalizeInitialChildren(current) && (workInProgress.flags |= 4); } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 1: + bubbleProperties(workInProgress); + workInProgress.flags &= -16777217; + return null; + case 6: + if (current && null != workInProgress.stateNode) + current.memoizedProps !== newProps && (workInProgress.flags |= 4); + else { + if ("string" !== typeof newProps && null === workInProgress.stateNode) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + renderLanes = rootInstanceStackCursor.current; + if (!contextStackCursor.current.isInAParentText) + throw Error( + "Text strings must be rendered within a component." + ); + current = allocateTag(); + ReactNativePrivateInterface.UIManager.createView( + current, + "RCTRawText", + renderLanes, + { text: newProps } + ); + instanceCache.set(current, workInProgress); + workInProgress.stateNode = current; + } + bubbleProperties(workInProgress); + return null; + case 13: + newProps = workInProgress.memoizedState; if ( - !offscreenSubtreeWasHidden && - (safelyDetachRef(deletedFiber, nearestMountedAncestor), - (prevHostParent = deletedFiber.stateNode), - "function" === typeof prevHostParent.componentWillUnmount) - ) - try { - callComponentWillUnmountWithTimer(deletedFiber, prevHostParent); - } catch (error) { - captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + null === current || + (null !== current.memoizedState && + null !== current.memoizedState.dehydrated) + ) { + if (null !== newProps && null !== newProps.dehydrated) { + if (null === current) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + 0 === (workInProgress.flags & 128) && + (workInProgress.memoizedState = null); + workInProgress.flags |= 4; + bubbleProperties(workInProgress); + 0 !== (workInProgress.mode & 2) && + null !== newProps && + ((type = workInProgress.child), + null !== type && + (workInProgress.treeBaseDuration -= type.treeBaseDuration)); + type = !1; + } else + null !== hydrationErrors && + (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)), + (type = !0); + if (!type) { + if (workInProgress.flags & 256) + return popSuspenseHandler(workInProgress), workInProgress; + popSuspenseHandler(workInProgress); + return null; } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 21: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - case 22: - safelyDetachRef(deletedFiber, nearestMountedAncestor); - deletedFiber.mode & 1 - ? ((offscreenSubtreeWasHidden = - (prevHostParent = offscreenSubtreeWasHidden) || - null !== deletedFiber.memoizedState), - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ), - (offscreenSubtreeWasHidden = prevHostParent)) - : recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber - ); - break; - default: - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber + } + popSuspenseHandler(workInProgress); + if (0 !== (workInProgress.flags & 128)) + return ( + (workInProgress.lanes = renderLanes), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress + ); + renderLanes = null !== newProps; + renderLanes !== (null !== current && null !== current.memoizedState) && + renderLanes && + (workInProgress.child.flags |= 8192); + scheduleRetryEffect(workInProgress, workInProgress.updateQueue); + bubbleProperties(workInProgress); + 0 !== (workInProgress.mode & 2) && + renderLanes && + ((renderLanes = workInProgress.child), + null !== renderLanes && + (workInProgress.treeBaseDuration -= renderLanes.treeBaseDuration)); + return null; + case 4: + return popHostContainer(), bubbleProperties(workInProgress), null; + case 10: + return ( + popProvider(workInProgress.type._context), + bubbleProperties(workInProgress), + null ); - } -} -function getRetryCache(finishedWork) { - switch (finishedWork.tag) { - case 13: + case 17: + return bubbleProperties(workInProgress), null; case 19: - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); - return retryCache; + pop(suspenseStackCursor); + type = workInProgress.memoizedState; + if (null === type) return bubbleProperties(workInProgress), null; + newProps = 0 !== (workInProgress.flags & 128); + updatePayload = type.rendering; + if (null === updatePayload) + if (newProps) cutOffTailIfNeeded(type, !1); + else { + if ( + 0 !== workInProgressRootExitStatus || + (null !== current && 0 !== (current.flags & 128)) + ) + for (current = workInProgress.child; null !== current; ) { + updatePayload = findFirstSuspended(current); + if (null !== updatePayload) { + workInProgress.flags |= 128; + cutOffTailIfNeeded(type, !1); + current = updatePayload.updateQueue; + workInProgress.updateQueue = current; + scheduleRetryEffect(workInProgress, current); + workInProgress.subtreeFlags = 0; + for (current = workInProgress.child; null !== current; ) + resetWorkInProgress(current, renderLanes), + (current = current.sibling); + push( + suspenseStackCursor, + (suspenseStackCursor.current & 1) | 2 + ); + return workInProgress.child; + } + current = current.sibling; + } + null !== type.tail && + now$1() > workInProgressRootRenderTargetTime && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(type, !1), + (workInProgress.lanes = 4194304)); + } + else { + if (!newProps) + if ( + ((current = findFirstSuspended(updatePayload)), null !== current) + ) { + if ( + ((workInProgress.flags |= 128), + (newProps = !0), + (renderLanes = current.updateQueue), + (workInProgress.updateQueue = renderLanes), + scheduleRetryEffect(workInProgress, renderLanes), + cutOffTailIfNeeded(type, !0), + null === type.tail && + "hidden" === type.tailMode && + !updatePayload.alternate) + ) + return bubbleProperties(workInProgress), null; + } else + 2 * now$1() - type.renderingStartTime > + workInProgressRootRenderTargetTime && + 536870912 !== renderLanes && + ((workInProgress.flags |= 128), + (newProps = !0), + cutOffTailIfNeeded(type, !1), + (workInProgress.lanes = 4194304)); + type.isBackwards + ? ((updatePayload.sibling = workInProgress.child), + (workInProgress.child = updatePayload)) + : ((renderLanes = type.last), + null !== renderLanes + ? (renderLanes.sibling = updatePayload) + : (workInProgress.child = updatePayload), + (type.last = updatePayload)); + } + if (null !== type.tail) + return ( + (workInProgress = type.tail), + (type.rendering = workInProgress), + (type.tail = workInProgress.sibling), + (type.renderingStartTime = now$1()), + (workInProgress.sibling = null), + (renderLanes = suspenseStackCursor.current), + push( + suspenseStackCursor, + newProps ? (renderLanes & 1) | 2 : renderLanes & 1 + ), + workInProgress + ); + bubbleProperties(workInProgress); + return null; case 22: + case 23: return ( - (finishedWork = finishedWork.stateNode), - (retryCache = finishedWork._retryCache), - null === retryCache && - (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), - retryCache - ); - default: - throw Error( - "Unexpected Suspense handler tag (" + - finishedWork.tag + - "). This is a bug in React." + popSuspenseHandler(workInProgress), + popHiddenContext(), + (newProps = null !== workInProgress.memoizedState), + null !== current + ? (null !== current.memoizedState) !== newProps && + (workInProgress.flags |= 8192) + : newProps && (workInProgress.flags |= 8192), + newProps && 0 !== (workInProgress.mode & 1) + ? 0 !== (renderLanes & 536870912) && + 0 === (workInProgress.flags & 128) && + (bubbleProperties(workInProgress), + workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192)) + : bubbleProperties(workInProgress), + (renderLanes = workInProgress.updateQueue), + null !== renderLanes && + scheduleRetryEffect(workInProgress, renderLanes.retryQueue), + null ); + case 24: + return null; + case 25: + return null; } + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); } -function attachSuspenseRetryListeners(finishedWork, wakeables) { - var retryCache = getRetryCache(finishedWork); - wakeables.forEach(function (wakeable) { - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - if (isDevToolsPresent) - if (null !== inProgressLanes && null !== inProgressRoot) - restorePendingUpdaters(inProgressRoot, inProgressLanes); - else - throw Error( - "Expected finished root and lanes to be set. This is a bug in React." - ); - wakeable.then(retry, retry); - } - }); -} -function commitMutationEffects(root, finishedWork, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - commitMutationEffectsOnFiber(finishedWork, root); - inProgressRoot = inProgressLanes = null; -} -function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) { - var deletions = parentFiber.deletions; - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - try { - var root = root$jscomp$0, - returnFiber = parentFiber, - parent = returnFiber; - a: for (; null !== parent; ) { - switch (parent.tag) { - case 27: - case 5: - hostParent = parent.stateNode; - hostParentIsContainer = !1; - break a; - case 3: - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = !0; - break a; - case 4: - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = !0; - break a; - } - parent = parent.return; - } - if (null === hostParent) - throw Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); - commitDeletionEffectsOnFiber(root, returnFiber, childToDelete); - hostParent = null; - hostParentIsContainer = !1; - var alternate = childToDelete.alternate; - null !== alternate && (alternate.return = null); - childToDelete.return = null; - } catch (error) { - captureCommitPhaseError(childToDelete, parentFiber, error); - } - } - if (parentFiber.subtreeFlags & 12854) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), - (parentFiber = parentFiber.sibling); -} -function commitMutationEffectsOnFiber(finishedWork, root) { - var current = finishedWork.alternate, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - try { - commitHookEffectListUnmount(3, finishedWork, finishedWork.return), - commitHookEffectListMount(3, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(), - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$100) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$100 - ); - } - recordLayoutEffectDuration(finishedWork); - } else - try { - commitHookEffectListUnmount(5, finishedWork, finishedWork.return); - } catch (error$101) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$101 - ); - } - } - break; +function unwindWork(current, workInProgress) { + switch (workInProgress.tag) { case 1: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - flags & 64 && - offscreenSubtreeIsHidden && - ((finishedWork = finishedWork.updateQueue), - null !== finishedWork && - ((flags = finishedWork.callbacks), - null !== flags && - ((current = finishedWork.shared.hiddenCallbacks), - (finishedWork.shared.hiddenCallbacks = - null === current ? flags : current.concat(flags))))); - break; + return ( + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null + ); + case 3: + return ( + popHostContainer(), + (current = workInProgress.flags), + 0 !== (current & 65536) && 0 === (current & 128) + ? ((workInProgress.flags = (current & -65537) | 128), workInProgress) + : null + ); case 26: case 27: case 5: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 512 && + return popHostContext(workInProgress), null; + case 13: + popSuspenseHandler(workInProgress); + current = workInProgress.memoizedState; + if ( null !== current && - safelyDetachRef(current, current.return); - if (flags & 4 && ((flags = finishedWork.stateNode), null != flags)) { - var newProps = finishedWork.memoizedProps; - current = null !== current ? current.memoizedProps : newProps; - finishedWork.updateQueue = null; - try { - var viewConfig = flags.viewConfig; - instanceProps.set(flags._nativeTag, newProps); - var updatePayload = diffProperties( - null, - current, - newProps, - viewConfig.validAttributes - ); - null != updatePayload && - ReactNativePrivateInterface.UIManager.updateView( - flags._nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } catch (error$104) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$104); - } - } - break; - case 6: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - if (flags & 4) { - if (null === finishedWork.stateNode) - throw Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ); - flags = finishedWork.stateNode; - current = finishedWork.memoizedProps; - try { - ReactNativePrivateInterface.UIManager.updateView( - flags, - "RCTRawText", - { text: current } - ); - } catch (error$105) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$105); - } - } - break; + null !== current.dehydrated && + null === workInProgress.alternate + ) + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + current = workInProgress.flags; + return current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null; + case 19: + return pop(suspenseStackCursor), null; + case 4: + return popHostContainer(), null; + case 10: + return popProvider(workInProgress.type._context), null; + case 22: + case 23: + return ( + popSuspenseHandler(workInProgress), + popHiddenContext(), + (current = workInProgress.flags), + current & 65536 + ? ((workInProgress.flags = (current & -65537) | 128), + 0 !== (workInProgress.mode & 2) && + transferActualDuration(workInProgress), + workInProgress) + : null + ); + case 24: + return null; + case 25: + return null; + default: + return null; + } +} +function unwindInterruptedWork(current, interruptedWork) { + switch (interruptedWork.tag) { case 3: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); + break; + case 26: + case 27: + case 5: + popHostContext(interruptedWork); break; case 4: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); + popHostContainer(); break; case 13: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - finishedWork.child.flags & 8192 && - ((current = null !== current && null !== current.memoizedState), - null === finishedWork.memoizedState || - current || - (globalMostRecentFallbackTime = now$1())); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); + popSuspenseHandler(interruptedWork); + break; + case 19: + pop(suspenseStackCursor); + break; + case 10: + popProvider(interruptedWork.type._context); break; case 22: - flags & 512 && - null !== current && - safelyDetachRef(current, current.return); - viewConfig = null !== finishedWork.memoizedState; - updatePayload = null !== current && null !== current.memoizedState; - if (finishedWork.mode & 1) { - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, - prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || viewConfig; - offscreenSubtreeWasHidden = - prevOffscreenSubtreeWasHidden || updatePayload; - recursivelyTraverseMutationEffects(root, finishedWork); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - } else recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - root = finishedWork.stateNode; - root._current = finishedWork; - root._visibility &= -3; - root._visibility |= root._pendingVisibility & 2; - if ( - flags & 8192 && - ((root._visibility = viewConfig - ? root._visibility & -2 - : root._visibility | 1), - viewConfig && - ((root = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), - null === current || - updatePayload || - root || - (0 !== (finishedWork.mode & 1) && - recursivelyTraverseDisappearLayoutEffects(finishedWork))), - null === finishedWork.memoizedProps || - "manual" !== finishedWork.memoizedProps.mode) - ) - a: for (current = null, root = finishedWork; ; ) { - if (5 === root.tag) { - if (null === current) { - current = root; - try { - if (((newProps = root.stateNode), viewConfig)) { - var viewConfig$jscomp$0 = newProps.viewConfig; - var updatePayload$jscomp$0 = diffProperties( - null, - emptyObject, - { style: { display: "none" } }, - viewConfig$jscomp$0.validAttributes - ); - ReactNativePrivateInterface.UIManager.updateView( - newProps._nativeTag, - viewConfig$jscomp$0.uiViewClassName, - updatePayload$jscomp$0 - ); - } else { - var instance = root.stateNode, - props = root.memoizedProps, - viewConfig$jscomp$1 = instance.viewConfig, - prevProps = assign({}, props, { - style: [props.style, { display: "none" }] - }); - var updatePayload$jscomp$1 = diffProperties( - null, - prevProps, - props, - viewConfig$jscomp$1.validAttributes - ); - ReactNativePrivateInterface.UIManager.updateView( - instance._nativeTag, - viewConfig$jscomp$1.uiViewClassName, - updatePayload$jscomp$1 + case 23: + popSuspenseHandler(interruptedWork), popHiddenContext(); + } +} +var offscreenSubtreeIsHidden = !1, + offscreenSubtreeWasHidden = !1, + PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, + nextEffect = null, + inProgressLanes = null, + inProgressRoot = null; +function shouldProfile(current) { + return 0 !== (current.mode & 2) && 0 !== (executionContext & 4); +} +function callComponentWillUnmountWithTimer(current, instance) { + instance.props = current.memoizedProps; + instance.state = current.memoizedState; + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current); + } + else instance.componentWillUnmount(); +} +function safelyAttachRef(current, nearestMountedAncestor) { + try { + var ref = current.ref; + if (null !== ref) { + var instance = current.stateNode; + switch (current.tag) { + case 26: + case 27: + case 5: + var instanceToUse = getPublicInstance(instance); + break; + default: + instanceToUse = instance; + } + if ("function" === typeof ref) + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), (current.refCleanup = ref(instanceToUse)); + } finally { + recordLayoutEffectDuration(current); + } + else current.refCleanup = ref(instanceToUse); + else ref.current = instanceToUse; + } + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } +} +function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref, + refCleanup = current.refCleanup; + if (null !== ref) + if ("function" === typeof refCleanup) + try { + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), refCleanup(); + } finally { + recordLayoutEffectDuration(current); + } + else refCleanup(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } finally { + (current.refCleanup = null), + (current = current.alternate), + null != current && (current.refCleanup = null); + } + else if ("function" === typeof ref) + try { + if (shouldProfile(current)) + try { + startLayoutEffectTimer(), ref(null); + } finally { + recordLayoutEffectDuration(current); + } + else ref(null); + } catch (error$84) { + captureCommitPhaseError(current, nearestMountedAncestor, error$84); + } + else ref.current = null; +} +function safelyCallDestroy(current, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error) { + captureCommitPhaseError(current, nearestMountedAncestor, error); + } +} +var shouldFireAfterActiveInstanceBlur = !1; +function commitBeforeMutationEffects(root, firstChild) { + for (nextEffect = firstChild; null !== nextEffect; ) + if ( + ((root = nextEffect), + (firstChild = root.child), + 0 !== (root.subtreeFlags & 1028) && null !== firstChild) + ) + (firstChild.return = root), (nextEffect = firstChild); + else + for (; null !== nextEffect; ) { + root = nextEffect; + try { + var current = root.alternate, + flags = root.flags; + switch (root.tag) { + case 0: + break; + case 11: + case 15: + break; + case 1: + if (0 !== (flags & 1024) && null !== current) { + var prevProps = current.memoizedProps, + prevState = current.memoizedState, + instance = root.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + root.elementType === root.type + ? prevProps + : resolveDefaultProps(root.type, prevProps), + prevState ); - } - } catch (error) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error - ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; } - } - } else if (6 === root.tag) { - if (null === current) - try { - throw Error("Not yet implemented."); - } catch (error$94) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error$94 + break; + case 3: + break; + case 5: + case 26: + case 27: + case 6: + case 4: + case 17: + break; + default: + if (0 !== (flags & 1024)) + throw Error( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." ); - } - } else if ( - ((22 !== root.tag && 23 !== root.tag) || - null === root.memoizedState || - root === finishedWork) && - null !== root.child - ) { - root.child.return = root; - root = root.child; - continue; - } - if (root === finishedWork) break a; - for (; null === root.sibling; ) { - if (null === root.return || root.return === finishedWork) break a; - current === root && (current = null); - root = root.return; } - current === root && (current = null); - root.sibling.return = root.return; - root = root.sibling; + } catch (error) { + captureCommitPhaseError(root, root.return, error); } - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((current = flags.retryQueue), - null !== current && - ((flags.retryQueue = null), - attachSuspenseRetryListeners(finishedWork, current)))); - break; - case 19: - recursivelyTraverseMutationEffects(root, finishedWork); - commitReconciliationEffects(finishedWork); - flags & 4 && - ((flags = finishedWork.updateQueue), - null !== flags && - ((finishedWork.updateQueue = null), - attachSuspenseRetryListeners(finishedWork, flags))); - break; - case 21: - break; - default: - recursivelyTraverseMutationEffects(root, finishedWork), - commitReconciliationEffects(finishedWork); + firstChild = root.sibling; + if (null !== firstChild) { + firstChild.return = root.return; + nextEffect = firstChild; + break; + } + nextEffect = root.return; + } + current = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = !1; + return current; +} +function commitHookEffectListUnmount( + flags, + finishedWork, + nearestMountedAncestor +) { + var updateQueue = finishedWork.updateQueue; + updateQueue = null !== updateQueue ? updateQueue.lastEffect : null; + if (null !== updateQueue) { + var effect = (updateQueue = updateQueue.next); + do { + if ((effect.tag & flags) === flags) { + var inst = effect.inst, + destroy = inst.destroy; + void 0 !== destroy && + ((inst.destroy = void 0), + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy)); + } + effect = effect.next; + } while (effect !== updateQueue); } } -function commitReconciliationEffects(finishedWork) { - var flags = finishedWork.flags; - if (flags & 2) { +function commitHookEffectListMount(flags, finishedWork) { + finishedWork = finishedWork.updateQueue; + finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; + if (null !== finishedWork) { + var effect = (finishedWork = finishedWork.next); + do { + if ((effect.tag & flags) === flags) { + var create$85 = effect.create, + inst = effect.inst; + create$85 = create$85(); + inst.destroy = create$85; + } + effect = effect.next; + } while (effect !== finishedWork); + } +} +function commitHookLayoutEffects(finishedWork, hookFlags) { + if (shouldProfile(finishedWork)) { try { - a: { - for (var parent = finishedWork.return; null !== parent; ) { - if (isHostParent(parent)) { - var JSCompiler_inline_result = parent; + startLayoutEffectTimer(), + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error$87) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$87); + } +} +function commitClassCallbacks(finishedWork) { + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var instance = finishedWork.stateNode; + try { + commitCallbacks(updateQueue, instance); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + } +} +function commitProfilerUpdate(finishedWork, current) { + if (executionContext & 4) + try { + var _finishedWork$memoize2 = finishedWork.memoizedProps, + onCommit = _finishedWork$memoize2.onCommit, + onRender = _finishedWork$memoize2.onRender, + effectDuration = finishedWork.stateNode.effectDuration; + _finishedWork$memoize2 = commitTime; + current = null === current ? "mount" : "update"; + currentUpdateIsNested && (current = "nested-update"); + "function" === typeof onRender && + onRender( + finishedWork.memoizedProps.id, + current, + finishedWork.actualDuration, + finishedWork.treeBaseDuration, + finishedWork.actualStartTime, + _finishedWork$memoize2 + ); + "function" === typeof onCommit && + onCommit( + finishedWork.memoizedProps.id, + current, + effectDuration, + _finishedWork$memoize2 + ); + enqueuePendingPassiveProfilerEffect(finishedWork); + var parentFiber = finishedWork.return; + a: for (; null !== parentFiber; ) { + switch (parentFiber.tag) { + case 3: + parentFiber.stateNode.effectDuration += effectDuration; + break a; + case 12: + parentFiber.stateNode.effectDuration += effectDuration; break a; + } + parentFiber = parentFiber.return; + } + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } +} +function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) { + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitHookLayoutEffects(finishedWork, 5); + break; + case 1: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 4) + if (((finishedRoot = finishedWork.stateNode), null === current)) + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + finishedRoot.componentDidMount(); + } catch (error$88) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$88 + ); + } + else { + var prevProps = + finishedWork.elementType === finishedWork.type + ? current.memoizedProps + : resolveDefaultProps(finishedWork.type, current.memoizedProps); + current = current.memoizedState; + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$89) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$89 + ); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + finishedRoot.componentDidUpdate( + prevProps, + current, + finishedRoot.__reactInternalSnapshotBeforeUpdate + ); + } catch (error$90) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$90 + ); + } + } + flags & 64 && commitClassCallbacks(finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); + break; + case 3: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) { + finishedRoot = null; + if (null !== finishedWork.child) + switch (finishedWork.child.tag) { + case 27: + case 5: + finishedRoot = getPublicInstance(finishedWork.child.stateNode); + break; + case 1: + finishedRoot = finishedWork.child.stateNode; } - parent = parent.return; + try { + commitCallbacks(flags, finishedRoot); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } - throw Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - switch (JSCompiler_inline_result.tag) { - case 27: - case 5: - var parent$jscomp$0 = JSCompiler_inline_result.stateNode; - JSCompiler_inline_result.flags & 32 && - (JSCompiler_inline_result.flags &= -33); - var before = getHostSibling(finishedWork); - insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0); - break; - case 3: - case 4: - var parent$95 = JSCompiler_inline_result.stateNode.containerInfo, - before$96 = getHostSibling(finishedWork); - insertOrAppendPlacementNodeIntoContainer( - finishedWork, - before$96, - parent$95 - ); - break; - default: - throw Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ); } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - finishedWork.flags &= -3; - } - flags & 4096 && (finishedWork.flags &= -4097); -} -function commitLayoutEffects(finishedWork, root, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); - inProgressRoot = inProgressLanes = null; -} -function recursivelyTraverseLayoutEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 8772) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), - (parentFiber = parentFiber.sibling); -} -function recursivelyTraverseDisappearLayoutEffects(parentFiber) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 14: - case 15: - if (shouldProfile(finishedWork)) - try { - startLayoutEffectTimer(), - commitHookEffectListUnmount(4, finishedWork, finishedWork.return); - } finally { - recordLayoutEffectDuration(finishedWork); - } - else commitHookEffectListUnmount(4, finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 1: - safelyDetachRef(finishedWork, finishedWork.return); - var instance = finishedWork.stateNode; - if ("function" === typeof instance.componentWillUnmount) { - var current = finishedWork, - nearestMountedAncestor = finishedWork.return; - try { - callComponentWillUnmountWithTimer(current, instance); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } + break; + case 26: + case 27: + case 5: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && safelyAttachRef(finishedWork, finishedWork.return); + break; + case 12: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 4 && commitProfilerUpdate(finishedWork, current); + break; + case 13: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + break; + case 22: + if (0 !== (finishedWork.mode & 1)) { + if ( + ((prevProps = + null !== finishedWork.memoizedState || offscreenSubtreeIsHidden), + !prevProps) + ) { + current = + (null !== current && null !== current.memoizedState) || + offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevProps; + (offscreenSubtreeWasHidden = current) && + !prevOffscreenSubtreeWasHidden + ? recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + 0 !== (finishedWork.subtreeFlags & 8772) + ) + : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 26: - case 27: - case 5: - safelyDetachRef(finishedWork, finishedWork.return); - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - case 22: - safelyDetachRef(finishedWork, finishedWork.return); - null === finishedWork.memoizedState && - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - default: - recursivelyTraverseDisappearLayoutEffects(finishedWork); - } - parentFiber = parentFiber.sibling; + } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); + flags & 512 && + ("manual" === finishedWork.memoizedProps.mode + ? safelyAttachRef(finishedWork, finishedWork.return) + : safelyDetachRef(finishedWork, finishedWork.return)); + break; + default: + recursivelyTraverseLayoutEffects(finishedRoot, finishedWork); } } -function recursivelyTraverseReappearLayoutEffects( - finishedRoot$jscomp$0, - parentFiber, - includeWorkInProgressEffects -) { - includeWorkInProgressEffects = - includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var current = parentFiber.alternate, - finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber, - flags = finishedWork.flags; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - commitHookLayoutEffects(finishedWork, 4); - break; - case 1: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - finishedRoot = finishedWork.stateNode; - if ("function" === typeof finishedRoot.componentDidMount) - try { - finishedRoot.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - current = finishedWork.updateQueue; - if (null !== current) { - var hiddenCallbacks = current.shared.hiddenCallbacks; - if (null !== hiddenCallbacks) - for ( - current.shared.hiddenCallbacks = null, current = 0; - current < hiddenCallbacks.length; - current++ - ) - callCallback(hiddenCallbacks[current], finishedRoot); - } - includeWorkInProgressEffects && - flags & 64 && - commitClassCallbacks(finishedWork); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 26: - case 27: - case 5: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - case 12: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - includeWorkInProgressEffects && - flags & 4 && - commitProfilerUpdate(finishedWork, current); - break; - case 13: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - break; - case 22: - null === finishedWork.memoizedState && - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - safelyAttachRef(finishedWork, finishedWork.return); - break; - default: - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects - ); - } - parentFiber = parentFiber.sibling; - } +function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; + null !== alternate && + ((fiber.alternate = null), detachFiberAfterEffects(alternate)); + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + fiber.stateNode = null; + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; } -function commitHookPassiveMountEffects(finishedWork, hookFlags) { - if (shouldProfile(finishedWork)) { - passiveEffectStartTime = now(); - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); +function isHostParent(fiber) { + return 5 === fiber.tag || 3 === fiber.tag || 4 === fiber.tag; +} +function getHostSibling(fiber) { + a: for (;;) { + for (; null === fiber.sibling; ) { + if (null === fiber.return || isHostParent(fiber.return)) return null; + fiber = fiber.return; } - recordPassiveEffectDuration(finishedWork); - } else - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error$109) { - captureCommitPhaseError(finishedWork, finishedWork.return, error$109); + fiber.sibling.return = fiber.return; + for ( + fiber = fiber.sibling; + 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; + + ) { + if (fiber.flags & 2) continue a; + if (null === fiber.child || 4 === fiber.tag) continue a; + else (fiber.child.return = fiber), (fiber = fiber.child); } + if (!(fiber.flags & 2)) return fiber.stateNode; + } } -function recursivelyTraversePassiveMountEffects(root, parentFiber) { - if (parentFiber.subtreeFlags & 10256) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveMountOnFiber(root, parentFiber), - (parentFiber = parentFiber.sibling); +function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { + var tag = node.tag; + if (5 === tag || 6 === tag) + if (((node = node.stateNode), before)) { + if ("number" === typeof parent) + throw Error("Container does not support insertBefore operation"); + } else + ReactNativePrivateInterface.UIManager.setChildren(parent, [ + "number" === typeof node ? node : node._nativeTag + ]); + else if (4 !== tag && ((node = node.child), null !== node)) + for ( + insertOrAppendPlacementNodeIntoContainer(node, before, parent), + node = node.sibling; + null !== node; + + ) + insertOrAppendPlacementNodeIntoContainer(node, before, parent), + (node = node.sibling); } -function commitPassiveMountOnFiber(finishedRoot, finishedWork) { - var flags = finishedWork.flags; - switch (finishedWork.tag) { +function insertOrAppendPlacementNode(node, before, parent) { + var tag = node.tag; + if (5 === tag || 6 === tag) + if (((node = node.stateNode), before)) { + tag = parent._children; + var index = tag.indexOf(node); + 0 <= index + ? (tag.splice(index, 1), + (before = tag.indexOf(before)), + tag.splice(before, 0, node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [index], + [before], + [], + [], + [] + )) + : ((before = tag.indexOf(before)), + tag.splice(before, 0, node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [], + [], + ["number" === typeof node ? node : node._nativeTag], + [before], + [] + )); + } else + (before = "number" === typeof node ? node : node._nativeTag), + (tag = parent._children), + (index = tag.indexOf(node)), + 0 <= index + ? (tag.splice(index, 1), + tag.push(node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [index], + [tag.length - 1], + [], + [], + [] + )) + : (tag.push(node), + ReactNativePrivateInterface.UIManager.manageChildren( + parent._nativeTag, + [], + [], + [before], + [tag.length - 1], + [] + )); + else if (4 !== tag && ((node = node.child), null !== node)) + for ( + insertOrAppendPlacementNode(node, before, parent), node = node.sibling; + null !== node; + + ) + insertOrAppendPlacementNode(node, before, parent), (node = node.sibling); +} +var hostParent = null, + hostParentIsContainer = !1; +function recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + parent +) { + for (parent = parent.child; null !== parent; ) + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), + (parent = parent.sibling); +} +function commitDeletionEffectsOnFiber( + finishedRoot, + nearestMountedAncestor, + deletedFiber +) { + if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount) + try { + injectedHook.onCommitFiberUnmount(rendererID, deletedFiber); + } catch (err) {} + switch (deletedFiber.tag) { + case 26: + case 27: + case 5: + offscreenSubtreeWasHidden || + safelyDetachRef(deletedFiber, nearestMountedAncestor); + case 6: + var prevHostParent = hostParent, + prevHostParentIsContainer = hostParentIsContainer; + hostParent = null; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; + null !== hostParent && + (hostParentIsContainer + ? ((finishedRoot = hostParent), + recursivelyUncacheFiberNode(deletedFiber.stateNode), + ReactNativePrivateInterface.UIManager.manageChildren( + finishedRoot, + [], + [], + [], + [], + [0] + )) + : ((finishedRoot = hostParent), + (nearestMountedAncestor = deletedFiber.stateNode), + recursivelyUncacheFiberNode(nearestMountedAncestor), + (deletedFiber = finishedRoot._children), + (nearestMountedAncestor = deletedFiber.indexOf( + nearestMountedAncestor + )), + deletedFiber.splice(nearestMountedAncestor, 1), + ReactNativePrivateInterface.UIManager.manageChildren( + finishedRoot._nativeTag, + [], + [], + [], + [], + [nearestMountedAncestor] + ))); + break; + case 18: + null !== hostParent && shim$1(); + break; + case 4: + prevHostParent = hostParent; + prevHostParentIsContainer = hostParentIsContainer; + hostParent = deletedFiber.stateNode.containerInfo; + hostParentIsContainer = !0; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; + break; case 0: case 11: + case 14: case 15: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + if ( + !offscreenSubtreeWasHidden && + ((prevHostParent = deletedFiber.updateQueue), + null !== prevHostParent && + ((prevHostParent = prevHostParent.lastEffect), + null !== prevHostParent)) + ) { + prevHostParentIsContainer = prevHostParent = prevHostParent.next; + do { + var tag = prevHostParentIsContainer.tag, + inst = prevHostParentIsContainer.inst, + destroy = inst.destroy; + void 0 !== destroy && + (0 !== (tag & 2) + ? ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )) + : 0 !== (tag & 4) && + (shouldProfile(deletedFiber) + ? (startLayoutEffectTimer(), + (inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + ), + recordLayoutEffectDuration(deletedFiber)) + : ((inst.destroy = void 0), + safelyCallDestroy( + deletedFiber, + nearestMountedAncestor, + destroy + )))); + prevHostParentIsContainer = prevHostParentIsContainer.next; + } while (prevHostParentIsContainer !== prevHostParent); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; - case 3: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + case 1: + if ( + !offscreenSubtreeWasHidden && + (safelyDetachRef(deletedFiber, nearestMountedAncestor), + (prevHostParent = deletedFiber.stateNode), + "function" === typeof prevHostParent.componentWillUnmount) + ) + try { + callComponentWillUnmountWithTimer(deletedFiber, prevHostParent); + } catch (error) { + captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error); + } + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; - case 23: + case 21: + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; case 22: - flags = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : finishedWork.mode & 1 || - ((flags._visibility |= 4), - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) - : flags._visibility & 4 - ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) - : ((flags._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( + safelyDetachRef(deletedFiber, nearestMountedAncestor); + deletedFiber.mode & 1 + ? ((offscreenSubtreeWasHidden = + (prevHostParent = offscreenSubtreeWasHidden) || + null !== deletedFiber.memoizedState), + recursivelyTraverseDeletionEffects( finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + nearestMountedAncestor, + deletedFiber + ), + (offscreenSubtreeWasHidden = prevHostParent)) + : recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); break; default: - recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); - } -} -function recursivelyTraverseReconnectPassiveEffects( - finishedRoot$jscomp$0, - parentFiber -) { - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - var finishedRoot = finishedRoot$jscomp$0, - finishedWork = parentFiber; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - commitHookPassiveMountEffects(finishedWork, 8); - break; - case 23: - break; - case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState - ? instance._visibility & 4 - ? recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - ) - : finishedWork.mode & 1 || - ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )) - : ((instance._visibility |= 4), - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork - )); - break; - case 24: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - break; - default: - recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); - } - parentFiber = parentFiber.sibling; + recursivelyTraverseDeletionEffects( + finishedRoot, + nearestMountedAncestor, + deletedFiber + ); } } -var suspenseyCommitFlag = 8192; -function recursivelyAccumulateSuspenseyCommit(parentFiber) { - if (parentFiber.subtreeFlags & suspenseyCommitFlag) - for (parentFiber = parentFiber.child; null !== parentFiber; ) - accumulateSuspenseyCommitOnFiber(parentFiber), - (parentFiber = parentFiber.sibling); -} -function accumulateSuspenseyCommitOnFiber(fiber) { - switch (fiber.tag) { - case 26: - recursivelyAccumulateSuspenseyCommit(fiber); - if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) - throw Error( - "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." - ); - break; - case 5: - recursivelyAccumulateSuspenseyCommit(fiber); - break; - case 3: - case 4: - recursivelyAccumulateSuspenseyCommit(fiber); - break; +function getRetryCache(finishedWork) { + switch (finishedWork.tag) { + case 13: + case 19: + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); + return retryCache; case 22: - if (null === fiber.memoizedState) { - var current = fiber.alternate; - null !== current && null !== current.memoizedState - ? ((current = suspenseyCommitFlag), - (suspenseyCommitFlag = 16777216), - recursivelyAccumulateSuspenseyCommit(fiber), - (suspenseyCommitFlag = current)) - : recursivelyAccumulateSuspenseyCommit(fiber); - } - break; + return ( + (finishedWork = finishedWork.stateNode), + (retryCache = finishedWork._retryCache), + null === retryCache && + (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), + retryCache + ); default: - recursivelyAccumulateSuspenseyCommit(fiber); + throw Error( + "Unexpected Suspense handler tag (" + + finishedWork.tag + + "). This is a bug in React." + ); } } -function detachAlternateSiblings(parentFiber) { - var previousFiber = parentFiber.alternate; - if ( - null !== previousFiber && - ((parentFiber = previousFiber.child), null !== parentFiber) - ) { - previousFiber.child = null; - do - (previousFiber = parentFiber.sibling), - (parentFiber.sibling = null), - (parentFiber = previousFiber); - while (null !== parentFiber); - } +function attachSuspenseRetryListeners(finishedWork, wakeables) { + var retryCache = getRetryCache(finishedWork); + wakeables.forEach(function (wakeable) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); + if (isDevToolsPresent) + if (null !== inProgressLanes && null !== inProgressRoot) + restorePendingUpdaters(inProgressRoot, inProgressLanes); + else + throw Error( + "Expected finished root and lanes to be set. This is a bug in React." + ); + wakeable.then(retry, retry); + } + }); } -function commitHookPassiveUnmountEffects( - finishedWork, - nearestMountedAncestor, - hookFlags -) { - shouldProfile(finishedWork) - ? ((passiveEffectStartTime = now()), - commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor - ), - recordPassiveEffectDuration(finishedWork)) - : commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor - ); +function commitMutationEffects(root, finishedWork, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + commitMutationEffectsOnFiber(finishedWork, root); + inProgressRoot = inProgressLanes = null; } -function recursivelyTraversePassiveUnmountEffects(parentFiber) { +function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) { var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - if (parentFiber.subtreeFlags & 10256) + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + var root = root$jscomp$0, + returnFiber = parentFiber, + parent = returnFiber; + a: for (; null !== parent; ) { + switch (parent.tag) { + case 27: + case 5: + hostParent = parent.stateNode; + hostParentIsContainer = !1; + break a; + case 3: + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = !0; + break a; + case 4: + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = !0; + break a; + } + parent = parent.return; + } + if (null === hostParent) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + commitDeletionEffectsOnFiber(root, returnFiber, childToDelete); + hostParent = null; + hostParentIsContainer = !1; + var alternate = childToDelete.alternate; + null !== alternate && (alternate.return = null); + childToDelete.return = null; + } catch (error) { + captureCommitPhaseError(childToDelete, parentFiber, error); + } + } + if (parentFiber.subtreeFlags & 12854) for (parentFiber = parentFiber.child; null !== parentFiber; ) - commitPassiveUnmountOnFiber(parentFiber), + commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), (parentFiber = parentFiber.sibling); } -function commitPassiveUnmountOnFiber(finishedWork) { +function commitMutationEffectsOnFiber(finishedWork, root) { + var current = finishedWork.alternate, + flags = finishedWork.flags; switch (finishedWork.tag) { case 0: case 11: + case 14: case 15: - recursivelyTraversePassiveUnmountEffects(finishedWork); - finishedWork.flags & 2048 && - commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, 9); - break; - case 22: - var instance = finishedWork.stateNode; - null !== finishedWork.memoizedState && - instance._visibility & 4 && - (null === finishedWork.return || 13 !== finishedWork.return.tag) - ? ((instance._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(finishedWork)) - : recursivelyTraversePassiveUnmountEffects(finishedWork); - break; - default: - recursivelyTraversePassiveUnmountEffects(finishedWork); - } -} -function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { - var deletions = parentFiber.deletions; - if (0 !== (parentFiber.flags & 16)) { - if (null !== deletions) - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber - ); - } - detachAlternateSiblings(parentFiber); - } - for (parentFiber = parentFiber.child; null !== parentFiber; ) { - deletions = parentFiber; - switch (deletions.tag) { - case 0: - case 11: - case 15: - commitHookPassiveUnmountEffects(deletions, deletions.return, 8); - recursivelyTraverseDisconnectPassiveEffects(deletions); - break; - case 22: - i = deletions.stateNode; - i._visibility & 4 && - ((i._visibility &= -5), - recursivelyTraverseDisconnectPassiveEffects(deletions)); - break; - default: - recursivelyTraverseDisconnectPassiveEffects(deletions); - } - parentFiber = parentFiber.sibling; - } -} -function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - deletedSubtreeRoot, - nearestMountedAncestor -) { - for (; null !== nextEffect; ) { - var fiber = nextEffect; - switch (fiber.tag) { - case 0: - case 11: - case 15: - commitHookPassiveUnmountEffects(fiber, nearestMountedAncestor, 8); - } - var child = fiber.child; - if (null !== child) (child.return = fiber), (nextEffect = child); - else - a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { - child = nextEffect; - var sibling = child.sibling, - returnFiber = child.return; - detachFiberAfterEffects(child); - if (child === fiber) { - nextEffect = null; - break a; - } - if (null !== sibling) { - sibling.return = returnFiber; - nextEffect = sibling; - break a; + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + try { + commitHookEffectListUnmount(3, finishedWork, finishedWork.return), + commitHookEffectListMount(3, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); } - nextEffect = returnFiber; + if (shouldProfile(finishedWork)) { + try { + startLayoutEffectTimer(), + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$99) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$99 + ); + } + recordLayoutEffectDuration(finishedWork); + } else + try { + commitHookEffectListUnmount(5, finishedWork, finishedWork.return); + } catch (error$100) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$100 + ); + } } - } -} -var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, - ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, - executionContext = 0, - workInProgressRoot = null, - workInProgress = null, - workInProgressRootRenderLanes = 0, - workInProgressSuspendedReason = 0, - workInProgressThrownValue = null, - workInProgressRootDidAttachPingListener = !1, - entangledRenderLanes = 0, - workInProgressRootExitStatus = 0, - workInProgressRootFatalError = null, - workInProgressRootSkippedLanes = 0, - workInProgressRootInterleavedUpdatedLanes = 0, - workInProgressRootPingedLanes = 0, - workInProgressDeferredLane = 0, - workInProgressRootConcurrentErrors = null, - workInProgressRootRecoverableErrors = null, - globalMostRecentFallbackTime = 0, - workInProgressRootRenderTargetTime = Infinity, - workInProgressTransitions = null, - hasUncaughtError = !1, - firstUncaughtError = null, - legacyErrorBoundariesThatAlreadyFailed = null, - rootDoesHavePassiveEffects = !1, - rootWithPendingPassiveEffects = null, - pendingPassiveEffectsLanes = 0, - pendingPassiveProfilerEffects = [], - nestedUpdateCount = 0, - rootWithNestedUpdates = null; -function requestUpdateLane(fiber) { - if (0 === (fiber.mode & 1)) return 2; - if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) - return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; - fiber = ReactCurrentBatchConfig$1.transition; - null !== fiber && fiber._callbacks.add(handleAsyncAction); - if (null !== fiber) - return ( - 0 === currentEventTransitionLane && - (currentEventTransitionLane = claimNextTransitionLane()), - currentEventTransitionLane - ); - fiber = currentUpdatePriority; - return 0 !== fiber ? fiber : 32; -} -function requestDeferredLane() { - 0 === workInProgressDeferredLane && - (workInProgressDeferredLane = - 0 !== (workInProgressRootRenderLanes & 536870912) - ? 536870912 - : claimNextTransitionLane()); - var suspenseHandler = suspenseHandlerStackCursor.current; - null !== suspenseHandler && (suspenseHandler.flags |= 32); - return workInProgressDeferredLane; -} -function scheduleUpdateOnFiber(root, fiber, lane) { - if ( - (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || - null !== root.cancelPendingCommit - ) - prepareFreshStack(root, 0), - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); - markRootUpdated(root, lane); - if (0 === (executionContext & 2) || root !== workInProgressRoot) - isDevToolsPresent && addFiberToLanesMap(root, fiber, lane), - root === workInProgressRoot && - (0 === (executionContext & 2) && - (workInProgressRootInterleavedUpdatedLanes |= lane), - 4 === workInProgressRootExitStatus && - markRootSuspended( - root, - workInProgressRootRenderLanes, - workInProgressDeferredLane - )), - ensureRootIsScheduled(root), - 2 === lane && - 0 === executionContext && - 0 === (fiber.mode & 1) && - ((workInProgressRootRenderTargetTime = now$1() + 500), - flushSyncWorkAcrossRoots_impl(!0)); -} -function performConcurrentWorkOnRoot(root, didTimeout) { - nestedUpdateScheduled = currentUpdateIsNested = !1; - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var originalCallbackNode = root.callbackNode; - if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) - return null; - var lanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : 0 - ); - if (0 === lanes) return null; - var exitStatus = (didTimeout = - 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) - ? renderRootConcurrent(root, lanes) - : renderRootSync(root, lanes); - if (0 !== exitStatus) { - var renderWasConcurrent = didTimeout; - do { - if (6 === exitStatus) markRootSuspended(root, lanes, 0); - else { - didTimeout = root.current.alternate; - if ( - renderWasConcurrent && - !isRenderConsistentWithExternalStores(didTimeout) - ) { - exitStatus = renderRootSync(root, lanes); - renderWasConcurrent = !1; - continue; - } - if (2 === exitStatus) { - renderWasConcurrent = lanes; - var errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - renderWasConcurrent + break; + case 1: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + flags & 64 && + offscreenSubtreeIsHidden && + ((finishedWork = finishedWork.updateQueue), + null !== finishedWork && + ((flags = finishedWork.callbacks), + null !== flags && + ((current = finishedWork.shared.hiddenCallbacks), + (finishedWork.shared.hiddenCallbacks = + null === current ? flags : current.concat(flags))))); + break; + case 26: + case 27: + case 5: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + if (flags & 4 && ((flags = finishedWork.stateNode), null != flags)) { + var newProps = finishedWork.memoizedProps; + current = null !== current ? current.memoizedProps : newProps; + finishedWork.updateQueue = null; + try { + var viewConfig = flags.viewConfig; + instanceProps.set(flags._nativeTag, newProps); + var updatePayload = diffProperties( + null, + current, + newProps, + viewConfig.validAttributes ); - 0 !== errorRetryLanes && - ((lanes = errorRetryLanes), - (exitStatus = recoverFromConcurrentError( - root, - renderWasConcurrent, - errorRetryLanes - ))); + null != updatePayload && + ReactNativePrivateInterface.UIManager.updateView( + flags._nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } catch (error$103) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$103); } - if (1 === exitStatus) - throw ( - ((originalCallbackNode = workInProgressRootFatalError), - prepareFreshStack(root, 0), - markRootSuspended(root, lanes, 0), - ensureRootIsScheduled(root), - originalCallbackNode) + } + break; + case 6: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & 4) { + if (null === finishedWork.stateNode) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." ); - root.finishedWork = didTimeout; - root.finishedLanes = lanes; - a: { - renderWasConcurrent = root; - switch (exitStatus) { - case 0: - case 1: - throw Error("Root did not complete. This is a bug in React."); - case 4: - if ((lanes & 4194176) === lanes) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane + flags = finishedWork.stateNode; + current = finishedWork.memoizedProps; + try { + ReactNativePrivateInterface.UIManager.updateView( + flags, + "RCTRawText", + { text: current } + ); + } catch (error$104) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$104); + } + } + break; + case 3: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 4: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + break; + case 13: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + finishedWork.child.flags & 8192 && + ((current = null !== current && null !== current.memoizedState), + null === finishedWork.memoizedState || + current || + (globalMostRecentFallbackTime = now$1())); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 22: + flags & 512 && + null !== current && + safelyDetachRef(current, current.return); + viewConfig = null !== finishedWork.memoizedState; + updatePayload = null !== current && null !== current.memoizedState; + if (finishedWork.mode & 1) { + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, + prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || viewConfig; + offscreenSubtreeWasHidden = + prevOffscreenSubtreeWasHidden || updatePayload; + recursivelyTraverseMutationEffects(root, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + } else recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + root = finishedWork.stateNode; + root._current = finishedWork; + root._visibility &= -3; + root._visibility |= root._pendingVisibility & 2; + if ( + flags & 8192 && + ((root._visibility = viewConfig + ? root._visibility & -2 + : root._visibility | 1), + viewConfig && + ((root = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden), + null === current || + updatePayload || + root || + (0 !== (finishedWork.mode & 1) && + recursivelyTraverseDisappearLayoutEffects(finishedWork))), + null === finishedWork.memoizedProps || + "manual" !== finishedWork.memoizedProps.mode) + ) + a: for (current = null, root = finishedWork; ; ) { + if (5 === root.tag) { + if (null === current) { + current = root; + try { + if (((newProps = root.stateNode), viewConfig)) { + var viewConfig$jscomp$0 = newProps.viewConfig; + var updatePayload$jscomp$0 = diffProperties( + null, + emptyObject, + { style: { display: "none" } }, + viewConfig$jscomp$0.validAttributes + ); + ReactNativePrivateInterface.UIManager.updateView( + newProps._nativeTag, + viewConfig$jscomp$0.uiViewClassName, + updatePayload$jscomp$0 + ); + } else { + var instance = root.stateNode, + props = root.memoizedProps, + viewConfig$jscomp$1 = instance.viewConfig, + prevProps = assign({}, props, { + style: [props.style, { display: "none" }] + }); + var updatePayload$jscomp$1 = diffProperties( + null, + prevProps, + props, + viewConfig$jscomp$1.validAttributes + ); + ReactNativePrivateInterface.UIManager.updateView( + instance._nativeTag, + viewConfig$jscomp$1.uiViewClassName, + updatePayload$jscomp$1 + ); + } + } catch (error) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error ); - break a; } - break; - case 2: - case 3: - case 5: - break; - default: - throw Error("Unknown root exit status."); - } - if ( - (lanes & 62914560) === lanes && - 3 === exitStatus && - ((exitStatus = globalMostRecentFallbackTime + 300 - now$1()), - 10 < exitStatus) + } + } else if (6 === root.tag) { + if (null === current) + try { + throw Error("Not yet implemented."); + } catch (error$93) { + captureCommitPhaseError( + finishedWork, + finishedWork.return, + error$93 + ); + } + } else if ( + ((22 !== root.tag && 23 !== root.tag) || + null === root.memoizedState || + root === finishedWork) && + null !== root.child ) { - markRootSuspended( - renderWasConcurrent, - lanes, - workInProgressDeferredLane - ); - if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; - renderWasConcurrent.timeoutHandle = scheduleTimeout( - commitRootWhenReady.bind( - null, - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ), - exitStatus - ); + root.child.return = root; + root = root.child; + continue; + } + if (root === finishedWork) break a; + for (; null === root.sibling; ) { + if (null === root.return || root.return === finishedWork) break a; + current === root && (current = null); + root = root.return; + } + current === root && (current = null); + root.sibling.return = root.return; + root = root.sibling; + } + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((current = flags.retryQueue), + null !== current && + ((flags.retryQueue = null), + attachSuspenseRetryListeners(finishedWork, current)))); + break; + case 19: + recursivelyTraverseMutationEffects(root, finishedWork); + commitReconciliationEffects(finishedWork); + flags & 4 && + ((flags = finishedWork.updateQueue), + null !== flags && + ((finishedWork.updateQueue = null), + attachSuspenseRetryListeners(finishedWork, flags))); + break; + case 21: + break; + default: + recursivelyTraverseMutationEffects(root, finishedWork), + commitReconciliationEffects(finishedWork); + } +} +function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + if (flags & 2) { + try { + a: { + for (var parent = finishedWork.return; null !== parent; ) { + if (isHostParent(parent)) { + var JSCompiler_inline_result = parent; break a; } - commitRootWhenReady( - renderWasConcurrent, - didTimeout, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - lanes, - workInProgressDeferredLane - ); + parent = parent.return; } + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); } - break; - } while (1); - } - ensureRootIsScheduled(root); - scheduleTaskForRootDuringMicrotask(root, now$1()); - root = - root.callbackNode === originalCallbackNode - ? performConcurrentWorkOnRoot.bind(null, root) - : null; - return root; -} -function recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes -) { - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, - JSCompiler_inline_result; - (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && - (prepareFreshStack(root, errorRetryLanes).flags |= 256); - errorRetryLanes = renderRootSync(root, errorRetryLanes); - if (2 !== errorRetryLanes) { - if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) - return ( - (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), - (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), - 4 - ); - root = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - null !== root && queueRecoverableErrors(root); + switch (JSCompiler_inline_result.tag) { + case 27: + case 5: + var parent$jscomp$0 = JSCompiler_inline_result.stateNode; + JSCompiler_inline_result.flags & 32 && + (JSCompiler_inline_result.flags &= -33); + var before = getHostSibling(finishedWork); + insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0); + break; + case 3: + case 4: + var parent$94 = JSCompiler_inline_result.stateNode.containerInfo, + before$95 = getHostSibling(finishedWork); + insertOrAppendPlacementNodeIntoContainer( + finishedWork, + before$95, + parent$94 + ); + break; + default: + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + finishedWork.flags &= -3; } - return errorRetryLanes; + flags & 4096 && (finishedWork.flags &= -4097); } -function queueRecoverableErrors(errors) { - null === workInProgressRootRecoverableErrors - ? (workInProgressRootRecoverableErrors = errors) - : workInProgressRootRecoverableErrors.push.apply( - workInProgressRootRecoverableErrors, - errors - ); +function commitLayoutEffects(finishedWork, root, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork); + inProgressRoot = inProgressLanes = null; } -function commitRootWhenReady( - root, - finishedWork, - recoverableErrors, - transitions, - lanes, - spawnedLane -) { - 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); - commitRoot(root, recoverableErrors, transitions, spawnedLane); +function recursivelyTraverseLayoutEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 8772) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), + (parentFiber = parentFiber.sibling); } -function isRenderConsistentWithExternalStores(finishedWork) { - for (var node = finishedWork; ; ) { - if (node.flags & 16384) { - var updateQueue = node.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.stores), null !== updateQueue) - ) - for (var i = 0; i < updateQueue.length; i++) { - var check = updateQueue[i], - getSnapshot = check.getSnapshot; - check = check.value; +function recursivelyTraverseDisappearLayoutEffects(parentFiber) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 14: + case 15: + if (shouldProfile(finishedWork)) try { - if (!objectIs(getSnapshot(), check)) return !1; + startLayoutEffectTimer(), + commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + else commitHookEffectListUnmount(4, finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 1: + safelyDetachRef(finishedWork, finishedWork.return); + var instance = finishedWork.stateNode; + if ("function" === typeof instance.componentWillUnmount) { + var current = finishedWork, + nearestMountedAncestor = finishedWork.return; + try { + callComponentWillUnmountWithTimer(current, instance); } catch (error) { - return !1; + captureCommitPhaseError(current, nearestMountedAncestor, error); } } + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 26: + case 27: + case 5: + safelyDetachRef(finishedWork, finishedWork.return); + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + case 22: + safelyDetachRef(finishedWork, finishedWork.return); + null === finishedWork.memoizedState && + recursivelyTraverseDisappearLayoutEffects(finishedWork); + break; + default: + recursivelyTraverseDisappearLayoutEffects(finishedWork); } - updateQueue = node.child; - if (node.subtreeFlags & 16384 && null !== updateQueue) - (updateQueue.return = node), (node = updateQueue); - else { - if (node === finishedWork) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === finishedWork) return !0; - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; + parentFiber = parentFiber.sibling; + } +} +function recursivelyTraverseReappearLayoutEffects( + finishedRoot$jscomp$0, + parentFiber, + includeWorkInProgressEffects +) { + includeWorkInProgressEffects = + includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772); + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var current = parentFiber.alternate, + finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber, + flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + commitHookLayoutEffects(finishedWork, 4); + break; + case 1: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + finishedRoot = finishedWork.stateNode; + if ("function" === typeof finishedRoot.componentDidMount) + try { + finishedRoot.componentDidMount(); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + current = finishedWork.updateQueue; + if (null !== current) { + var hiddenCallbacks = current.shared.hiddenCallbacks; + if (null !== hiddenCallbacks) + for ( + current.shared.hiddenCallbacks = null, current = 0; + current < hiddenCallbacks.length; + current++ + ) + callCallback(hiddenCallbacks[current], finishedRoot); + } + includeWorkInProgressEffects && + flags & 64 && + commitClassCallbacks(finishedWork); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 26: + case 27: + case 5: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + case 12: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + includeWorkInProgressEffects && + flags & 4 && + commitProfilerUpdate(finishedWork, current); + break; + case 13: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + break; + case 22: + null === finishedWork.memoizedState && + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); + safelyAttachRef(finishedWork, finishedWork.return); + break; + default: + recursivelyTraverseReappearLayoutEffects( + finishedRoot, + finishedWork, + includeWorkInProgressEffects + ); } - } - return !0; -} -function markRootSuspended(root, suspendedLanes, spawnedLane) { - suspendedLanes &= ~workInProgressRootPingedLanes; - suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - for ( - var expirationTimes = root.expirationTimes, lanes = suspendedLanes; - 0 < lanes; - - ) { - var index$6 = 31 - clz32(lanes), - lane = 1 << index$6; - expirationTimes[index$6] = -1; - lanes &= ~lane; - } - 0 !== spawnedLane && - markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); -} -function resetWorkInProgressStack() { - if (null !== workInProgress) { - if (0 === workInProgressSuspendedReason) - var interruptedWork = workInProgress.return; - else - (interruptedWork = workInProgress), - resetContextDependencies(), - resetHooksOnUnwind(interruptedWork), - (thenableState$1 = null), - (thenableIndexCounter$1 = 0), - (interruptedWork = workInProgress); - for (; null !== interruptedWork; ) - unwindInterruptedWork(interruptedWork.alternate, interruptedWork), - (interruptedWork = interruptedWork.return); - workInProgress = null; + parentFiber = parentFiber.sibling; } } -function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = 0; - var timeoutHandle = root.timeoutHandle; - -1 !== timeoutHandle && - ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); - timeoutHandle = root.cancelPendingCommit; - null !== timeoutHandle && - ((root.cancelPendingCommit = null), timeoutHandle()); - resetWorkInProgressStack(); - workInProgressRoot = root; - workInProgress = timeoutHandle = createWorkInProgress(root.current, null); - workInProgressRootRenderLanes = lanes; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - workInProgressRootDidAttachPingListener = !1; - workInProgressRootExitStatus = 0; - workInProgressRootFatalError = null; - workInProgressDeferredLane = - workInProgressRootPingedLanes = - workInProgressRootInterleavedUpdatedLanes = - workInProgressRootSkippedLanes = - 0; - workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = - null; - 0 !== (lanes & 8) && (lanes |= lanes & 32); - var allEntangledLanes = root.entangledLanes; - if (0 !== allEntangledLanes) - for ( - root = root.entanglements, allEntangledLanes &= lanes; - 0 < allEntangledLanes; - - ) { - var index$4 = 31 - clz32(allEntangledLanes), - lane = 1 << index$4; - lanes |= root[index$4]; - allEntangledLanes &= ~lane; +function commitHookPassiveMountEffects(finishedWork, hookFlags) { + if (shouldProfile(finishedWork)) { + passiveEffectStartTime = now(); + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error) { + captureCommitPhaseError(finishedWork, finishedWork.return, error); + } + recordPassiveEffectDuration(finishedWork); + } else + try { + commitHookEffectListMount(hookFlags, finishedWork); + } catch (error$108) { + captureCommitPhaseError(finishedWork, finishedWork.return, error$108); } - entangledRenderLanes = lanes; - finishQueueingConcurrentUpdates(); - return timeoutHandle; -} -function handleThrow(root, thrownValue) { - currentlyRenderingFiber$1 = null; - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - ReactCurrentOwner.current = null; - thrownValue === SuspenseException - ? ((thrownValue = getSuspendedThenable()), - (root = suspenseHandlerStackCursor.current), - (workInProgressSuspendedReason = - (null !== root && - ((workInProgressRootRenderLanes & 4194176) === - workInProgressRootRenderLanes - ? null !== shellBoundary - : ((workInProgressRootRenderLanes & 62914560) !== - workInProgressRootRenderLanes && - 0 === (workInProgressRootRenderLanes & 536870912)) || - root !== shellBoundary)) || - 0 !== (workInProgressRootSkippedLanes & 134217727) || - 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) - ? 3 - : 2)) - : thrownValue === SuspenseyCommitException - ? ((thrownValue = getSuspendedThenable()), - (workInProgressSuspendedReason = 4)) - : (workInProgressSuspendedReason = - thrownValue === SelectiveHydrationException - ? 8 - : null !== thrownValue && - "object" === typeof thrownValue && - "function" === typeof thrownValue.then - ? 6 - : 1); - workInProgressThrownValue = thrownValue; - root = workInProgress; - null === root - ? ((workInProgressRootExitStatus = 1), - (workInProgressRootFatalError = thrownValue)) - : root.mode & 2 && stopProfilerTimerIfRunningAndRecordDelta(root, !0); } -function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +function recursivelyTraversePassiveMountEffects(root, parentFiber) { + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveMountOnFiber(root, parentFiber), + (parentFiber = parentFiber.sibling); } -function renderDidSuspendDelayIfPossible() { - workInProgressRootExitStatus = 4; - (0 === (workInProgressRootSkippedLanes & 134217727) && - 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || - null === workInProgressRoot || - markRootSuspended( - workInProgressRoot, - workInProgressRootRenderLanes, - workInProgressDeferredLane - ); +function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + flags & 2048 && commitHookPassiveMountEffects(finishedWork, 9); + break; + case 3: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + case 23: + break; + case 22: + flags = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : finishedWork.mode & 1 || + ((flags._visibility |= 4), + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork)) + : flags._visibility & 4 + ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork) + : ((flags._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork); + } } -function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - 0 < memoizedUpdaters.size && - (restorePendingUpdaters(root, workInProgressRootRenderLanes), - memoizedUpdaters.clear()); - movePendingFibersToMemoized(root, lanes); +function recursivelyTraverseReconnectPassiveEffects( + finishedRoot$jscomp$0, + parentFiber +) { + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + var finishedRoot = finishedRoot$jscomp$0, + finishedWork = parentFiber; + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + commitHookPassiveMountEffects(finishedWork, 8); + break; + case 23: + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState + ? instance._visibility & 4 + ? recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + ) + : finishedWork.mode & 1 || + ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )) + : ((instance._visibility |= 4), + recursivelyTraverseReconnectPassiveEffects( + finishedRoot, + finishedWork + )); + break; + case 24: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); + break; + default: + recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork); } - workInProgressTransitions = null; - prepareFreshStack(root, lanes); + parentFiber = parentFiber.sibling; } - lanes = !1; - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) { - memoizedUpdaters = workInProgress; - var thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - case 3: - case 2: - lanes || - null !== suspenseHandlerStackCursor.current || - (lanes = !0); - default: - (workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, memoizedUpdaters, thrownValue); - } +} +var suspenseyCommitFlag = 8192; +function recursivelyAccumulateSuspenseyCommit(parentFiber) { + if (parentFiber.subtreeFlags & suspenseyCommitFlag) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + accumulateSuspenseyCommitOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); +} +function accumulateSuspenseyCommitOnFiber(fiber) { + switch (fiber.tag) { + case 26: + recursivelyAccumulateSuspenseyCommit(fiber); + if (fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState) + throw Error( + "The current renderer does not support Resources. This error is likely caused by a bug in React. Please file an issue." + ); + break; + case 5: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 3: + case 4: + recursivelyAccumulateSuspenseyCommit(fiber); + break; + case 22: + if (null === fiber.memoizedState) { + var current = fiber.alternate; + null !== current && null !== current.memoizedState + ? ((current = suspenseyCommitFlag), + (suspenseyCommitFlag = 16777216), + recursivelyAccumulateSuspenseyCommit(fiber), + (suspenseyCommitFlag = current)) + : recursivelyAccumulateSuspenseyCommit(fiber); } - workLoopSync(); break; - } catch (thrownValue$110) { - handleThrow(root, thrownValue$110); - } - while (1); - lanes && root.shellSuspendCounter++; - resetContextDependencies(); - executionContext = prevExecutionContext; - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - throw Error( - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; + default: + recursivelyAccumulateSuspenseyCommit(fiber); + } } -function workLoopSync() { - for (; null !== workInProgress; ) performUnitOfWork(workInProgress); +function detachAlternateSiblings(parentFiber) { + var previousFiber = parentFiber.alternate; + if ( + null !== previousFiber && + ((parentFiber = previousFiber.child), null !== parentFiber) + ) { + previousFiber.child = null; + do + (previousFiber = parentFiber.sibling), + (parentFiber.sibling = null), + (parentFiber = previousFiber); + while (null !== parentFiber); + } } -function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= 2; - var prevDispatcher = pushDispatcher(); - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - 0 < memoizedUpdaters.size && - (restorePendingUpdaters(root, workInProgressRootRenderLanes), - memoizedUpdaters.clear()); - movePendingFibersToMemoized(root, lanes); - } - workInProgressTransitions = null; - workInProgressRootRenderTargetTime = now$1() + 500; - prepareFreshStack(root, lanes); +function commitHookPassiveUnmountEffects( + finishedWork, + nearestMountedAncestor, + hookFlags +) { + shouldProfile(finishedWork) + ? ((passiveEffectStartTime = now()), + commitHookEffectListUnmount( + hookFlags, + finishedWork, + nearestMountedAncestor + ), + recordPassiveEffectDuration(finishedWork)) + : commitHookEffectListUnmount( + hookFlags, + finishedWork, + nearestMountedAncestor + ); +} +function recursivelyTraversePassiveUnmountEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); + } + detachAlternateSiblings(parentFiber); } - a: do - try { - if (0 !== workInProgressSuspendedReason && null !== workInProgress) - b: switch ( - ((lanes = workInProgress), - (memoizedUpdaters = workInProgressThrownValue), - workInProgressSuspendedReason) - ) { - case 1: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 2: - if (isThenableResolved(memoizedUpdaters)) { - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(lanes); - break; - } - lanes = function () { - 2 === workInProgressSuspendedReason && - workInProgressRoot === root && - (workInProgressSuspendedReason = 7); - ensureRootIsScheduled(root); - }; - memoizedUpdaters.then(lanes, lanes); - break a; - case 3: - workInProgressSuspendedReason = 7; - break a; - case 4: - workInProgressSuspendedReason = 5; - break a; - case 7: - isThenableResolved(memoizedUpdaters) - ? ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - replaySuspendedUnitOfWork(lanes)) - : ((workInProgressSuspendedReason = 0), - (workInProgressThrownValue = null), - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters)); - break; - case 5: - switch (workInProgress.tag) { - case 5: - case 26: - case 27: - lanes = workInProgress; - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - var sibling = lanes.sibling; - if (null !== sibling) workInProgress = sibling; - else { - var returnFiber = lanes.return; - null !== returnFiber - ? ((workInProgress = returnFiber), - completeUnitOfWork(returnFiber)) - : (workInProgress = null); - } - break b; - } - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 6: - workInProgressSuspendedReason = 0; - workInProgressThrownValue = null; - throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); - break; - case 8: - resetWorkInProgressStack(); - workInProgressRootExitStatus = 6; - break a; - default: - throw Error("Unexpected SuspendedReason. This is a bug in React."); - } - workLoopConcurrent(); + if (parentFiber.subtreeFlags & 10256) + for (parentFiber = parentFiber.child; null !== parentFiber; ) + commitPassiveUnmountOnFiber(parentFiber), + (parentFiber = parentFiber.sibling); +} +function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + recursivelyTraversePassiveUnmountEffects(finishedWork); + finishedWork.flags & 2048 && + commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, 9); + break; + case 22: + var instance = finishedWork.stateNode; + null !== finishedWork.memoizedState && + instance._visibility & 4 && + (null === finishedWork.return || 13 !== finishedWork.return.tag) + ? ((instance._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(finishedWork)) + : recursivelyTraversePassiveUnmountEffects(finishedWork); break; - } catch (thrownValue$112) { - handleThrow(root, thrownValue$112); + default: + recursivelyTraversePassiveUnmountEffects(finishedWork); + } +} +function recursivelyTraverseDisconnectPassiveEffects(parentFiber) { + var deletions = parentFiber.deletions; + if (0 !== (parentFiber.flags & 16)) { + if (null !== deletions) + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; + nextEffect = childToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + childToDelete, + parentFiber + ); + } + detachAlternateSiblings(parentFiber); + } + for (parentFiber = parentFiber.child; null !== parentFiber; ) { + deletions = parentFiber; + switch (deletions.tag) { + case 0: + case 11: + case 15: + commitHookPassiveUnmountEffects(deletions, deletions.return, 8); + recursivelyTraverseDisconnectPassiveEffects(deletions); + break; + case 22: + i = deletions.stateNode; + i._visibility & 4 && + ((i._visibility &= -5), + recursivelyTraverseDisconnectPassiveEffects(deletions)); + break; + default: + recursivelyTraverseDisconnectPassiveEffects(deletions); } - while (1); - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - executionContext = prevExecutionContext; - if (null !== workInProgress) return 0; - workInProgressRoot = null; - workInProgressRootRenderLanes = 0; - finishQueueingConcurrentUpdates(); - return workInProgressRootExitStatus; + parentFiber = parentFiber.sibling; + } } -function workLoopConcurrent() { - for (; null !== workInProgress && !shouldYield(); ) - performUnitOfWork(workInProgress); +function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( + deletedSubtreeRoot, + nearestMountedAncestor +) { + for (; null !== nextEffect; ) { + var fiber = nextEffect; + switch (fiber.tag) { + case 0: + case 11: + case 15: + commitHookPassiveUnmountEffects(fiber, nearestMountedAncestor, 8); + } + var child = fiber.child; + if (null !== child) (child.return = fiber), (nextEffect = child); + else + a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) { + child = nextEffect; + var sibling = child.sibling, + returnFiber = child.return; + detachFiberAfterEffects(child); + if (child === fiber) { + nextEffect = null; + break a; + } + if (null !== sibling) { + sibling.return = returnFiber; + nextEffect = sibling; + break a; + } + nextEffect = returnFiber; + } + } } -function performUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate; - 0 !== (unitOfWork.mode & 2) - ? (startProfilerTimer(unitOfWork), - (current = beginWork(current, unitOfWork, entangledRenderLanes)), - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0)) - : (current = beginWork(current, unitOfWork, entangledRenderLanes)); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; +var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig, + executionContext = 0, + workInProgressRoot = null, + workInProgress = null, + workInProgressRootRenderLanes = 0, + workInProgressSuspendedReason = 0, + workInProgressThrownValue = null, + workInProgressRootDidAttachPingListener = !1, + entangledRenderLanes = 0, + workInProgressRootExitStatus = 0, + workInProgressRootFatalError = null, + workInProgressRootSkippedLanes = 0, + workInProgressRootInterleavedUpdatedLanes = 0, + workInProgressRootPingedLanes = 0, + workInProgressDeferredLane = 0, + workInProgressRootConcurrentErrors = null, + workInProgressRootRecoverableErrors = null, + workInProgressRootDidIncludeRecursiveRenderUpdate = !1, + globalMostRecentFallbackTime = 0, + workInProgressRootRenderTargetTime = Infinity, + workInProgressTransitions = null, + hasUncaughtError = !1, + firstUncaughtError = null, + legacyErrorBoundariesThatAlreadyFailed = null, + rootDoesHavePassiveEffects = !1, + rootWithPendingPassiveEffects = null, + pendingPassiveEffectsLanes = 0, + pendingPassiveProfilerEffects = [], + nestedUpdateCount = 0, + rootWithNestedUpdates = null; +function requestUpdateLane(fiber) { + if (0 === (fiber.mode & 1)) return 2; + if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes) + return workInProgressRootRenderLanes & -workInProgressRootRenderLanes; + fiber = ReactCurrentBatchConfig$1.transition; + null !== fiber && fiber._callbacks.add(handleAsyncAction); + if (null !== fiber) + return ( + 0 === currentEventTransitionLane && + (currentEventTransitionLane = claimNextTransitionLane()), + currentEventTransitionLane + ); + fiber = currentUpdatePriority; + return 0 !== fiber ? fiber : 32; } -function replaySuspendedUnitOfWork(unitOfWork) { - var current = unitOfWork.alternate, - isProfilingMode = 0 !== (unitOfWork.mode & 2); - isProfilingMode && startProfilerTimer(unitOfWork); - switch (unitOfWork.tag) { - case 2: - unitOfWork.tag = 0; - case 15: - case 0: - var Component = unitOfWork.type, - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - var context = isContextProvider(Component) - ? previousContext - : contextStackCursor$1.current; - context = getMaskedContext(unitOfWork, context); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - context, - workInProgressRootRenderLanes +function requestDeferredLane() { + 0 === workInProgressDeferredLane && + (workInProgressDeferredLane = + 0 !== (workInProgressRootRenderLanes & 536870912) + ? 536870912 + : claimNextTransitionLane()); + var suspenseHandler = suspenseHandlerStackCursor.current; + null !== suspenseHandler && (suspenseHandler.flags |= 32); + return workInProgressDeferredLane; +} +function scheduleUpdateOnFiber(root, fiber, lane) { + if ( + (root === workInProgressRoot && 2 === workInProgressSuspendedReason) || + null !== root.cancelPendingCommit + ) + prepareFreshStack(root, 0), + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane ); + markRootUpdated$1(root, lane); + if (0 === (executionContext & 2) || root !== workInProgressRoot) + isDevToolsPresent && addFiberToLanesMap(root, fiber, lane), + root === workInProgressRoot && + (0 === (executionContext & 2) && + (workInProgressRootInterleavedUpdatedLanes |= lane), + 4 === workInProgressRootExitStatus && + markRootSuspended( + root, + workInProgressRootRenderLanes, + workInProgressDeferredLane + )), + ensureRootIsScheduled(root), + 2 === lane && + 0 === executionContext && + 0 === (fiber.mode & 1) && + ((workInProgressRootRenderTargetTime = now$1() + 500), + flushSyncWorkAcrossRoots_impl(!0)); +} +function performConcurrentWorkOnRoot(root, didTimeout) { + nestedUpdateScheduled = currentUpdateIsNested = !1; + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + var originalCallbackNode = root.callbackNode; + if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode) + return null; + var lanes = getNextLanes( + root, + root === workInProgressRoot ? workInProgressRootRenderLanes : 0 + ); + if (0 === lanes) return null; + var exitStatus = (didTimeout = + 0 === (lanes & 60) && 0 === (lanes & root.expiredLanes) && !didTimeout) + ? renderRootConcurrent(root, lanes) + : renderRootSync(root, lanes); + if (0 !== exitStatus) { + var renderWasConcurrent = didTimeout; + do { + if (6 === exitStatus) markRootSuspended(root, lanes, 0); + else { + didTimeout = root.current.alternate; + if ( + renderWasConcurrent && + !isRenderConsistentWithExternalStores(didTimeout) + ) { + exitStatus = renderRootSync(root, lanes); + renderWasConcurrent = !1; + continue; + } + if (2 === exitStatus) { + renderWasConcurrent = lanes; + var errorRetryLanes = getLanesToRetrySynchronouslyOnError( + root, + renderWasConcurrent + ); + 0 !== errorRetryLanes && + ((lanes = errorRetryLanes), + (exitStatus = recoverFromConcurrentError( + root, + renderWasConcurrent, + errorRetryLanes + ))); + } + if (1 === exitStatus) + throw ( + ((originalCallbackNode = workInProgressRootFatalError), + prepareFreshStack(root, 0), + markRootSuspended(root, lanes, 0), + ensureRootIsScheduled(root), + originalCallbackNode) + ); + root.finishedWork = didTimeout; + root.finishedLanes = lanes; + a: { + renderWasConcurrent = root; + switch (exitStatus) { + case 0: + case 1: + throw Error("Root did not complete. This is a bug in React."); + case 4: + if ((lanes & 4194176) === lanes) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + break a; + } + break; + case 2: + case 3: + case 5: + break; + default: + throw Error("Unknown root exit status."); + } + if ( + (lanes & 62914560) === lanes && + 3 === exitStatus && + ((exitStatus = globalMostRecentFallbackTime + 300 - now$1()), + 10 < exitStatus) + ) { + markRootSuspended( + renderWasConcurrent, + lanes, + workInProgressDeferredLane + ); + if (0 !== getNextLanes(renderWasConcurrent, 0)) break a; + renderWasConcurrent.timeoutHandle = scheduleTimeout( + commitRootWhenReady.bind( + null, + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ), + exitStatus + ); + break a; + } + commitRootWhenReady( + renderWasConcurrent, + didTimeout, + workInProgressRootRecoverableErrors, + workInProgressTransitions, + workInProgressRootDidIncludeRecursiveRenderUpdate, + lanes, + workInProgressDeferredLane + ); + } + } break; - case 11: - Component = unitOfWork.type.render; - unresolvedProps = unitOfWork.pendingProps; - unresolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - current = replayFunctionComponent( - current, - unitOfWork, - unresolvedProps, - Component, - unitOfWork.ref, - workInProgressRootRenderLanes + } while (1); + } + ensureRootIsScheduled(root); + scheduleTaskForRootDuringMicrotask(root, now$1()); + root = + root.callbackNode === originalCallbackNode + ? performConcurrentWorkOnRoot.bind(null, root) + : null; + return root; +} +function recoverFromConcurrentError( + root, + originallyAttemptedLanes, + errorRetryLanes +) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors, + JSCompiler_inline_result; + (JSCompiler_inline_result = root.current.memoizedState.isDehydrated) && + (prepareFreshStack(root, errorRetryLanes).flags |= 256); + errorRetryLanes = renderRootSync(root, errorRetryLanes); + if (2 !== errorRetryLanes) { + if (workInProgressRootDidAttachPingListener && !JSCompiler_inline_result) + return ( + (root.errorRecoveryDisabledLanes |= originallyAttemptedLanes), + (workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes), + 4 ); - break; - case 5: - resetHooksOnUnwind(unitOfWork); - default: - unwindInterruptedWork(current, unitOfWork), - (unitOfWork = workInProgress = - resetWorkInProgress(unitOfWork, entangledRenderLanes)), - (current = beginWork(current, unitOfWork, entangledRenderLanes)); + root = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + null !== root && queueRecoverableErrors(root); } - isProfilingMode && stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - null === current - ? completeUnitOfWork(unitOfWork) - : (workInProgress = current); - ReactCurrentOwner.current = null; + return errorRetryLanes; } -function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { - resetContextDependencies(); - resetHooksOnUnwind(unitOfWork); - thenableState$1 = null; - thenableIndexCounter$1 = 0; - var returnFiber = unitOfWork.return; - try { - if ( - throwException( - root, - returnFiber, - unitOfWork, - thrownValue, - workInProgressRootRenderLanes +function queueRecoverableErrors(errors) { + null === workInProgressRootRecoverableErrors + ? (workInProgressRootRecoverableErrors = errors) + : workInProgressRootRecoverableErrors.push.apply( + workInProgressRootRecoverableErrors, + errors + ); +} +function commitRootWhenReady( + root, + finishedWork, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + lanes, + spawnedLane +) { + 0 === (lanes & 42) && accumulateSuspenseyCommitOnFiber(finishedWork); + commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane + ); +} +function isRenderConsistentWithExternalStores(finishedWork) { + for (var node = finishedWork; ; ) { + if (node.flags & 16384) { + var updateQueue = node.updateQueue; + if ( + null !== updateQueue && + ((updateQueue = updateQueue.stores), null !== updateQueue) ) - ) { - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - } catch (error) { - if (null !== returnFiber) throw ((workInProgress = returnFiber), error); - workInProgressRootExitStatus = 1; - workInProgressRootFatalError = thrownValue; - workInProgress = null; - return; - } - if (unitOfWork.flags & 32768) - a: { - root = unitOfWork; - do { - unitOfWork = unwindWork(root.alternate, root); - if (null !== unitOfWork) { - unitOfWork.flags &= 32767; - workInProgress = unitOfWork; - break a; - } - if (0 !== (root.mode & 2)) { - stopProfilerTimerIfRunningAndRecordDelta(root, !1); - unitOfWork = root.actualDuration; - for (thrownValue = root.child; null !== thrownValue; ) - (unitOfWork += thrownValue.actualDuration), - (thrownValue = thrownValue.sibling); - root.actualDuration = unitOfWork; + for (var i = 0; i < updateQueue.length; i++) { + var check = updateQueue[i], + getSnapshot = check.getSnapshot; + check = check.value; + try { + if (!objectIs(getSnapshot(), check)) return !1; + } catch (error) { + return !1; + } } - root = root.return; - null !== root && - ((root.flags |= 32768), - (root.subtreeFlags = 0), - (root.deletions = null)); - workInProgress = root; - } while (null !== root); - workInProgressRootExitStatus = 6; - workInProgress = null; - } - else completeUnitOfWork(unitOfWork); -} -function completeUnitOfWork(unitOfWork) { - var completedWork = unitOfWork; - do { - var current = completedWork.alternate; - unitOfWork = completedWork.return; - 0 === (completedWork.mode & 2) - ? (current = completeWork(current, completedWork, entangledRenderLanes)) - : (startProfilerTimer(completedWork), - (current = completeWork(current, completedWork, entangledRenderLanes)), - stopProfilerTimerIfRunningAndRecordDelta(completedWork, !1)); - if (null !== current) { - workInProgress = current; - return; } - completedWork = completedWork.sibling; - if (null !== completedWork) { - workInProgress = completedWork; - return; + updateQueue = node.child; + if (node.subtreeFlags & 16384 && null !== updateQueue) + (updateQueue.return = node), (node = updateQueue); + else { + if (node === finishedWork) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return !0; + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; } - workInProgress = completedWork = unitOfWork; - } while (null !== completedWork); - 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); + } + return !0; } -function commitRoot(root, recoverableErrors, transitions, spawnedLane) { - var previousUpdateLanePriority = currentUpdatePriority, - prevTransition = ReactCurrentBatchConfig.transition; - try { - (ReactCurrentBatchConfig.transition = null), - (currentUpdatePriority = 2), - commitRootImpl( - root, - recoverableErrors, - transitions, - previousUpdateLanePriority, - spawnedLane - ); - } finally { - (ReactCurrentBatchConfig.transition = prevTransition), - (currentUpdatePriority = previousUpdateLanePriority); +function markRootSuspended(root, suspendedLanes, spawnedLane) { + suspendedLanes &= ~workInProgressRootPingedLanes; + suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes; + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; + for ( + var expirationTimes = root.expirationTimes, lanes = suspendedLanes; + 0 < lanes; + + ) { + var index$6 = 31 - clz32(lanes), + lane = 1 << index$6; + expirationTimes[index$6] = -1; + lanes &= ~lane; + } + 0 !== spawnedLane && + markSpawnedDeferredLane(root, spawnedLane, suspendedLanes); +} +function resetWorkInProgressStack() { + if (null !== workInProgress) { + if (0 === workInProgressSuspendedReason) + var interruptedWork = workInProgress.return; + else + (interruptedWork = workInProgress), + resetContextDependencies(), + resetHooksOnUnwind(interruptedWork), + (thenableState$1 = null), + (thenableIndexCounter$1 = 0), + (interruptedWork = workInProgress); + for (; null !== interruptedWork; ) + unwindInterruptedWork(interruptedWork.alternate, interruptedWork), + (interruptedWork = interruptedWork.return); + workInProgress = null; } - return null; } -function commitRootImpl( - root, - recoverableErrors, - transitions, - renderPriorityLevel, - spawnedLane -) { - do flushPassiveEffects(); - while (null !== rootWithPendingPassiveEffects); - if (0 !== (executionContext & 6)) - throw Error("Should not already be working."); - var finishedWork = root.finishedWork; - transitions = root.finishedLanes; - if (null === finishedWork) return null; +function prepareFreshStack(root, lanes) { root.finishedWork = null; root.finishedLanes = 0; - if (finishedWork === root.current) - throw Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ); - root.callbackNode = null; - root.callbackPriority = 0; - root.cancelPendingCommit = null; - var remainingLanes = finishedWork.lanes | finishedWork.childLanes; - remainingLanes |= concurrentlyUpdatedLanes; - markRootFinished(root, remainingLanes, spawnedLane); - root === workInProgressRoot && - ((workInProgress = workInProgressRoot = null), - (workInProgressRootRenderLanes = 0)); - (0 === (finishedWork.subtreeFlags & 10256) && - 0 === (finishedWork.flags & 10256)) || - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); - spawnedLane = 0 !== (finishedWork.flags & 15990); - if (0 !== (finishedWork.subtreeFlags & 15990) || spawnedLane) { - spawnedLane = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = null; - remainingLanes = currentUpdatePriority; - currentUpdatePriority = 2; - var prevExecutionContext = executionContext; - executionContext |= 4; - ReactCurrentOwner.current = null; - commitBeforeMutationEffects(root, finishedWork); - commitTime = now(); - commitMutationEffects(root, finishedWork, transitions); - root.current = finishedWork; - commitLayoutEffects(finishedWork, root, transitions); - requestPaint(); - executionContext = prevExecutionContext; - currentUpdatePriority = remainingLanes; - ReactCurrentBatchConfig.transition = spawnedLane; - } else (root.current = finishedWork), (commitTime = now()); - rootDoesHavePassiveEffects && - ((rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsLanes = transitions)); - remainingLanes = root.pendingLanes; - 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - isDevToolsPresent && root.memoizedUpdaters.clear(); - ensureRootIsScheduled(root); - if (null !== recoverableErrors) + var timeoutHandle = root.timeoutHandle; + -1 !== timeoutHandle && + ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle)); + timeoutHandle = root.cancelPendingCommit; + null !== timeoutHandle && + ((root.cancelPendingCommit = null), timeoutHandle()); + resetWorkInProgressStack(); + workInProgressRoot = root; + workInProgress = timeoutHandle = createWorkInProgress(root.current, null); + workInProgressRootRenderLanes = lanes; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + workInProgressRootDidAttachPingListener = !1; + workInProgressRootExitStatus = 0; + workInProgressRootFatalError = null; + workInProgressDeferredLane = + workInProgressRootPingedLanes = + workInProgressRootInterleavedUpdatedLanes = + workInProgressRootSkippedLanes = + 0; + workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = + null; + workInProgressRootDidIncludeRecursiveRenderUpdate = !1; + 0 !== (lanes & 8) && (lanes |= lanes & 32); + var allEntangledLanes = root.entangledLanes; + if (0 !== allEntangledLanes) for ( - renderPriorityLevel = root.onRecoverableError, finishedWork = 0; - finishedWork < recoverableErrors.length; - finishedWork++ - ) - (spawnedLane = recoverableErrors[finishedWork]), - (remainingLanes = { - digest: spawnedLane.digest, - componentStack: spawnedLane.stack - }), - renderPriorityLevel(spawnedLane.value, remainingLanes); - if (hasUncaughtError) - throw ( - ((hasUncaughtError = !1), - (root = firstUncaughtError), - (firstUncaughtError = null), - root) + root = root.entanglements, allEntangledLanes &= lanes; + 0 < allEntangledLanes; + + ) { + var index$4 = 31 - clz32(allEntangledLanes), + lane = 1 << index$4; + lanes |= root[index$4]; + allEntangledLanes &= ~lane; + } + entangledRenderLanes = lanes; + finishQueueingConcurrentUpdates(); + return timeoutHandle; +} +function handleThrow(root, thrownValue) { + currentlyRenderingFiber$1 = null; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentOwner.current = null; + thrownValue === SuspenseException + ? ((thrownValue = getSuspendedThenable()), + (root = suspenseHandlerStackCursor.current), + (workInProgressSuspendedReason = + (null !== root && + ((workInProgressRootRenderLanes & 4194176) === + workInProgressRootRenderLanes + ? null !== shellBoundary + : ((workInProgressRootRenderLanes & 62914560) !== + workInProgressRootRenderLanes && + 0 === (workInProgressRootRenderLanes & 536870912)) || + root !== shellBoundary)) || + 0 !== (workInProgressRootSkippedLanes & 134217727) || + 0 !== (workInProgressRootInterleavedUpdatedLanes & 134217727) + ? 3 + : 2)) + : thrownValue === SuspenseyCommitException + ? ((thrownValue = getSuspendedThenable()), + (workInProgressSuspendedReason = 4)) + : (workInProgressSuspendedReason = + thrownValue === SelectiveHydrationException + ? 8 + : null !== thrownValue && + "object" === typeof thrownValue && + "function" === typeof thrownValue.then + ? 6 + : 1); + workInProgressThrownValue = thrownValue; + root = workInProgress; + null === root + ? ((workInProgressRootExitStatus = 1), + (workInProgressRootFatalError = thrownValue)) + : root.mode & 2 && stopProfilerTimerIfRunningAndRecordDelta(root, !0); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function renderDidSuspendDelayIfPossible() { + workInProgressRootExitStatus = 4; + (0 === (workInProgressRootSkippedLanes & 134217727) && + 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) || + null === workInProgressRoot || + markRootSuspended( + workInProgressRoot, + workInProgressRootRenderLanes, + workInProgressDeferredLane ); - 0 !== (pendingPassiveEffectsLanes & 3) && - 0 !== root.tag && - flushPassiveEffects(); - remainingLanes = root.pendingLanes; - 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) - ? ((nestedUpdateScheduled = !0), - root === rootWithNestedUpdates - ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))) - : (nestedUpdateCount = 0); - flushSyncWorkAcrossRoots_impl(!1); - return null; } -function flushPassiveEffects() { - if (null !== rootWithPendingPassiveEffects) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), - prevTransition = ReactCurrentBatchConfig.transition, - previousPriority = currentUpdatePriority; +function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + 0 < memoizedUpdaters.size && + (restorePendingUpdaters(root, workInProgressRootRenderLanes), + memoizedUpdaters.clear()); + movePendingFibersToMemoized(root, lanes); + } + workInProgressTransitions = null; + prepareFreshStack(root, lanes); + } + lanes = !1; + a: do try { - ReactCurrentBatchConfig.transition = null; - currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; - if (null === rootWithPendingPassiveEffects) - var JSCompiler_inline_result = !1; - else { - renderPriority = rootWithPendingPassiveEffects; - rootWithPendingPassiveEffects = null; - pendingPassiveEffectsLanes = 0; - if (0 !== (executionContext & 6)) - throw Error("Cannot flush passive effects while already rendering."); - var prevExecutionContext = executionContext; - executionContext |= 4; - commitPassiveUnmountOnFiber(renderPriority.current); - commitPassiveMountOnFiber(renderPriority, renderPriority.current); - var profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - for (var i = 0; i < profilerEffects.length; i++) { - var finishedWork = profilerEffects[i]; - if (executionContext & 4 && 0 !== (finishedWork.flags & 4)) - switch (finishedWork.tag) { - case 12: - var passiveEffectDuration = - finishedWork.stateNode.passiveEffectDuration, - _finishedWork$memoize = finishedWork.memoizedProps, - id = _finishedWork$memoize.id, - onPostCommit = _finishedWork$memoize.onPostCommit, - commitTime$87 = commitTime, - phase = null === finishedWork.alternate ? "mount" : "update"; - currentUpdateIsNested && (phase = "nested-update"); - "function" === typeof onPostCommit && - onPostCommit(id, phase, passiveEffectDuration, commitTime$87); - var parentFiber = finishedWork.return; - b: for (; null !== parentFiber; ) { - switch (parentFiber.tag) { - case 3: - parentFiber.stateNode.passiveEffectDuration += - passiveEffectDuration; - break b; - case 12: - parentFiber.stateNode.passiveEffectDuration += - passiveEffectDuration; - break b; - } - parentFiber = parentFiber.return; - } - } + if (0 !== workInProgressSuspendedReason && null !== workInProgress) { + memoizedUpdaters = workInProgress; + var thrownValue = workInProgressThrownValue; + switch (workInProgressSuspendedReason) { + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; + break a; + case 3: + case 2: + lanes || + null !== suspenseHandlerStackCursor.current || + (lanes = !0); + default: + (workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, memoizedUpdaters, thrownValue); } - executionContext = prevExecutionContext; - flushSyncWorkAcrossRoots_impl(!1); - if ( - injectedHook && - "function" === typeof injectedHook.onPostCommitFiberRoot - ) - try { - injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); - } catch (err) {} - var stateNode = renderPriority.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - JSCompiler_inline_result = !0; } - return JSCompiler_inline_result; - } finally { - (currentUpdatePriority = previousPriority), - (ReactCurrentBatchConfig.transition = prevTransition); + workLoopSync(); + break; + } catch (thrownValue$109) { + handleThrow(root, thrownValue$109); } - } - return !1; -} -function enqueuePendingPassiveProfilerEffect(fiber) { - pendingPassiveProfilerEffects.push(fiber); - rootDoesHavePassiveEffects || - ((rootDoesHavePassiveEffects = !0), - scheduleCallback(NormalPriority, function () { - flushPassiveEffects(); - return null; - })); + while (1); + lanes && root.shellSuspendCounter++; + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; } -function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); - rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); - null !== rootFiber && - (markRootUpdated(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +function workLoopSync() { + for (; null !== workInProgress; ) performUnitOfWork(workInProgress); } -function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { - if (3 === sourceFiber.tag) - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); - else - for (; null !== nearestMountedAncestor; ) { - if (3 === nearestMountedAncestor.tag) { - captureCommitPhaseErrorOnRoot( - nearestMountedAncestor, - sourceFiber, - error - ); - break; - } else if (1 === nearestMountedAncestor.tag) { - var instance = nearestMountedAncestor.stateNode; - if ( - "function" === - typeof nearestMountedAncestor.type.getDerivedStateFromError || - ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) +function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= 2; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + 0 < memoizedUpdaters.size && + (restorePendingUpdaters(root, workInProgressRootRenderLanes), + memoizedUpdaters.clear()); + movePendingFibersToMemoized(root, lanes); + } + workInProgressTransitions = null; + workInProgressRootRenderTargetTime = now$1() + 500; + prepareFreshStack(root, lanes); + } + a: do + try { + if (0 !== workInProgressSuspendedReason && null !== workInProgress) + b: switch ( + ((lanes = workInProgress), + (memoizedUpdaters = workInProgressThrownValue), + workInProgressSuspendedReason) ) { - sourceFiber = createCapturedValueAtFiber(error, sourceFiber); - sourceFiber = createClassErrorUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - nearestMountedAncestor = enqueueUpdate( - nearestMountedAncestor, - sourceFiber, - 2 - ); - null !== nearestMountedAncestor && - (markRootUpdated(nearestMountedAncestor, 2), - ensureRootIsScheduled(nearestMountedAncestor)); - break; + case 1: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 2: + if (isThenableResolved(memoizedUpdaters)) { + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + replaySuspendedUnitOfWork(lanes); + break; + } + lanes = function () { + 2 === workInProgressSuspendedReason && + workInProgressRoot === root && + (workInProgressSuspendedReason = 7); + ensureRootIsScheduled(root); + }; + memoizedUpdaters.then(lanes, lanes); + break a; + case 3: + workInProgressSuspendedReason = 7; + break a; + case 4: + workInProgressSuspendedReason = 5; + break a; + case 7: + isThenableResolved(memoizedUpdaters) + ? ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + replaySuspendedUnitOfWork(lanes)) + : ((workInProgressSuspendedReason = 0), + (workInProgressThrownValue = null), + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters)); + break; + case 5: + switch (workInProgress.tag) { + case 5: + case 26: + case 27: + lanes = workInProgress; + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + var sibling = lanes.sibling; + if (null !== sibling) workInProgress = sibling; + else { + var returnFiber = lanes.return; + null !== returnFiber + ? ((workInProgress = returnFiber), + completeUnitOfWork(returnFiber)) + : (workInProgress = null); + } + break b; + } + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 6: + workInProgressSuspendedReason = 0; + workInProgressThrownValue = null; + throwAndUnwindWorkLoop(root, lanes, memoizedUpdaters); + break; + case 8: + resetWorkInProgressStack(); + workInProgressRootExitStatus = 6; + break a; + default: + throw Error("Unexpected SuspendedReason. This is a bug in React."); } - } - nearestMountedAncestor = nearestMountedAncestor.return; + workLoopConcurrent(); + break; + } catch (thrownValue$111) { + handleThrow(root, thrownValue$111); } + while (1); + resetContextDependencies(); + ReactCurrentDispatcher.current = prevDispatcher; + executionContext = prevExecutionContext; + if (null !== workInProgress) return 0; + workInProgressRoot = null; + workInProgressRootRenderLanes = 0; + finishQueueingConcurrentUpdates(); + return workInProgressRootExitStatus; } -function attachPingListener(root, wakeable, lanes) { - var pingCache = root.pingCache; - if (null === pingCache) { - pingCache = root.pingCache = new PossiblyWeakMap(); - var threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else - (threadIDs = pingCache.get(wakeable)), - void 0 === threadIDs && - ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); - threadIDs.has(lanes) || - ((workInProgressRootDidAttachPingListener = !0), - threadIDs.add(lanes), - (pingCache = pingSuspendedRoot.bind(null, root, wakeable, lanes)), - isDevToolsPresent && restorePendingUpdaters(root, lanes), - wakeable.then(pingCache, pingCache)); -} -function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(wakeable); - root.pingedLanes |= root.suspendedLanes & pingedLanes; - workInProgressRoot === root && - (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && - (4 === workInProgressRootExitStatus || - (3 === workInProgressRootExitStatus && - (workInProgressRootRenderLanes & 62914560) === - workInProgressRootRenderLanes && - 300 > now$1() - globalMostRecentFallbackTime) - ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) - : (workInProgressRootPingedLanes |= pingedLanes)); - ensureRootIsScheduled(root); -} -function retryTimedOutBoundary(boundaryFiber, retryLane) { - 0 === retryLane && - (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); - boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - null !== boundaryFiber && - (markRootUpdated(boundaryFiber, retryLane), - ensureRootIsScheduled(boundaryFiber)); -} -function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState, - retryLane = 0; - null !== suspenseState && (retryLane = suspenseState.retryLane); - retryTimedOutBoundary(boundaryFiber, retryLane); +function workLoopConcurrent() { + for (; null !== workInProgress && !shouldYield(); ) + performUnitOfWork(workInProgress); } -function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = 0; - switch (boundaryFiber.tag) { - case 13: - var retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - null !== suspenseState && (retryLane = suspenseState.retryLane); - break; - case 19: - retryCache = boundaryFiber.stateNode; +function performUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate; + 0 !== (unitOfWork.mode & 2) + ? (startProfilerTimer(unitOfWork), + (current = beginWork(current, unitOfWork, entangledRenderLanes)), + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0)) + : (current = beginWork(current, unitOfWork, entangledRenderLanes)); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; +} +function replaySuspendedUnitOfWork(unitOfWork) { + var current = unitOfWork.alternate, + isProfilingMode = 0 !== (unitOfWork.mode & 2); + isProfilingMode && startProfilerTimer(unitOfWork); + switch (unitOfWork.tag) { + case 2: + unitOfWork.tag = 0; + case 15: + case 0: + var Component = unitOfWork.type, + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + void 0, + workInProgressRootRenderLanes + ); break; - case 22: - retryCache = boundaryFiber.stateNode._retryCache; + case 11: + Component = unitOfWork.type.render; + unresolvedProps = unitOfWork.pendingProps; + unresolvedProps = + unitOfWork.elementType === Component + ? unresolvedProps + : resolveDefaultProps(Component, unresolvedProps); + current = replayFunctionComponent( + current, + unitOfWork, + unresolvedProps, + Component, + unitOfWork.ref, + workInProgressRootRenderLanes + ); break; + case 5: + resetHooksOnUnwind(unitOfWork); default: - throw Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ); + unwindInterruptedWork(current, unitOfWork), + (unitOfWork = workInProgress = + resetWorkInProgress(unitOfWork, entangledRenderLanes)), + (current = beginWork(current, unitOfWork, entangledRenderLanes)); } - null !== retryCache && retryCache.delete(wakeable); - retryTimedOutBoundary(boundaryFiber, retryLane); + isProfilingMode && stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, !0); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + null === current + ? completeUnitOfWork(unitOfWork) + : (workInProgress = current); + ReactCurrentOwner.current = null; } -var beginWork; -beginWork = function (current, workInProgress, renderLanes) { - if (null !== current) +function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue) { + resetContextDependencies(); + resetHooksOnUnwind(unitOfWork); + thenableState$1 = null; + thenableIndexCounter$1 = 0; + var returnFiber = unitOfWork.return; + try { if ( - current.memoizedProps !== workInProgress.pendingProps || - didPerformWorkStackCursor.current - ) - didReceiveUpdate = !0; - else { - if ( - 0 === (current.lanes & renderLanes) && - 0 === (workInProgress.flags & 128) + throwException( + root, + returnFiber, + unitOfWork, + thrownValue, + workInProgressRootRenderLanes ) - return ( - (didReceiveUpdate = !1), - attemptEarlyBailoutIfNoScheduledUpdate( - current, - workInProgress, - renderLanes - ) - ); - didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1; + ) { + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; } - else didReceiveUpdate = !1; - workInProgress.lanes = 0; - switch (workInProgress.tag) { - case 2: - var Component = workInProgress.type; - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - var context = getMaskedContext( - workInProgress, - contextStackCursor$1.current - ); - prepareToReadContext(workInProgress, renderLanes); - context = renderWithHooks( - null, - workInProgress, - Component, - current, - context, - renderLanes - ); - workInProgress.flags |= 1; - if ( - "object" === typeof context && - null !== context && - "function" === typeof context.render && - void 0 === context.$$typeof - ) { - workInProgress.tag = 1; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - if (isContextProvider(Component)) { - var hasContext = !0; - pushContextProvider(workInProgress); - } else hasContext = !1; - workInProgress.memoizedState = - null !== context.state && void 0 !== context.state - ? context.state - : null; - initializeUpdateQueue(workInProgress); - context.updater = classComponentUpdater; - workInProgress.stateNode = context; - context._reactInternals = workInProgress; - mountClassInstance(workInProgress, Component, current, renderLanes); - workInProgress = finishClassComponent( - null, - workInProgress, - Component, - !0, - hasContext, - renderLanes - ); - } else - (workInProgress.tag = 0), - reconcileChildren(null, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child); - return workInProgress; - case 16: - Component = workInProgress.elementType; - a: { - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - current = workInProgress.pendingProps; - context = Component._init; - Component = context(Component._payload); - workInProgress.type = Component; - context = workInProgress.tag = resolveLazyComponentTag(Component); - current = resolveDefaultProps(Component, current); - switch (context) { - case 0: - workInProgress = updateFunctionComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 1: - workInProgress = updateClassComponent( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 11: - workInProgress = updateForwardRef( - null, - workInProgress, - Component, - current, - renderLanes - ); - break a; - case 14: - workInProgress = updateMemoComponent( - null, - workInProgress, - Component, - resolveDefaultProps(Component.type, current), - renderLanes - ); - break a; + } catch (error) { + if (null !== returnFiber) throw ((workInProgress = returnFiber), error); + workInProgressRootExitStatus = 1; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (unitOfWork.flags & 32768) + a: { + root = unitOfWork; + do { + unitOfWork = unwindWork(root.alternate, root); + if (null !== unitOfWork) { + unitOfWork.flags &= 32767; + workInProgress = unitOfWork; + break a; } - throw Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." - ); - } - return workInProgress; - case 0: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateFunctionComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 1: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateClassComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 3: - pushHostRootContext(workInProgress); - if (null === current) - throw Error("Should have a current fiber. This is a bug in React."); - context = workInProgress.pendingProps; - Component = workInProgress.memoizedState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, context, null, renderLanes); - context = workInProgress.memoizedState.element; - context === Component - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - )) - : (reconcileChildren(current, workInProgress, context, renderLanes), - (workInProgress = workInProgress.child)); - return workInProgress; - case 26: - case 27: - case 5: - return ( - pushHostContext(workInProgress), - (Component = workInProgress.pendingProps.children), - markRef$1(current, workInProgress), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child + if (0 !== (root.mode & 2)) { + stopProfilerTimerIfRunningAndRecordDelta(root, !1); + unitOfWork = root.actualDuration; + for (thrownValue = root.child; null !== thrownValue; ) + (unitOfWork += thrownValue.actualDuration), + (thrownValue = thrownValue.sibling); + root.actualDuration = unitOfWork; + } + root = root.return; + null !== root && + ((root.flags |= 32768), + (root.subtreeFlags = 0), + (root.deletions = null)); + workInProgress = root; + } while (null !== root); + workInProgressRootExitStatus = 6; + workInProgress = null; + } + else completeUnitOfWork(unitOfWork); +} +function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + var current = completedWork.alternate; + unitOfWork = completedWork.return; + 0 === (completedWork.mode & 2) + ? (current = completeWork(current, completedWork, entangledRenderLanes)) + : (startProfilerTimer(completedWork), + (current = completeWork(current, completedWork, entangledRenderLanes)), + stopProfilerTimerIfRunningAndRecordDelta(completedWork, !1)); + if (null !== current) { + workInProgress = current; + return; + } + completedWork = completedWork.sibling; + if (null !== completedWork) { + workInProgress = completedWork; + return; + } + workInProgress = completedWork = unitOfWork; + } while (null !== completedWork); + 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5); +} +function commitRoot( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + spawnedLane +) { + var previousUpdateLanePriority = currentUpdatePriority, + prevTransition = ReactCurrentBatchConfig.transition; + try { + (ReactCurrentBatchConfig.transition = null), + (currentUpdatePriority = 2), + commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + previousUpdateLanePriority, + spawnedLane ); - case 6: + } finally { + (ReactCurrentBatchConfig.transition = prevTransition), + (currentUpdatePriority = previousUpdateLanePriority); + } + return null; +} +function commitRootImpl( + root, + recoverableErrors, + transitions, + didIncludeRenderPhaseUpdate, + renderPriorityLevel, + spawnedLane +) { + do flushPassiveEffects(); + while (null !== rootWithPendingPassiveEffects); + if (0 !== (executionContext & 6)) + throw Error("Should not already be working."); + didIncludeRenderPhaseUpdate = root.finishedWork; + transitions = root.finishedLanes; + if (null === didIncludeRenderPhaseUpdate) return null; + root.finishedWork = null; + root.finishedLanes = 0; + if (didIncludeRenderPhaseUpdate === root.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + root.callbackNode = null; + root.callbackPriority = 0; + root.cancelPendingCommit = null; + var remainingLanes = + didIncludeRenderPhaseUpdate.lanes | didIncludeRenderPhaseUpdate.childLanes; + remainingLanes |= concurrentlyUpdatedLanes; + markRootFinished(root, remainingLanes, spawnedLane); + root === workInProgressRoot && + ((workInProgress = workInProgressRoot = null), + (workInProgressRootRenderLanes = 0)); + (0 === (didIncludeRenderPhaseUpdate.subtreeFlags & 10256) && + 0 === (didIncludeRenderPhaseUpdate.flags & 10256)) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); return null; - case 13: - return updateSuspenseComponent(current, workInProgress, renderLanes); - case 4: - return ( - pushHostContainer( - workInProgress, - workInProgress.stateNode.containerInfo - ), - (Component = workInProgress.pendingProps), - null === current - ? (workInProgress.child = reconcileChildFibers( - workInProgress, - null, - Component, - renderLanes - )) - : reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 11: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - updateForwardRef( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 7: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps, - renderLanes - ), - workInProgress.child - ); - case 8: - return ( - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child - ); - case 12: - return ( - (workInProgress.flags |= 4), - (Component = workInProgress.stateNode), - (Component.effectDuration = 0), - (Component.passiveEffectDuration = 0), - reconcileChildren( - current, - workInProgress, - workInProgress.pendingProps.children, - renderLanes - ), - workInProgress.child - ); - case 10: - a: { - Component = workInProgress.type._context; - context = workInProgress.pendingProps; - hasContext = workInProgress.memoizedProps; - var newValue = context.value; - push(valueCursor, Component._currentValue); - Component._currentValue = newValue; - if (null !== hasContext) - if (objectIs(hasContext.value, newValue)) { - if ( - hasContext.children === context.children && - !didPerformWorkStackCursor.current - ) { - workInProgress = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes - ); - break a; - } - } else - for ( - hasContext = workInProgress.child, - null !== hasContext && (hasContext.return = workInProgress); - null !== hasContext; - - ) { - var list = hasContext.dependencies; - if (null !== list) { - newValue = hasContext.child; - for ( - var dependency = list.firstContext; - null !== dependency; - - ) { - if (dependency.context === Component) { - if (1 === hasContext.tag) { - dependency = createUpdate(renderLanes & -renderLanes); - dependency.tag = 2; - var updateQueue = hasContext.updateQueue; - if (null !== updateQueue) { - updateQueue = updateQueue.shared; - var pending = updateQueue.pending; - null === pending - ? (dependency.next = dependency) - : ((dependency.next = pending.next), - (pending.next = dependency)); - updateQueue.pending = dependency; - } - } - hasContext.lanes |= renderLanes; - dependency = hasContext.alternate; - null !== dependency && (dependency.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - hasContext.return, - renderLanes, - workInProgress - ); - list.lanes |= renderLanes; - break; - } - dependency = dependency.next; - } - } else if (10 === hasContext.tag) - newValue = - hasContext.type === workInProgress.type - ? null - : hasContext.child; - else if (18 === hasContext.tag) { - newValue = hasContext.return; - if (null === newValue) - throw Error( - "We just came from a parent so we must have had a parent. This is a bug in React." - ); - newValue.lanes |= renderLanes; - list = newValue.alternate; - null !== list && (list.lanes |= renderLanes); - scheduleContextWorkOnParentPath( - newValue, - renderLanes, - workInProgress - ); - newValue = hasContext.sibling; - } else newValue = hasContext.child; - if (null !== newValue) newValue.return = hasContext; - else - for (newValue = hasContext; null !== newValue; ) { - if (newValue === workInProgress) { - newValue = null; - break; - } - hasContext = newValue.sibling; - if (null !== hasContext) { - hasContext.return = newValue.return; - newValue = hasContext; - break; + })); + spawnedLane = 0 !== (didIncludeRenderPhaseUpdate.flags & 15990); + if (0 !== (didIncludeRenderPhaseUpdate.subtreeFlags & 15990) || spawnedLane) { + spawnedLane = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + remainingLanes = currentUpdatePriority; + currentUpdatePriority = 2; + var prevExecutionContext = executionContext; + executionContext |= 4; + ReactCurrentOwner.current = null; + commitBeforeMutationEffects(root, didIncludeRenderPhaseUpdate); + commitTime = now(); + commitMutationEffects(root, didIncludeRenderPhaseUpdate, transitions); + root.current = didIncludeRenderPhaseUpdate; + commitLayoutEffects(didIncludeRenderPhaseUpdate, root, transitions); + requestPaint(); + executionContext = prevExecutionContext; + currentUpdatePriority = remainingLanes; + ReactCurrentBatchConfig.transition = spawnedLane; + } else (root.current = didIncludeRenderPhaseUpdate), (commitTime = now()); + rootDoesHavePassiveEffects && + ((rootDoesHavePassiveEffects = !1), + (rootWithPendingPassiveEffects = root), + (pendingPassiveEffectsLanes = transitions)); + remainingLanes = root.pendingLanes; + 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null); + onCommitRoot(didIncludeRenderPhaseUpdate.stateNode, renderPriorityLevel); + isDevToolsPresent && root.memoizedUpdaters.clear(); + ensureRootIsScheduled(root); + if (null !== recoverableErrors) + for ( + renderPriorityLevel = root.onRecoverableError, + didIncludeRenderPhaseUpdate = 0; + didIncludeRenderPhaseUpdate < recoverableErrors.length; + didIncludeRenderPhaseUpdate++ + ) + (spawnedLane = recoverableErrors[didIncludeRenderPhaseUpdate]), + (remainingLanes = { + digest: spawnedLane.digest, + componentStack: spawnedLane.stack + }), + renderPriorityLevel(spawnedLane.value, remainingLanes); + if (hasUncaughtError) + throw ( + ((hasUncaughtError = !1), + (root = firstUncaughtError), + (firstUncaughtError = null), + root) + ); + 0 !== (pendingPassiveEffectsLanes & 3) && + 0 !== root.tag && + flushPassiveEffects(); + remainingLanes = root.pendingLanes; + 0 !== (transitions & 4194218) && 0 !== (remainingLanes & 42) + ? ((nestedUpdateScheduled = !0), + root === rootWithNestedUpdates + ? nestedUpdateCount++ + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))) + : (nestedUpdateCount = 0); + flushSyncWorkAcrossRoots_impl(!1); + return null; +} +function flushPassiveEffects() { + if (null !== rootWithPendingPassiveEffects) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), + prevTransition = ReactCurrentBatchConfig.transition, + previousPriority = currentUpdatePriority; + try { + ReactCurrentBatchConfig.transition = null; + currentUpdatePriority = 32 > renderPriority ? 32 : renderPriority; + if (null === rootWithPendingPassiveEffects) + var JSCompiler_inline_result = !1; + else { + renderPriority = rootWithPendingPassiveEffects; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = 0; + if (0 !== (executionContext & 6)) + throw Error("Cannot flush passive effects while already rendering."); + var prevExecutionContext = executionContext; + executionContext |= 4; + commitPassiveUnmountOnFiber(renderPriority.current); + commitPassiveMountOnFiber(renderPriority, renderPriority.current); + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; + for (var i = 0; i < profilerEffects.length; i++) { + var finishedWork = profilerEffects[i]; + if (executionContext & 4 && 0 !== (finishedWork.flags & 4)) + switch (finishedWork.tag) { + case 12: + var passiveEffectDuration = + finishedWork.stateNode.passiveEffectDuration, + _finishedWork$memoize = finishedWork.memoizedProps, + id = _finishedWork$memoize.id, + onPostCommit = _finishedWork$memoize.onPostCommit, + commitTime$86 = commitTime, + phase = null === finishedWork.alternate ? "mount" : "update"; + currentUpdateIsNested && (phase = "nested-update"); + "function" === typeof onPostCommit && + onPostCommit(id, phase, passiveEffectDuration, commitTime$86); + var parentFiber = finishedWork.return; + b: for (; null !== parentFiber; ) { + switch (parentFiber.tag) { + case 3: + parentFiber.stateNode.passiveEffectDuration += + passiveEffectDuration; + break b; + case 12: + parentFiber.stateNode.passiveEffectDuration += + passiveEffectDuration; + break b; } - newValue = newValue.return; + parentFiber = parentFiber.return; } - hasContext = newValue; } - reconcileChildren( - current, - workInProgress, - context.children, - renderLanes + } + executionContext = prevExecutionContext; + flushSyncWorkAcrossRoots_impl(!1); + if ( + injectedHook && + "function" === typeof injectedHook.onPostCommitFiberRoot + ) + try { + injectedHook.onPostCommitFiberRoot(rendererID, renderPriority); + } catch (err) {} + var stateNode = renderPriority.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + JSCompiler_inline_result = !0; + } + return JSCompiler_inline_result; + } finally { + (currentUpdatePriority = previousPriority), + (ReactCurrentBatchConfig.transition = prevTransition); + } + } + return !1; +} +function enqueuePendingPassiveProfilerEffect(fiber) { + pendingPassiveProfilerEffects.push(fiber); + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(NormalPriority, function () { + flushPassiveEffects(); + return null; + })); +} +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 2); + rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2); + null !== rootFiber && + (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber)); +} +function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) { + if (3 === sourceFiber.tag) + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + else + for (; null !== nearestMountedAncestor; ) { + if (3 === nearestMountedAncestor.tag) { + captureCommitPhaseErrorOnRoot( + nearestMountedAncestor, + sourceFiber, + error ); - workInProgress = workInProgress.child; + break; + } else if (1 === nearestMountedAncestor.tag) { + var instance = nearestMountedAncestor.stateNode; + if ( + "function" === + typeof nearestMountedAncestor.type.getDerivedStateFromError || + ("function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + ) { + sourceFiber = createCapturedValueAtFiber(error, sourceFiber); + sourceFiber = createClassErrorUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + nearestMountedAncestor = enqueueUpdate( + nearestMountedAncestor, + sourceFiber, + 2 + ); + null !== nearestMountedAncestor && + (markRootUpdated$1(nearestMountedAncestor, 2), + ensureRootIsScheduled(nearestMountedAncestor)); + break; + } } - return workInProgress; - case 9: - return ( - (context = workInProgress.type), - (Component = workInProgress.pendingProps.children), - prepareToReadContext(workInProgress, renderLanes), - (context = readContext(context)), - (Component = Component(context)), - (workInProgress.flags |= 1), - reconcileChildren(current, workInProgress, Component, renderLanes), - workInProgress.child - ); - case 14: - return ( - (Component = workInProgress.type), - (context = resolveDefaultProps(Component, workInProgress.pendingProps)), - (context = resolveDefaultProps(Component.type, context)), - updateMemoComponent( - current, - workInProgress, - Component, - context, - renderLanes - ) - ); - case 15: - return updateSimpleMemoComponent( - current, - workInProgress, - workInProgress.type, - workInProgress.pendingProps, - renderLanes - ); - case 17: - return ( - (Component = workInProgress.type), - (context = workInProgress.pendingProps), - (context = - workInProgress.elementType === Component - ? context - : resolveDefaultProps(Component, context)), - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress), - (workInProgress.tag = 1), - isContextProvider(Component) - ? ((current = !0), pushContextProvider(workInProgress)) - : (current = !1), - prepareToReadContext(workInProgress, renderLanes), - constructClassInstance(workInProgress, Component, context), - mountClassInstance(workInProgress, Component, context, renderLanes), - finishClassComponent( - null, - workInProgress, - Component, - !0, - current, - renderLanes - ) - ); + nearestMountedAncestor = nearestMountedAncestor.return; + } +} +function attachPingListener(root, wakeable, lanes) { + var pingCache = root.pingCache; + if (null === pingCache) { + pingCache = root.pingCache = new PossiblyWeakMap(); + var threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else + (threadIDs = pingCache.get(wakeable)), + void 0 === threadIDs && + ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs)); + threadIDs.has(lanes) || + ((workInProgressRootDidAttachPingListener = !0), + threadIDs.add(lanes), + (pingCache = pingSuspendedRoot.bind(null, root, wakeable, lanes)), + isDevToolsPresent && restorePendingUpdaters(root, lanes), + wakeable.then(pingCache, pingCache)); +} +function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(wakeable); + root.pingedLanes |= root.suspendedLanes & pingedLanes; + workInProgressRoot === root && + (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && + (4 === workInProgressRootExitStatus || + (3 === workInProgressRootExitStatus && + (workInProgressRootRenderLanes & 62914560) === + workInProgressRootRenderLanes && + 300 > now$1() - globalMostRecentFallbackTime) + ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) + : (workInProgressRootPingedLanes |= pingedLanes)); + ensureRootIsScheduled(root); +} +function retryTimedOutBoundary(boundaryFiber, retryLane) { + 0 === retryLane && + (retryLane = 0 === (boundaryFiber.mode & 1) ? 2 : claimNextRetryLane()); + boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + null !== boundaryFiber && + (markRootUpdated$1(boundaryFiber, retryLane), + ensureRootIsScheduled(boundaryFiber)); +} +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState, + retryLane = 0; + null !== suspenseState && (retryLane = suspenseState.retryLane); + retryTimedOutBoundary(boundaryFiber, retryLane); +} +function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = 0; + switch (boundaryFiber.tag) { + case 13: + var retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + null !== suspenseState && (retryLane = suspenseState.retryLane); + break; case 19: - return updateSuspenseListComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode; + break; case 22: - return updateOffscreenComponent(current, workInProgress, renderLanes); + retryCache = boundaryFiber.stateNode._retryCache; + break; + default: + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); } - throw Error( - "Unknown unit of work tag (" + - workInProgress.tag + - "). This error is likely caused by a bug in React. Please file an issue." - ); -}; + null !== retryCache && retryCache.delete(wakeable); + retryTimedOutBoundary(boundaryFiber, retryLane); +} function restorePendingUpdaters(root, lanes) { isDevToolsPresent && root.memoizedUpdaters.forEach(function (schedulingFiber) { @@ -9831,6 +9505,7 @@ function createFiberFromTypeAndProps( case REACT_CONTEXT_TYPE: fiberTag = 9; break a; + case REACT_CONSUMER_TYPE: case REACT_FORWARD_REF_TYPE: fiberTag = 11; break a; @@ -9988,63 +9663,19 @@ function findHostInstance(component) { return null === component ? null : getPublicInstance(component.stateNode); } function updateContainer(element, container, parentComponent, callback) { - var current = container.current, - lane = requestUpdateLane(current); - a: if (parentComponent) { - parentComponent = parentComponent._reactInternals; - b: { - if ( - getNearestMountedFiber(parentComponent) !== parentComponent || - 1 !== parentComponent.tag - ) - throw Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); - var JSCompiler_inline_result = parentComponent; - do { - switch (JSCompiler_inline_result.tag) { - case 3: - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode.context; - break b; - case 1: - if (isContextProvider(JSCompiler_inline_result.type)) { - JSCompiler_inline_result = - JSCompiler_inline_result.stateNode - .__reactInternalMemoizedMergedChildContext; - break b; - } - } - JSCompiler_inline_result = JSCompiler_inline_result.return; - } while (null !== JSCompiler_inline_result); - throw Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ); - } - if (1 === parentComponent.tag) { - var Component = parentComponent.type; - if (isContextProvider(Component)) { - parentComponent = processChildContext( - parentComponent, - Component, - JSCompiler_inline_result - ); - break a; - } - } - parentComponent = JSCompiler_inline_result; - } else parentComponent = emptyContextObject; + parentComponent = container.current; + var lane = requestUpdateLane(parentComponent); null === container.context - ? (container.context = parentComponent) - : (container.pendingContext = parentComponent); + ? (container.context = emptyContextObject) + : (container.pendingContext = emptyContextObject); container = createUpdate(lane); container.payload = { element: element }; callback = void 0 === callback ? null : callback; null !== callback && (container.callback = callback); - element = enqueueUpdate(current, container, lane); + element = enqueueUpdate(parentComponent, container, lane); null !== element && - (scheduleUpdateOnFiber(element, current, lane), - entangleTransitions(element, current, lane)); + (scheduleUpdateOnFiber(element, parentComponent, lane), + entangleTransitions(element, parentComponent, lane)); return lane; } function emptyFindFiberByHostInstance() { @@ -10099,10 +9730,10 @@ batchedUpdatesImpl = function (fn, a) { } }; var roots = new Map(), - devToolsConfig$jscomp$inline_1154 = { + devToolsConfig$jscomp$inline_1140 = { findFiberByHostInstance: getInstanceFromTag, bundleType: 0, - version: "18.3.0-canary-03d6f7cf0-20240209", + version: "18.3.0-canary-9372c6311-20240315", rendererPackageName: "react-native-renderer", rendererConfig: { getInspectorDataForInstance: getInspectorDataForInstance, @@ -10118,11 +9749,11 @@ var roots = new Map(), }.bind(null, findNodeHandle) } }; -var internals$jscomp$inline_1389 = { - bundleType: devToolsConfig$jscomp$inline_1154.bundleType, - version: devToolsConfig$jscomp$inline_1154.version, - rendererPackageName: devToolsConfig$jscomp$inline_1154.rendererPackageName, - rendererConfig: devToolsConfig$jscomp$inline_1154.rendererConfig, +var internals$jscomp$inline_1378 = { + bundleType: devToolsConfig$jscomp$inline_1140.bundleType, + version: devToolsConfig$jscomp$inline_1140.version, + rendererPackageName: devToolsConfig$jscomp$inline_1140.rendererPackageName, + rendererConfig: devToolsConfig$jscomp$inline_1140.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, @@ -10138,26 +9769,26 @@ var internals$jscomp$inline_1389 = { return null === fiber ? null : fiber.stateNode; }, findFiberByHostInstance: - devToolsConfig$jscomp$inline_1154.findFiberByHostInstance || + devToolsConfig$jscomp$inline_1140.findFiberByHostInstance || emptyFindFiberByHostInstance, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, - reconcilerVersion: "18.3.0-canary-03d6f7cf0-20240209" + reconcilerVersion: "18.3.0-canary-9372c6311-20240315" }; if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) { - var hook$jscomp$inline_1390 = __REACT_DEVTOOLS_GLOBAL_HOOK__; + var hook$jscomp$inline_1379 = __REACT_DEVTOOLS_GLOBAL_HOOK__; if ( - !hook$jscomp$inline_1390.isDisabled && - hook$jscomp$inline_1390.supportsFiber + !hook$jscomp$inline_1379.isDisabled && + hook$jscomp$inline_1379.supportsFiber ) try { - (rendererID = hook$jscomp$inline_1390.inject( - internals$jscomp$inline_1389 + (rendererID = hook$jscomp$inline_1379.inject( + internals$jscomp$inline_1378 )), - (injectedHook = hook$jscomp$inline_1390); + (injectedHook = hook$jscomp$inline_1379); } catch (err) {} } exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = { diff --git a/packages/react-native/Libraries/Settings/React-RCTSettings.podspec b/packages/react-native/Libraries/Settings/React-RCTSettings.podspec index 30f9bdbb1ed191..4105f324fa4788 100644 --- a/packages/react-native/Libraries/Settings/React-RCTSettings.podspec +++ b/packages/react-native/Libraries/Settings/React-RCTSettings.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -50,7 +50,7 @@ Pod::Spec.new do |s| s.dependency "React-jsi" s.dependency "React-Core/RCTSettingsHeaders" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple", :additional_framework_paths => ["build/generated/ios"]) end diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheet.d.ts b/packages/react-native/Libraries/StyleSheet/StyleSheet.d.ts index 6d9fda4dac2e85..17ab55d6bc9fbd 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheet.d.ts +++ b/packages/react-native/Libraries/StyleSheet/StyleSheet.d.ts @@ -14,7 +14,7 @@ export interface StyleSheetProperties { flatten(style: T): T; } -type Falsy = undefined | null | false; +type Falsy = undefined | null | false | ''; interface RecursiveArray extends Array | RecursiveArray> {} /** Keep a brand of 'T' so that calls to `StyleSheet.flatten` can take `RegisteredStyle` and return `T`. */ diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.d.ts b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.d.ts index 5a9121be11765f..f4a99256313845 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.d.ts +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.d.ts @@ -27,6 +27,8 @@ export type DimensionValue = type AnimatableNumericValue = number | Animated.AnimatedNode; type AnimatableStringValue = string | Animated.AnimatedNode; +export type CursorValue = 'auto' | 'pointer'; + /** * Flex Prop Types * @see https://reactnative.dev/docs/flexbox @@ -274,6 +276,7 @@ export interface ViewStyle extends FlexStyle, ShadowStyleIOS, TransformsStyle { * Controls whether the View can be the target of touch events. */ pointerEvents?: 'box-none' | 'none' | 'box-only' | 'auto' | undefined; + cursor?: CursorValue | undefined; } export type FontVariant = @@ -403,4 +406,5 @@ export interface ImageStyle extends FlexStyle, ShadowStyleIOS, TransformsStyle { tintColor?: ColorValue | undefined; opacity?: AnimatableNumericValue | undefined; objectFit?: 'cover' | 'contain' | 'fill' | 'scale-down' | undefined; + cursor?: CursorValue | undefined; } diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js index d4b5ab921132fc..59a7afc81d8c3d 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js @@ -37,6 +37,8 @@ export type EdgeInsetsValue = { export type DimensionValue = number | string | 'auto' | AnimatedNode | null; export type AnimatableNumericValue = number | AnimatedNode; +export type CursorValue = 'auto' | 'pointer'; + /** * React Native's layout system is based on Flexbox and is powered both * on iOS and Android by an open source project called `Yoga`: @@ -729,6 +731,7 @@ export type ____ViewStyle_InternalCore = $ReadOnly<{ opacity?: AnimatableNumericValue, elevation?: number, pointerEvents?: 'auto' | 'none' | 'box-none' | 'box-only', + cursor?: CursorValue, }>; export type ____ViewStyle_Internal = $ReadOnly<{ @@ -918,5 +921,5 @@ export type ____FlattenStyleProp_Internal< > = TStyleProp extends null | void | false | '' ? empty : TStyleProp extends $ReadOnlyArray - ? ____FlattenStyleProp_Internal - : TStyleProp; + ? ____FlattenStyleProp_Internal + : TStyleProp; diff --git a/packages/react-native/Libraries/Text/Text.js b/packages/react-native/Libraries/Text/Text.js index 5ccceefc346e6b..19d697c99a2776 100644 --- a/packages/react-native/Libraries/Text/Text.js +++ b/packages/react-native/Libraries/Text/Text.js @@ -118,9 +118,6 @@ const Text: React.AbstractComponent< setHighlighted(false); onPressOut?.(event); }, - onResponderTerminationRequest_DEPRECATED: - onResponderTerminationRequest, - onStartShouldSetResponder_DEPRECATED: onStartShouldSetResponder, } : null, [ @@ -131,8 +128,6 @@ const Text: React.AbstractComponent< onPress, onPressIn, onPressOut, - onResponderTerminationRequest, - onStartShouldSetResponder, suppressHighlighting, ], ); @@ -169,8 +164,13 @@ const Text: React.AbstractComponent< }, onClick: eventHandlers.onClick, onResponderTerminationRequest: - eventHandlers.onResponderTerminationRequest, - onStartShouldSetResponder: eventHandlers.onStartShouldSetResponder, + onResponderTerminationRequest != null + ? onResponderTerminationRequest + : eventHandlers.onResponderTerminationRequest, + onStartShouldSetResponder: + onStartShouldSetResponder != null + ? onStartShouldSetResponder + : eventHandlers.onStartShouldSetResponder, }, [ eventHandlers, @@ -178,6 +178,8 @@ const Text: React.AbstractComponent< onResponderMove, onResponderRelease, onResponderTerminate, + onResponderTerminationRequest, + onStartShouldSetResponder, ], ); diff --git a/packages/react-native/Libraries/Utilities/Platform.android.js b/packages/react-native/Libraries/Utilities/Platform.android.js index 5272465aa7c5ac..e2cfdf8aa64285 100644 --- a/packages/react-native/Libraries/Utilities/Platform.android.js +++ b/packages/react-native/Libraries/Utilities/Platform.android.js @@ -78,10 +78,10 @@ const Platform: PlatformType = { ? // $FlowFixMe[incompatible-return] spec.android : 'native' in spec - ? // $FlowFixMe[incompatible-return] - spec.native - : // $FlowFixMe[incompatible-return] - spec.default, + ? // $FlowFixMe[incompatible-return] + spec.native + : // $FlowFixMe[incompatible-return] + spec.default, }; module.exports = Platform; diff --git a/packages/react-native/Libraries/Vibration/React-RCTVibration.podspec b/packages/react-native/Libraries/Vibration/React-RCTVibration.podspec index e6b7d69cde4cbc..3685818c8e744d 100644 --- a/packages/react-native/Libraries/Vibration/React-RCTVibration.podspec +++ b/packages/react-native/Libraries/Vibration/React-RCTVibration.podspec @@ -22,7 +22,7 @@ folly_version = folly_config[:version] header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -50,7 +50,7 @@ Pod::Spec.new do |s| s.dependency "React-jsi" s.dependency "React-Core/RCTVibrationHeaders" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") end diff --git a/packages/react-native/Libraries/__tests__/__snapshots__/public-api-test.js.snap b/packages/react-native/Libraries/__tests__/__snapshots__/public-api-test.js.snap index de27ba219ed603..290704597d70e4 100644 --- a/packages/react-native/Libraries/__tests__/__snapshots__/public-api-test.js.snap +++ b/packages/react-native/Libraries/__tests__/__snapshots__/public-api-test.js.snap @@ -810,13 +810,7 @@ exports[`public API should not change unintentionally Libraries/Animated/compone `; exports[`public API should not change unintentionally Libraries/Animated/createAnimatedComponent.js 1`] = ` -"export type AnimatedProps = $ObjMap< - Props & - $ReadOnly<{ - passthroughAnimatedPropExplicitValues?: React.ElementConfig, - }>, - () => any, ->; +"export type AnimatedProps = $ObjMap any>; export type AnimatedComponentType< Props: { ... }, +Instance = mixed, @@ -1773,41 +1767,6 @@ declare export default typeof NativeKeyboardObserver; " `; -exports[`public API should not change unintentionally Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.android.js 1`] = ` -"export type PopupMenuAndroidInstance = { - +show: () => void, -}; -type Props = { - menuItems: $ReadOnlyArray, - onSelectionChange: (number) => void, - children: React.Node, - instanceRef: RefObject, -}; -declare export default function PopupMenuAndroid(Props): React.Node; -" -`; - -exports[`public API should not change unintentionally Libraries/Components/PopupMenuAndroid/PopupMenuAndroid.js 1`] = ` -"export type PopupMenuAndroidInstance = { - +show: () => void, -}; -type Props = { - menuItems: $ReadOnlyArray, - onSelectionChange: (number) => void, - children: Node, - instanceRef: RefObject, -}; -declare function PopupMenuAndroid(props: Props): Node; -declare export default typeof PopupMenuAndroid; -" -`; - -exports[`public API should not change unintentionally Libraries/Components/PopupMenuAndroid/PopupMenuAndroidNativeComponent.js 1`] = ` -"export * from \\"../../../src/private/specs/components/PopupMenuAndroidNativeComponent\\"; -declare export default typeof PopupMenuAndroidNativeComponent; -" -`; - exports[`public API should not change unintentionally Libraries/Components/Pressable/Pressable.js 1`] = ` "type ViewStyleProp = $ElementType, \\"style\\">; export type StateCallbackType = $ReadOnly<{| @@ -3076,14 +3035,11 @@ export type Props = $ReadOnly<{| multiline?: ?boolean, onBlur?: ?(e: BlurEvent) => mixed, onChange?: ?(e: ChangeEvent) => mixed, - unstable_onChangeSync?: ?(e: ChangeEvent) => mixed, onChangeText?: ?(text: string) => mixed, - unstable_onChangeTextSync?: ?(text: string) => mixed, onContentSizeChange?: ?(e: ContentSizeChangeEvent) => mixed, onEndEditing?: ?(e: EditingEvent) => mixed, onFocus?: ?(e: FocusEvent) => mixed, onKeyPress?: ?(e: KeyPressEvent) => mixed, - unstable_onKeyPressSync?: ?(e: KeyPressEvent) => mixed, onPress?: ?(event: PressEvent) => mixed, onPressIn?: ?(event: PressEvent) => mixed, onPressOut?: ?(event: PressEvent) => mixed, @@ -4519,11 +4475,16 @@ exports[`public API should not change unintentionally Libraries/Image/ImageSourc exports[`public API should not change unintentionally Libraries/Image/ImageTypes.flow.js 1`] = ` "type ImageComponentStaticsIOS = $ReadOnly<{ - getSize: ( + getSize(uri: string): Promise<{ width: number, height: number }>, + getSize( uri: string, success: (width: number, height: number) => void, failure?: (error: mixed) => void - ) => void, + ): void, + getSizeWithHeaders( + uri: string, + headers: { [string]: string, ... } + ): Promise<{ width: number, height: number }>, getSizeWithHeaders( uri: string, headers: { [string]: string, ... }, @@ -5310,6 +5271,7 @@ export type LogBoxLogData = $ReadOnly<{| message: Message, stack: Stack, category: string, + componentStackType?: ComponentStackType, componentStack: ComponentStack, codeFrame?: ?CodeFrame, isComponentError: boolean, @@ -5320,6 +5282,7 @@ declare class LogBoxLog { type: ?string; category: Category; componentStack: ComponentStack; + componentStackType: ComponentStackType; stack: Stack; count: number; level: LogLevel; @@ -5331,9 +5294,19 @@ declare class LogBoxLog { | $ReadOnly<{| error: null, stack: null, status: \\"PENDING\\" |}> | $ReadOnly<{| error: null, stack: Stack, status: \\"COMPLETE\\" |}> | $ReadOnly<{| error: Error, stack: null, status: \\"FAILED\\" |}>; + symbolicatedComponentStack: + | $ReadOnly<{| error: null, componentStack: null, status: \\"NONE\\" |}> + | $ReadOnly<{| error: null, componentStack: null, status: \\"PENDING\\" |}> + | $ReadOnly<{| + error: null, + componentStack: ComponentStack, + status: \\"COMPLETE\\", + |}> + | $ReadOnly<{| error: Error, componentStack: null, status: \\"FAILED\\" |}>; constructor(data: LogBoxLogData): void; incrementCount(): void; getAvailableStack(): Stack; + getAvailableComponentStack(): ComponentStack; retrySymbolicate(callback?: (status: SymbolicationStatus) => void): void; symbolicate(callback?: (status: SymbolicationStatus) => void): void; handleSymbolicate(callback?: (status: SymbolicationStatus) => void): void; @@ -5343,6 +5316,12 @@ declare class LogBoxLog { codeFrame: ?CodeFrame, callback?: (status: SymbolicationStatus) => void ): void; + updateComponentStackStatus( + error: ?Error, + componentStack: ?ComponentStack, + codeFrame: ?CodeFrame, + callback?: (status: SymbolicationStatus) => void + ): void; } declare export default typeof LogBoxLog; " @@ -5384,18 +5363,23 @@ export type Message = $ReadOnly<{| >, |}>; export type ComponentStack = $ReadOnlyArray; +export type ComponentStackType = \\"legacy\\" | \\"stack\\"; declare export function parseInterpolation( args: $ReadOnlyArray ): $ReadOnly<{| category: Category, message: Message, |}>; -declare export function parseComponentStack(message: string): ComponentStack; +declare export function parseComponentStack(message: string): { + type: ComponentStackType, + stack: ComponentStack, +}; declare export function parseLogBoxException( error: ExtendedExceptionData ): LogBoxLogData; declare export function parseLogBoxLog(args: $ReadOnlyArray): {| componentStack: ComponentStack, + componentStackType: ComponentStackType, category: Category, message: Message, |}; @@ -6222,9 +6206,6 @@ exports[`public API should not change unintentionally Libraries/Pressability/Pre onPressMove?: ?(event: PressEvent) => mixed, onPressOut?: ?(event: PressEvent) => mixed, blockNativeResponder?: ?boolean, - onLongPressShouldCancelPress_DEPRECATED?: ?() => boolean, - onResponderTerminationRequest_DEPRECATED?: ?() => boolean, - onStartShouldSetResponder_DEPRECATED?: ?() => boolean, |}>; export type EventHandlers = $ReadOnly<{| onBlur: (event: BlurEvent) => void, @@ -6299,7 +6280,6 @@ declare export default class Pressability { |}> ): boolean; _handleLongPress(event: PressEvent): void; - _shouldLongPressCancelPress(): boolean; _cancelHoverInDelayTimeout(): void; _cancelHoverOutDelayTimeout(): void; _cancelLongPressDelayTimeout(): void; @@ -7458,6 +7438,7 @@ export type EdgeInsetsValue = { }; export type DimensionValue = number | string | \\"auto\\" | AnimatedNode | null; export type AnimatableNumericValue = number | AnimatedNode; +export type CursorValue = \\"auto\\" | \\"pointer\\"; type ____LayoutStyle_Internal = $ReadOnly<{ display?: \\"none\\" | \\"flex\\", width?: DimensionValue, @@ -7608,6 +7589,7 @@ export type ____ViewStyle_InternalCore = $ReadOnly<{ opacity?: AnimatableNumericValue, elevation?: number, pointerEvents?: \\"auto\\" | \\"none\\" | \\"box-none\\" | \\"box-only\\", + cursor?: CursorValue, }>; export type ____ViewStyle_Internal = $ReadOnly<{ ...____ViewStyle_InternalCore, @@ -7780,8 +7762,8 @@ export type ____FlattenStyleProp_Internal< > = TStyleProp extends null | void | false | \\"\\" ? empty : TStyleProp extends $ReadOnlyArray - ? ____FlattenStyleProp_Internal - : TStyleProp; + ? ____FlattenStyleProp_Internal + : TStyleProp; " `; @@ -9026,7 +9008,6 @@ declare module.exports: { get ImageBackground(): ImageBackground, get InputAccessoryView(): InputAccessoryView, get KeyboardAvoidingView(): KeyboardAvoidingView, - get PopupMenuAndroid(): PopupMenuAndroid, get Modal(): Modal, get Pressable(): Pressable, get ProgressBarAndroid(): ProgressBarAndroid, diff --git a/packages/react-native/Libraries/__tests__/public-api-test.js b/packages/react-native/Libraries/__tests__/public-api-test.js index 2d098e84d4a796..66ff7f27556f8f 100644 --- a/packages/react-native/Libraries/__tests__/public-api-test.js +++ b/packages/react-native/Libraries/__tests__/public-api-test.js @@ -36,7 +36,6 @@ const FILES_WITH_KNOWN_ERRORS = new Set([ 'Libraries/Components/RefreshControl/RefreshControl.js', 'Libraries/Components/ScrollView/ScrollView.js', 'Libraries/Components/StatusBar/StatusBar.js', - 'Libraries/Components/TextInput/InputAccessoryView.js', 'Libraries/Components/StaticRenderer.js', 'Libraries/Components/Touchable/TouchableNativeFeedback.js', 'Libraries/Components/Touchable/TouchableWithoutFeedback.js', @@ -88,19 +87,22 @@ describe('public API', () => { return; } + let success = false; try { expect(await translateFlowToExportedAPI(source)).toMatchSnapshot(); - if (FILES_WITH_KNOWN_ERRORS.has(file)) { + success = true; + } catch (e) { + if (!FILES_WITH_KNOWN_ERRORS.has(file)) { + console.error('Unable to parse file:', file, '\n' + e); + } + } finally { + if (success && FILES_WITH_KNOWN_ERRORS.has(file)) { console.error( 'Expected parse error, please remove file exclude from FILES_WITH_KNOWN_ERRORS:', file, ); } - } catch (e) { - if (!FILES_WITH_KNOWN_ERRORS.has(file)) { - console.error('Unable to parse file:', file, '\n' + e); - } } } else { expect('UNTYPED MODULE').toMatchSnapshot(); diff --git a/packages/react-native/React/Base/RCTBridge+Private.h b/packages/react-native/React/Base/RCTBridge+Private.h index d9b2be4bab269c..6a16ae1988f9b4 100644 --- a/packages/react-native/React/Base/RCTBridge+Private.h +++ b/packages/react-native/React/Base/RCTBridge+Private.h @@ -74,11 +74,11 @@ RCT_EXTERN void RCTRegisterModule(Class); @property (nonatomic, strong, readonly) RCTModuleRegistry *moduleRegistry; /** - * The page target for this bridge, if one has been created. Exposed for RCTCxxBridge only. + * The HostTarget for this bridge, if one has been created. Exposed for RCTCxxBridge only. */ @property (nonatomic, assign, readonly) #ifdef __cplusplus - facebook::react::jsinspector_modern::PageTarget * + facebook::react::jsinspector_modern::HostTarget * #else // The inspector infrastructure cannot be used in C code. void * diff --git a/packages/react-native/React/Base/RCTBridge.mm b/packages/react-native/React/Base/RCTBridge.mm index 65d827e163be5f..ad980367083e28 100644 --- a/packages/react-native/React/Base/RCTBridge.mm +++ b/packages/react-native/React/Base/RCTBridge.mm @@ -188,9 +188,9 @@ void RCTUIManagerSetDispatchAccessibilityManagerInitOntoMain(BOOL enabled) kDispatchAccessibilityManagerInitOntoMain = enabled; } -class RCTBridgePageTargetDelegate : public facebook::react::jsinspector_modern::PageTargetDelegate { +class RCTBridgeHostTargetDelegate : public facebook::react::jsinspector_modern::HostTargetDelegate { public: - RCTBridgePageTargetDelegate(RCTBridge *bridge) : bridge_(bridge) {} + RCTBridgeHostTargetDelegate(RCTBridge *bridge) : bridge_(bridge) {} void onReload(const PageReloadRequest &request) override { @@ -208,8 +208,8 @@ @interface RCTBridge () @implementation RCTBridge { NSURL *_delegateBundleURL; - std::unique_ptr _inspectorPageDelegate; - std::shared_ptr _inspectorTarget; + std::unique_ptr _inspectorHostDelegate; + std::shared_ptr _inspectorTarget; std::optional _inspectorPageId; } @@ -259,7 +259,7 @@ - (instancetype)initWithDelegate:(id)delegate _bundleURL = bundleURL; _moduleProvider = block; _launchOptions = [launchOptions copy]; - _inspectorPageDelegate = std::make_unique(self); + _inspectorHostDelegate = std::make_unique(self); [self setUp]; } @@ -413,7 +413,7 @@ - (void)setUp auto &inspectorFlags = facebook::react::jsinspector_modern::InspectorFlags::getInstance(); if (inspectorFlags.getEnableModernCDPRegistry() && !_inspectorPageId.has_value()) { _inspectorTarget = - facebook::react::jsinspector_modern::PageTarget::create(*_inspectorPageDelegate, [](auto callback) { + facebook::react::jsinspector_modern::HostTarget::create(*_inspectorHostDelegate, [](auto callback) { RCTExecuteOnMainQueue(^{ callback(); }); @@ -526,7 +526,7 @@ - (void)registerSegmentWithId:(NSUInteger)segmentId path:(NSString *)path [self.batchedBridge registerSegmentWithId:segmentId path:path]; } -- (facebook::react::jsinspector_modern::PageTarget *)inspectorTarget +- (facebook::react::jsinspector_modern::HostTarget *)inspectorTarget { return _inspectorTarget.get(); } diff --git a/packages/react-native/React/Base/RCTBridgeProxy+Cxx.h b/packages/react-native/React/Base/RCTBridgeProxy+Cxx.h new file mode 100644 index 00000000000000..2748178a3dbb6e --- /dev/null +++ b/packages/react-native/React/Base/RCTBridgeProxy+Cxx.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#ifdef __cplusplus +#import +#endif + +#import "RCTBridgeProxy.h" + +@interface RCTBridgeProxy (Cxx) + +#ifdef __cplusplus +@property (nonatomic, readwrite) std::shared_ptr jsCallInvoker; +#endif + +@end diff --git a/packages/react-native/React/Base/RCTBridgeProxy.h b/packages/react-native/React/Base/RCTBridgeProxy.h index 79c75c3b491ae0..3a6de36473ee5b 100644 --- a/packages/react-native/React/Base/RCTBridgeProxy.h +++ b/packages/react-native/React/Base/RCTBridgeProxy.h @@ -15,6 +15,7 @@ @class RCTViewRegistry; @interface RCTBridgeProxy : NSProxy + - (instancetype)initWithViewRegistry:(RCTViewRegistry *)viewRegistry moduleRegistry:(RCTModuleRegistry *)moduleRegistry bundleManager:(RCTBundleManager *)bundleManager @@ -34,4 +35,5 @@ */ - (id)moduleForClass:(Class)moduleClass; - (id)moduleForName:(NSString *)moduleName lazilyLoadIfNecessary:(BOOL)lazilyLoad; + @end diff --git a/packages/react-native/React/Base/RCTBridgeProxy.mm b/packages/react-native/React/Base/RCTBridgeProxy.mm index 6c1e914c2f86b7..27637daf654c1c 100644 --- a/packages/react-native/React/Base/RCTBridgeProxy.mm +++ b/packages/react-native/React/Base/RCTBridgeProxy.mm @@ -6,10 +6,13 @@ */ #import "RCTBridgeProxy.h" +#import "RCTBridgeProxy+Cxx.h" + #import #import #import #import +#import #import using namespace facebook; @@ -21,6 +24,12 @@ - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel; - (void)forwardInvocation:(NSInvocation *)invocation; @end +@interface RCTBridgeProxy () + +@property (nonatomic, readwrite) std::shared_ptr jsCallInvoker; + +@end + @implementation RCTBridgeProxy { RCTUIManagerProxy *_uiManagerProxy; RCTModuleRegistry *_moduleRegistry; @@ -84,6 +93,12 @@ - (void *)runtime return _runtime; } +- (std::shared_ptr)jsCallInvoker +{ + [self logWarning:@"Please migrate to RuntimeExecutor" cmd:_cmd]; + return _jsCallInvoker; +} + /** * RCTModuleRegistry */ diff --git a/packages/react-native/React/Base/RCTBundleManager.h b/packages/react-native/React/Base/RCTBundleManager.h index 15ed245dbea80a..cd63944935a468 100644 --- a/packages/react-native/React/Base/RCTBundleManager.h +++ b/packages/react-native/React/Base/RCTBundleManager.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#import + @class RCTBridge; typedef NSURL * (^RCTBridgelessBundleURLGetter)(void); diff --git a/packages/react-native/React/Base/RCTConvert.h b/packages/react-native/React/Base/RCTConvert.h index 2d55e7c99acf12..8e8a847f6fc414 100644 --- a/packages/react-native/React/Base/RCTConvert.h +++ b/packages/react-native/React/Base/RCTConvert.h @@ -11,12 +11,22 @@ #import #import #import +#import #import #import #import #import #import +typedef NS_ENUM(NSInteger, RCTColorSpace) { + RCTColorSpaceSRGB, + RCTColorSpaceDisplayP3, +}; + +// Change the default color space +RCTColorSpace RCTGetDefaultColorSpace(void); +RCT_EXTERN void RCTSetDefaultColorSpace(RCTColorSpace colorSpace); + /** * This class provides a collection of conversion functions for mapping * JSON objects to native types and classes. These are useful when writing @@ -70,6 +80,7 @@ typedef NSURL RCTFileURL; + (UIReturnKeyType)UIReturnKeyType:(id)json; + (UIUserInterfaceStyle)UIUserInterfaceStyle:(id)json API_AVAILABLE(ios(12)); + (UIInterfaceOrientationMask)UIInterfaceOrientationMask:(NSString *)orientation; ++ (UIModalPresentationStyle)UIModalPresentationStyle:(id)json; #if !TARGET_OS_TV + (UIDataDetectorTypes)UIDataDetectorTypes:(id)json; @@ -80,6 +91,8 @@ typedef NSURL RCTFileURL; + (UIBarStyle)UIBarStyle:(id)json __deprecated; #endif ++ (RCTCursor)RCTCursor:(id)json; + + (CGFloat)CGFloat:(id)json; + (CGPoint)CGPoint:(id)json; + (CGSize)CGSize:(id)json; @@ -91,6 +104,13 @@ typedef NSURL RCTFileURL; + (CGAffineTransform)CGAffineTransform:(id)json; ++ (UIColor *)UIColorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha; ++ (UIColor *)UIColorWithRed:(CGFloat)red + green:(CGFloat)green + blue:(CGFloat)blue + alpha:(CGFloat)alpha + andColorSpace:(RCTColorSpace)colorSpace; ++ (RCTColorSpace)RCTColorSpaceFromString:(NSString *)colorSpace; + (UIColor *)UIColor:(id)json; + (CGColorRef)CGColor:(id)json CF_RETURNS_NOT_RETAINED; diff --git a/packages/react-native/React/Base/RCTConvert.mm b/packages/react-native/React/Base/RCTConvert.mm index 1367d93a873291..c4b15a1df20b52 100644 --- a/packages/react-native/React/Base/RCTConvert.mm +++ b/packages/react-native/React/Base/RCTConvert.mm @@ -510,6 +510,17 @@ + (UIKeyboardType)UIKeyboardType:(id)json RCT_DYNAMIC NSNotFound, unsignedIntegerValue) +RCT_ENUM_CONVERTER( + UIModalPresentationStyle, + (@{ + @"fullScreen" : @(UIModalPresentationFullScreen), + @"pageSheet" : @(UIModalPresentationPageSheet), + @"formSheet" : @(UIModalPresentationFormSheet), + @"overFullScreen" : @(UIModalPresentationOverFullScreen), + }), + UIModalPresentationFullScreen, + integerValue) + RCT_ENUM_CONVERTER( UIViewContentMode, (@{ @@ -545,6 +556,15 @@ + (UIKeyboardType)UIKeyboardType:(id)json RCT_DYNAMIC UIBarStyleDefault, integerValue) +RCT_ENUM_CONVERTER( + RCTCursor, + (@{ + @"auto" : @(RCTCursorAuto), + @"pointer" : @(RCTCursorPointer), + }), + RCTCursorAuto, + integerValue) + static void convertCGStruct(const char *type, NSArray *fields, CGFloat *result, id json) { NSUInteger count = fields.count; @@ -879,6 +899,48 @@ + (UIEdgeInsets)UIEdgeInsets:(id)json return names; } +// The iOS side is kept in synch with the C++ side by using the +// RCTAppDelegate which, at startup, sets the default color space. +// The usage of dispatch_once and of once_flag ensoure that those are +// set only once when the app starts and that they can't change while +// the app is running. +static RCTColorSpace _defaultColorSpace = RCTColorSpaceSRGB; +RCTColorSpace RCTGetDefaultColorSpace(void) +{ + return _defaultColorSpace; +} +void RCTSetDefaultColorSpace(RCTColorSpace colorSpace) +{ + _defaultColorSpace = colorSpace; +} + ++ (UIColor *)UIColorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha +{ + RCTColorSpace space = RCTGetDefaultColorSpace(); + return [self UIColorWithRed:red green:green blue:blue alpha:alpha andColorSpace:space]; +} ++ (UIColor *)UIColorWithRed:(CGFloat)red + green:(CGFloat)green + blue:(CGFloat)blue + alpha:(CGFloat)alpha + andColorSpace:(RCTColorSpace)colorSpace +{ + if (colorSpace == RCTColorSpaceDisplayP3) { + return [UIColor colorWithDisplayP3Red:red green:green blue:blue alpha:alpha]; + } + return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; +} + ++ (RCTColorSpace)RCTColorSpaceFromString:(NSString *)colorSpace +{ + if ([colorSpace isEqualToString:@"display-p3"]) { + return RCTColorSpaceDisplayP3; + } else if ([colorSpace isEqualToString:@"srgb"]) { + return RCTColorSpaceSRGB; + } + return RCTGetDefaultColorSpace(); +} + + (UIColor *)UIColor:(id)json { if (!json) { @@ -887,21 +949,29 @@ + (UIColor *)UIColor:(id)json if ([json isKindOfClass:[NSArray class]]) { NSArray *components = [self NSNumberArray:json]; CGFloat alpha = components.count > 3 ? [self CGFloat:components[3]] : 1.0; - return [UIColor colorWithRed:[self CGFloat:components[0]] - green:[self CGFloat:components[1]] - blue:[self CGFloat:components[2]] - alpha:alpha]; + return [self UIColorWithRed:[self CGFloat:components[0]] + green:[self CGFloat:components[1]] + blue:[self CGFloat:components[2]] + alpha:alpha]; } else if ([json isKindOfClass:[NSNumber class]]) { NSUInteger argb = [self NSUInteger:json]; CGFloat a = ((argb >> 24) & 0xFF) / 255.0; CGFloat r = ((argb >> 16) & 0xFF) / 255.0; CGFloat g = ((argb >> 8) & 0xFF) / 255.0; CGFloat b = (argb & 0xFF) / 255.0; - return [UIColor colorWithRed:r green:g blue:b alpha:a]; + return [self UIColorWithRed:r green:g blue:b alpha:a]; } else if ([json isKindOfClass:[NSDictionary class]]) { NSDictionary *dictionary = json; id value = nil; - if ((value = [dictionary objectForKey:@"semantic"])) { + NSString *rawColorSpace = [dictionary objectForKey:@"space"]; + if ([rawColorSpace isEqualToString:@"display-p3"] || [rawColorSpace isEqualToString:@"srgb"]) { + CGFloat r = [[dictionary objectForKey:@"r"] floatValue]; + CGFloat g = [[dictionary objectForKey:@"g"] floatValue]; + CGFloat b = [[dictionary objectForKey:@"b"] floatValue]; + CGFloat a = [[dictionary objectForKey:@"a"] floatValue]; + RCTColorSpace colorSpace = [self RCTColorSpaceFromString:rawColorSpace]; + return [self UIColorWithRed:r green:g blue:b alpha:a andColorSpace:colorSpace]; + } else if ((value = [dictionary objectForKey:@"semantic"])) { if ([value isKindOfClass:[NSString class]]) { NSString *semanticName = value; UIColor *color = [UIColor colorNamed:semanticName]; diff --git a/packages/react-native/React/Base/RCTJavaScriptLoader.mm b/packages/react-native/React/Base/RCTJavaScriptLoader.mm index 5330bb4d4700b9..5e8da8283244b6 100755 --- a/packages/react-native/React/Base/RCTJavaScriptLoader.mm +++ b/packages/react-native/React/Base/RCTJavaScriptLoader.mm @@ -318,9 +318,11 @@ static void attemptAsynchronousLoadOfBundleAtURL( onComplete(nil, source); } progressHandler:^(NSDictionary *headers, NSNumber *loaded, NSNumber *total) { + NSString *contentType = headers[@"Content-Type"]; + NSString *mimeType = [[contentType componentsSeparatedByString:@";"] firstObject]; // Only care about download progress events for the javascript bundle part. - if ([headers[@"Content-Type"] isEqualToString:@"application/javascript"] || - [headers[@"Content-Type"] isEqualToString:@"application/x-metro-bytecode-bundle"]) { + if ([mimeType isEqualToString:@"application/javascript"] || + [mimeType isEqualToString:@"application/x-metro-bytecode-bundle"]) { onProgress(progressEventFromDownloadProgress(loaded, total)); } }]; diff --git a/packages/react-native/React/Base/RCTUtils.m b/packages/react-native/React/Base/RCTUtils.m index 96e59e2db10181..716b5439ad0129 100644 --- a/packages/react-native/React/Base/RCTUtils.m +++ b/packages/react-native/React/Base/RCTUtils.m @@ -569,6 +569,10 @@ BOOL RCTRunningInAppExtension(void) } UIWindowScene *windowScene = (UIWindowScene *)scene; + if (@available(iOS 15.0, *)) { + return windowScene.keyWindow; + } + for (UIWindow *window in windowScene.windows) { if (window.isKeyWindow) { return window; diff --git a/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h b/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h index 47096221a7df62..3de4c5898c1558 100644 --- a/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h +++ b/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.h @@ -56,6 +56,13 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic, copy, nullable) RCTSurfaceHostingViewActivityIndicatorViewFactory activityIndicatorViewFactory; +/** + * When set to `YES`, the activity indicator is not automatically hidden when the Surface stage changes. + * In this scenario, users should invoke `hideActivityIndicator` to remove it. + * + * @param disabled: if `YES`, the auto-hide is disabled. Otherwise the loading view will be hidden automatically + */ +- (void)disableActivityIndicatorAutoHide:(BOOL)disabled; @end NS_ASSUME_NONNULL_END diff --git a/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm b/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm index 78f991eecfb091..cb4ebeba3f97f4 100644 --- a/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm +++ b/packages/react-native/React/Base/Surface/SurfaceHostingView/RCTSurfaceHostingView.mm @@ -24,6 +24,7 @@ @implementation RCTSurfaceHostingView { UIView *_Nullable _activityIndicatorView; UIView *_Nullable _surfaceView; RCTSurfaceStage _stage; + BOOL _autoHideDisabled; } RCT_NOT_IMPLEMENTED(-(instancetype)init) @@ -36,6 +37,7 @@ - (instancetype)initWithSurface:(id)surface if (self = [super initWithFrame:CGRectZero]) { _surface = surface; _sizeMeasureMode = sizeMeasureMode; + _autoHideDisabled = NO; _surface.delegate = self; _stage = surface.stage; @@ -124,6 +126,10 @@ - (void)setSizeMeasureMode:(RCTSurfaceSizeMeasureMode)sizeMeasureMode _sizeMeasureMode = sizeMeasureMode; [self _invalidateLayout]; } +- (void)disableActivityIndicatorAutoHide:(BOOL)disabled +{ + _autoHideDisabled = disabled; +} #pragma mark - isActivityIndicatorViewVisible @@ -162,7 +168,16 @@ - (void)setIsSurfaceViewVisible:(BOOL)visible _surfaceView = _surface.view; _surfaceView.frame = self.bounds; _surfaceView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - [self addSubview:_surfaceView]; + if (_activityIndicatorView && _autoHideDisabled) { + // The activity indicator is still showing and the surface is set to + // prevent the auto hide. This means that the application will take care of + // hiding it when it's ready. + // Let's add the surfaceView below the activity indicator so it's ready once + // the activity indicator is hidden. + [self insertSubview:_surfaceView belowSubview:_activityIndicatorView]; + } else { + [self addSubview:_surfaceView]; + } } else { [_surfaceView removeFromSuperview]; _surfaceView = nil; @@ -204,7 +219,7 @@ - (void)_invalidateLayout - (void)_updateViews { self.isSurfaceViewVisible = RCTSurfaceStageIsRunning(_stage); - self.isActivityIndicatorViewVisible = RCTSurfaceStageIsPreparing(_stage); + self.isActivityIndicatorViewVisible = _autoHideDisabled || RCTSurfaceStageIsPreparing(_stage); } - (void)didMoveToWindow diff --git a/packages/react-native/React/CoreModules/RCTRedBox.mm b/packages/react-native/React/CoreModules/RCTRedBox.mm index 822e17ab570baf..15cf2f023aaa4c 100644 --- a/packages/react-native/React/CoreModules/RCTRedBox.mm +++ b/packages/react-native/React/CoreModules/RCTRedBox.mm @@ -274,7 +274,13 @@ - (void)dismiss - (void)reload { - [_actionDelegate reloadFromRedBoxController:self]; + if (_actionDelegate != nil) { + [_actionDelegate reloadFromRedBoxController:self]; + } else { + // In bridgeless mode `RCTRedBox` gets deallocated, we need to notify listeners anyway. + RCTTriggerReloadCommandListeners(@"Redbox"); + [self dismiss]; + } } - (void)showExtraDataViewController diff --git a/packages/react-native/React/CoreModules/React-CoreModules.podspec b/packages/react-native/React/CoreModules/React-CoreModules.podspec index b6f2cfb1e23b97..f29771e5c3eb2b 100644 --- a/packages/react-native/React/CoreModules/React-CoreModules.podspec +++ b/packages/react-native/React/CoreModules/React-CoreModules.podspec @@ -27,7 +27,7 @@ header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", "\"$(PODS_ROOT)/DoubleConversion\"", "\"$(PODS_ROOT)/fmt/include\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", ] Pod::Spec.new do |s| @@ -59,7 +59,7 @@ Pod::Spec.new do |s| s.dependency "SocketRocket", socket_rocket_version add_dependency(s, "React-jsinspector", :framework_name => 'jsinspector_modern') - add_dependency(s, "React-Codegen") + add_dependency(s, "ReactCodegen") add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple") end diff --git a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm index a611708814e2a1..232576669771be 100644 --- a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm +++ b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm @@ -437,7 +437,7 @@ - (void)start // pointer into a member of RCTBridge! But we only use it while _reactInstance exists, meaning we // haven't been invalidated, and therefore RCTBridge hasn't been deallocated yet. RCTAssertMainQueue(); - facebook::react::jsinspector_modern::PageTarget *parentInspectorTarget = _parentBridge.inspectorTarget; + facebook::react::jsinspector_modern::HostTarget *parentInspectorTarget = _parentBridge.inspectorTarget; // Dispatch the instance initialization as soon as the initial module metadata has // been collected (see initModules) @@ -658,7 +658,7 @@ - (id)moduleForClass:(Class)moduleClass } - (void)_initializeBridge:(std::shared_ptr)executorFactory - parentInspectorTarget:(facebook::react::jsinspector_modern::PageTarget *)parentInspectorTarget + parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget { if (!self.valid) { return; @@ -691,7 +691,7 @@ - (void)_initializeBridge:(std::shared_ptr)executorFactory } - (void)_initializeBridgeLocked:(std::shared_ptr)executorFactory - parentInspectorTarget:(facebook::react::jsinspector_modern::PageTarget *)parentInspectorTarget + parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget { std::lock_guard guard(_moduleRegistryLock); @@ -1566,7 +1566,7 @@ - (void *)runtime return _reactInstance->getJavaScriptContext(); } -- (void)invokeAsync:(std::function &&)func +- (void)invokeAsync:(CallFunc &&)func { __block auto retainedFunc = std::move(func); __weak __typeof(self) weakSelf = self; diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/LegacyViewManagerInterop/RCTLegacyViewManagerInteropComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/LegacyViewManagerInterop/RCTLegacyViewManagerInteropComponentView.mm index 4dd1f7782c9dce..719d9b595f4dce 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/LegacyViewManagerInterop/RCTLegacyViewManagerInteropComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/LegacyViewManagerInterop/RCTLegacyViewManagerInteropComponentView.mm @@ -179,8 +179,8 @@ - (void)mountChildComponentView:(UIView *)childCompone - (void)unmountChildComponentView:(UIView *)childComponentView index:(NSInteger)index { - if (_adapter) { - [_adapter.paperView removeReactSubview:childComponentView]; + if (_adapter && index < _adapter.paperView.reactSubviews.count) { + [_adapter.paperView removeReactSubview:_adapter.paperView.reactSubviews[index]]; } else { [_viewsToBeUnmounted addObject:childComponentView]; } diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm index 90a9a134dcea72..265ad7a922b43f 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm @@ -752,13 +752,13 @@ - (void)_prepareForMaintainVisibleScrollPosition BOOL horizontal = _scrollView.contentSize.width > self.frame.size.width; int minIdx = props.maintainVisibleContentPosition.value().minIndexForVisible; for (NSUInteger ii = minIdx; ii < _contentView.subviews.count; ++ii) { - // Find the first entirely visible view. + // Find the first view that is partially or fully visible. UIView *subview = _contentView.subviews[ii]; BOOL hasNewView = NO; if (horizontal) { - hasNewView = subview.frame.origin.x > _scrollView.contentOffset.x; + hasNewView = subview.frame.origin.x + subview.frame.size.width > _scrollView.contentOffset.x; } else { - hasNewView = subview.frame.origin.y > _scrollView.contentOffset.y; + hasNewView = subview.frame.origin.y + subview.frame.size.height > _scrollView.contentOffset.y; } if (hasNewView || ii == _contentView.subviews.count - 1) { _prevFirstVisibleFrame = subview.frame; diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/Text/RCTParagraphComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/Text/RCTParagraphComponentView.mm index c2cc7f38f439b1..d09c6f760fd1d1 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/Text/RCTParagraphComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/Text/RCTParagraphComponentView.mm @@ -35,6 +35,7 @@ @implementation RCTParagraphComponentView { ParagraphAttributes _paragraphAttributes; RCTParagraphComponentAccessibilityProvider *_accessibilityProvider; UILongPressGestureRecognizer *_longPressGestureRecognizer; + CAShapeLayer *_highlightLayer; } - (instancetype)initWithFrame:(CGRect)frame @@ -132,7 +133,21 @@ - (void)drawRect:(CGRect)rect [nativeTextLayoutManager drawAttributedString:_state->getData().attributedString paragraphAttributes:_paragraphAttributes frame:frame - textStorage:unwrapManagedObject(nsTextStorage)]; + textStorage:unwrapManagedObject(nsTextStorage) + drawHighlightPath:^(UIBezierPath *highlightPath) { + if (highlightPath) { + if (!self->_highlightLayer) { + self->_highlightLayer = [CAShapeLayer layer]; + self->_highlightLayer.fillColor = [UIColor colorWithWhite:0 alpha:0.25].CGColor; + [self.layer addSublayer:self->_highlightLayer]; + } + self->_highlightLayer.position = frame.origin; + self->_highlightLayer.path = highlightPath.CGPath; + } else { + [self->_highlightLayer removeFromSuperlayer]; + self->_highlightLayer = nil; + } + }]; } #pragma mark - Accessibility diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm index 44e74da5cea06f..394a4a2fdaf6f2 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm @@ -336,16 +336,11 @@ - (NSString *)textInputShouldChangeText:(NSString *)text inRange:(NSRange)range if (!_backedTextInputView.textWasPasted) { if (_eventEmitter) { - KeyPressMetrics keyPressMetrics; - keyPressMetrics.text = RCTStringFromNSString(text); - keyPressMetrics.eventCount = _mostRecentEventCount; - const auto &textInputEventEmitter = static_cast(*_eventEmitter); - if (props.onKeyPressSync) { - textInputEventEmitter.onKeyPressSync(keyPressMetrics); - } else { - textInputEventEmitter.onKeyPress(keyPressMetrics); - } + textInputEventEmitter.onKeyPress({ + .text = RCTStringFromNSString(text), + .eventCount = static_cast(_mostRecentEventCount), + }); } } @@ -391,12 +386,7 @@ - (void)textInputDidChange if (_eventEmitter) { const auto &textInputEventEmitter = static_cast(*_eventEmitter); - const auto &props = static_cast(*_props); - if (props.onChangeSync) { - textInputEventEmitter.onChangeSync([self _textInputMetrics]); - } else { - textInputEventEmitter.onChange([self _textInputMetrics]); - } + textInputEventEmitter.onChange([self _textInputMetrics]); } } @@ -524,29 +514,18 @@ - (void)handleInputAccessoryDoneButton #pragma mark - Other -- (TextInputMetrics)_textInputMetrics -{ - TextInputMetrics metrics; - metrics.text = RCTStringFromNSString(_backedTextInputView.attributedText.string); - metrics.selectionRange = [self _selectionRange]; - metrics.eventCount = _mostRecentEventCount; - - CGPoint contentOffset = _backedTextInputView.contentOffset; - metrics.contentOffset = {contentOffset.x, contentOffset.y}; - - UIEdgeInsets contentInset = _backedTextInputView.contentInset; - metrics.contentInset = {contentInset.left, contentInset.top, contentInset.right, contentInset.bottom}; - - CGSize contentSize = _backedTextInputView.contentSize; - metrics.contentSize = {contentSize.width, contentSize.height}; - - CGSize layoutMeasurement = _backedTextInputView.bounds.size; - metrics.layoutMeasurement = {layoutMeasurement.width, layoutMeasurement.height}; - - CGFloat zoomScale = _backedTextInputView.zoomScale; - metrics.zoomScale = zoomScale; - - return metrics; +- (TextInputEventEmitter::Metrics)_textInputMetrics +{ + return { + .text = RCTStringFromNSString(_backedTextInputView.attributedText.string), + .selectionRange = [self _selectionRange], + .eventCount = static_cast(_mostRecentEventCount), + .contentOffset = RCTPointFromCGPoint(_backedTextInputView.contentOffset), + .contentInset = RCTEdgeInsetsFromUIEdgeInsets(_backedTextInputView.contentInset), + .contentSize = RCTSizeFromCGSize(_backedTextInputView.contentSize), + .layoutMeasurement = RCTSizeFromCGSize(_backedTextInputView.bounds.size), + .zoomScale = _backedTextInputView.zoomScale, + }; } - (void)_updateState diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm index a015c450ee21b7..8b9f511d89aa57 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm @@ -257,6 +257,11 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared & self.layer.doubleSided = newViewProps.backfaceVisibility == BackfaceVisibility::Visible; } + // `cursor` + if (oldViewProps.cursor != newViewProps.cursor) { + needsInvalidateLayer = YES; + } + // `shouldRasterize` if (oldViewProps.shouldRasterize != newViewProps.shouldRasterize) { self.layer.shouldRasterize = newViewProps.shouldRasterize; @@ -592,6 +597,33 @@ - (void)invalidateLayer layer.shadowPath = nil; } +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 170000 /* __IPHONE_17_0 */ + // Stage 1.5. Cursor / Hover Effects + if (@available(iOS 17.0, *)) { + UIHoverStyle *hoverStyle = nil; + if (_props->cursor == Cursor::Pointer) { + const RCTCornerInsets cornerInsets = + RCTGetCornerInsets(RCTCornerRadiiFromBorderRadii(borderMetrics.borderRadii), UIEdgeInsetsZero); +#if TARGET_OS_IOS + // Due to an Apple bug, it seems on iOS, UIShapes made with `[UIShape shapeWithBezierPath:]` + // evaluate their shape on the superviews' coordinate space. This leads to the hover shape + // rendering incorrectly on iOS, iOS apps in compatibility mode on visionOS, but not on visionOS. + // To work around this, for iOS, we can calculate the border path based on `view.frame` (the + // superview's coordinate space) instead of view.bounds. + CGPathRef borderPath = RCTPathCreateWithRoundedRect(self.frame, cornerInsets, NULL); +#else // TARGET_OS_VISION + CGPathRef borderPath = RCTPathCreateWithRoundedRect(self.bounds, cornerInsets, NULL); +#endif + UIBezierPath *bezierPath = [UIBezierPath bezierPathWithCGPath:borderPath]; + CGPathRelease(borderPath); + UIShape *shape = [UIShape shapeWithBezierPath:bezierPath]; + + hoverStyle = [UIHoverStyle styleWithEffect:[UIHoverAutomaticEffect effect] shape:shape]; + } + [self setHoverStyle:hoverStyle]; + } +#endif + // Stage 2. Border Rendering const bool useCoreAnimationBorderRendering = borderMetrics.borderColors.isUniform() && borderMetrics.borderWidths.isUniform() && diff --git a/packages/react-native/React/Fabric/RCTScheduler.h b/packages/react-native/React/Fabric/RCTScheduler.h index 888770cfd9fea0..9af355aa006bf1 100644 --- a/packages/react-native/React/Fabric/RCTScheduler.h +++ b/packages/react-native/React/Fabric/RCTScheduler.h @@ -21,8 +21,6 @@ NS_ASSUME_NONNULL_BEGIN -@class RCTMountingManager; - /** * Exactly same semantic as `facebook::react::SchedulerDelegate`. */ diff --git a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm index 4c1e048c4063f2..712d2cfe5e4dca 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -265,10 +265,6 @@ - (RCTScheduler *)_createScheduler CoreFeatures::enableGranularScrollViewStateUpdatesIOS = true; } - if (reactNativeConfig && reactNativeConfig->getBool("react_fabric:enable_mount_hooks_ios")) { - CoreFeatures::enableMountHooks = true; - } - if (reactNativeConfig && reactNativeConfig->getBool("react_fabric:enable_cloneless_state_progression")) { CoreFeatures::enableClonelessStateProgression = true; } diff --git a/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.h b/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.h new file mode 100644 index 00000000000000..68456babda3ba8 --- /dev/null +++ b/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#import + +@interface RCTColorSpaceUtils : NSObject + ++ (void)applyDefaultColorSpace:(RCTColorSpace)colorSpace; + +@end diff --git a/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.mm b/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.mm new file mode 100644 index 00000000000000..051547ecf595c4 --- /dev/null +++ b/packages/react-native/React/Fabric/Utils/RCTColorSpaceUtils.mm @@ -0,0 +1,23 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RCTColorSpaceUtils.h" + +#import + +@implementation RCTColorSpaceUtils + ++ (void)applyDefaultColorSpace:(RCTColorSpace)colorSpace +{ + facebook::react::ColorSpace cxxColorSpace = + colorSpace == RCTColorSpaceSRGB ? facebook::react::ColorSpace::sRGB : facebook::react::ColorSpace::DisplayP3; + + RCTSetDefaultColorSpace(colorSpace); + facebook::react::setDefaultColorSpace(cxxColorSpace); +} + +@end diff --git a/packages/react-native/React/Modules/RCTUIManager.m b/packages/react-native/React/Modules/RCTUIManager.m index f5e5c7c7a82aca..1fb21d07338e64 100644 --- a/packages/react-native/React/Modules/RCTUIManager.m +++ b/packages/react-native/React/Modules/RCTUIManager.m @@ -1674,8 +1674,8 @@ - (instancetype)initWithUIManager:(RCTUIManager *)uiManager andRegistry:(NSDicti { self = [super init]; if (self) { - self->_uiManager = uiManager; - self->_registry = registry; + _uiManager = uiManager; + _registry = registry; } return self; } @@ -1683,19 +1683,19 @@ - (instancetype)initWithUIManager:(RCTUIManager *)uiManager andRegistry:(NSDicti - (id)objectForKey:(id)key { if (![key isKindOfClass:[NSNumber class]]) { - return [super objectForKeyedSubscript:key]; + return [super objectForKey:key]; } NSNumber *index = (NSNumber *)key; - UIView *view = [_uiManager viewForReactTag:index]; + UIView *view = _registry[index]; if (view) { return [RCTUIManager paperViewOrCurrentView:view]; } - view = _registry[index]; + view = [_uiManager viewForReactTag:index]; if (view) { return [RCTUIManager paperViewOrCurrentView:view]; } - return [super objectForKeyedSubscript:key]; + return [super objectForKey:key]; } - (void)removeObjectForKey:(id)key diff --git a/packages/react-native/React/React-RCTFabric.podspec b/packages/react-native/React/React-RCTFabric.podspec index 5781df022f9b6a..9a28eeec44dc51 100644 --- a/packages/react-native/React/React-RCTFabric.podspec +++ b/packages/react-native/React/React-RCTFabric.podspec @@ -30,7 +30,7 @@ header_search_paths = [ "\"$(PODS_ROOT)/RCT-Folly\"", "\"$(PODS_ROOT)/Headers/Private/React-Core\"", "\"$(PODS_ROOT)/Headers/Private/Yoga\"", - "\"$(PODS_ROOT)/Headers/Public/React-Codegen\"", + "\"$(PODS_ROOT)/Headers/Public/ReactCodegen\"", ] if ENV['USE_FRAMEWORKS'] diff --git a/packages/react-native/React/Views/RCTCursor.h b/packages/react-native/React/Views/RCTCursor.h new file mode 100644 index 00000000000000..63fcb3e123e390 --- /dev/null +++ b/packages/react-native/React/Views/RCTCursor.h @@ -0,0 +1,13 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +typedef NS_ENUM(NSInteger, RCTCursor) { + RCTCursorAuto, + RCTCursorPointer, +}; diff --git a/packages/react-native/React/Views/RCTModalHostViewManager.h b/packages/react-native/React/Views/RCTModalHostViewManager.h index 11b52984b30834..d2694ea26fd186 100644 --- a/packages/react-native/React/Views/RCTModalHostViewManager.h +++ b/packages/react-native/React/Views/RCTModalHostViewManager.h @@ -9,12 +9,6 @@ #import #import -@interface RCTConvert (RCTModalHostView) - -+ (UIModalPresentationStyle)UIModalPresentationStyle:(id)json; - -@end - typedef void (^RCTModalViewInteractionBlock)( UIViewController *reactViewController, UIViewController *viewController, diff --git a/packages/react-native/React/Views/RCTModalHostViewManager.m b/packages/react-native/React/Views/RCTModalHostViewManager.m index b0295e05ae4d54..eccf05f9cb6795 100644 --- a/packages/react-native/React/Views/RCTModalHostViewManager.m +++ b/packages/react-native/React/Views/RCTModalHostViewManager.m @@ -14,21 +14,6 @@ #import "RCTShadowView.h" #import "RCTUtils.h" -@implementation RCTConvert (RCTModalHostView) - -RCT_ENUM_CONVERTER( - UIModalPresentationStyle, - (@{ - @"fullScreen" : @(UIModalPresentationFullScreen), - @"pageSheet" : @(UIModalPresentationPageSheet), - @"formSheet" : @(UIModalPresentationFormSheet), - @"overFullScreen" : @(UIModalPresentationOverFullScreen), - }), - UIModalPresentationFullScreen, - integerValue) - -@end - @interface RCTModalHostShadowView : RCTShadowView @end diff --git a/packages/react-native/React/Views/RCTView.h b/packages/react-native/React/Views/RCTView.h index 200d8b451bf59e..8abda6e8538d79 100644 --- a/packages/react-native/React/Views/RCTView.h +++ b/packages/react-native/React/Views/RCTView.h @@ -10,6 +10,7 @@ #import #import #import +#import #import extern const UIAccessibilityTraits SwitchAccessibilityTrait; @@ -120,6 +121,8 @@ extern const UIAccessibilityTraits SwitchAccessibilityTrait; */ @property (nonatomic, assign) UIEdgeInsets hitTestEdgeInsets; +@property (nonatomic, assign) RCTCursor cursor; + /** * (Experimental and unused for Paper) Pointer event handlers. */ diff --git a/packages/react-native/React/Views/RCTView.m b/packages/react-native/React/Views/RCTView.m index 6e6f9cd2761035..3a8658100332fe 100644 --- a/packages/react-native/React/Views/RCTView.m +++ b/packages/react-native/React/Views/RCTView.m @@ -136,6 +136,7 @@ - (instancetype)initWithFrame:(CGRect)frame _borderCurve = RCTBorderCurveCircular; _borderStyle = RCTBorderStyleSolid; _hitTestEdgeInsets = UIEdgeInsetsZero; + _cursor = RCTCursorAuto; _backgroundColor = super.backgroundColor; } @@ -796,6 +797,8 @@ - (void)displayLayer:(CALayer *)layer RCTUpdateShadowPathForView(self); + RCTUpdateHoverStyleForView(self); + const RCTCornerRadii cornerRadii = [self cornerRadii]; const UIEdgeInsets borderInsets = [self bordersAsInsets]; const RCTBorderColors borderColors = [self borderColorsWithTraitCollection:self.traitCollection]; @@ -891,6 +894,33 @@ static void RCTUpdateShadowPathForView(RCTView *view) } } +static void RCTUpdateHoverStyleForView(RCTView *view) +{ +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 170000 /* __IPHONE_17_0 */ + if (@available(iOS 17.0, *)) { + UIHoverStyle *hoverStyle = nil; + if ([view cursor] == RCTCursorPointer) { + const RCTCornerRadii cornerRadii = [view cornerRadii]; + const RCTCornerInsets cornerInsets = RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero); +#if TARGET_OS_IOS + // Due to an Apple bug, it seems on iOS, `[UIShape shapeWithBezierPath:]` needs to + // be calculated in the superviews' coordinate space (view.frame). This is not true + // on other platforms like visionOS. + CGPathRef borderPath = RCTPathCreateWithRoundedRect(view.frame, cornerInsets, NULL); +#else // TARGET_OS_VISION + CGPathRef borderPath = RCTPathCreateWithRoundedRect(view.bounds, cornerInsets, NULL); +#endif + UIBezierPath *bezierPath = [UIBezierPath bezierPathWithCGPath:borderPath]; + CGPathRelease(borderPath); + UIShape *shape = [UIShape shapeWithBezierPath:bezierPath]; + + hoverStyle = [UIHoverStyle styleWithEffect:[UIHoverHighlightEffect effect] shape:shape]; + } + [view setHoverStyle:hoverStyle]; + } +#endif +} + - (void)updateClippingForLayer:(CALayer *)layer { CALayer *mask = nil; diff --git a/packages/react-native/React/Views/RCTViewManager.m b/packages/react-native/React/Views/RCTViewManager.m index 66c449d7e81a00..0a0126545bde5f 100644 --- a/packages/react-native/React/Views/RCTViewManager.m +++ b/packages/react-native/React/Views/RCTViewManager.m @@ -13,6 +13,7 @@ #import "RCTBridge.h" #import "RCTConvert+Transform.h" #import "RCTConvert.h" +#import "RCTCursor.h" #import "RCTLog.h" #import "RCTShadowView.h" #import "RCTUIManager.h" @@ -195,6 +196,7 @@ - (RCTShadowView *)shadowView RCT_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) RCT_REMAP_VIEW_PROPERTY(backfaceVisibility, layer.doubleSided, css_backface_visibility_t) +RCT_EXPORT_VIEW_PROPERTY(cursor, RCTCursor) RCT_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) RCT_REMAP_VIEW_PROPERTY(shadowColor, layer.shadowColor, CGColor) RCT_REMAP_VIEW_PROPERTY(shadowOffset, layer.shadowOffset, CGSize) diff --git a/packages/react-native/React/Views/ScrollView/RCTScrollView.m b/packages/react-native/React/Views/ScrollView/RCTScrollView.m index 1aead514ac3fa5..7dd55cf33487b6 100644 --- a/packages/react-native/React/Views/ScrollView/RCTScrollView.m +++ b/packages/react-native/React/Views/ScrollView/RCTScrollView.m @@ -939,19 +939,19 @@ - (void)uiManagerWillPerformMounting:(RCTUIManager *)manager BOOL horz = [self isHorizontal:self->_scrollView]; NSUInteger minIdx = [self->_maintainVisibleContentPosition[@"minIndexForVisible"] integerValue]; for (NSUInteger ii = minIdx; ii < self->_contentView.subviews.count; ++ii) { - // Find the first entirely visible view. This must be done after we update the content offset + // Find the first partially or fully visible view. This must be done after we update the content offset // or it will tend to grab rows that were made visible by the shift in position UIView *subview = self->_contentView.subviews[ii]; BOOL hasNewView = NO; if (horz) { CGFloat leftInset = self.inverted ? self->_scrollView.contentInset.right : self->_scrollView.contentInset.left; CGFloat x = self->_scrollView.contentOffset.x + leftInset; - hasNewView = subview.frame.origin.x > x; + hasNewView = subview.frame.origin.x + subview.frame.size.width > x; } else { CGFloat bottomInset = self.inverted ? self->_scrollView.contentInset.top : self->_scrollView.contentInset.bottom; CGFloat y = self->_scrollView.contentOffset.y + bottomInset; - hasNewView = subview.frame.origin.y > y; + hasNewView = subview.frame.origin.y + subview.frame.size.height > y; } if (hasNewView || ii == self->_contentView.subviews.count - 1) { self->_prevFirstVisibleFrame = subview.frame; diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 24271f239edd3a..173b7b75813eec 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -108,7 +108,6 @@ public class com/facebook/react/ReactActivityDelegate { public fun (Lcom/facebook/react/ReactActivity;Ljava/lang/String;)V protected fun composeLaunchOptions ()Landroid/os/Bundle; protected fun createRootView ()Lcom/facebook/react/ReactRootView; - protected fun createRootView (Landroid/os/Bundle;)Lcom/facebook/react/ReactRootView; protected fun getContext ()Landroid/content/Context; protected fun getLaunchOptions ()Landroid/os/Bundle; public fun getMainComponentName ()Ljava/lang/String; @@ -121,15 +120,15 @@ public class com/facebook/react/ReactActivityDelegate { public fun onActivityResult (IILandroid/content/Intent;)V public fun onBackPressed ()Z public fun onConfigurationChanged (Landroid/content/res/Configuration;)V - protected fun onCreate (Landroid/os/Bundle;)V - protected fun onDestroy ()V + public fun onCreate (Landroid/os/Bundle;)V + public fun onDestroy ()V public fun onKeyDown (ILandroid/view/KeyEvent;)Z public fun onKeyLongPress (ILandroid/view/KeyEvent;)Z public fun onKeyUp (ILandroid/view/KeyEvent;)Z public fun onNewIntent (Landroid/content/Intent;)Z - protected fun onPause ()V + public fun onPause ()V public fun onRequestPermissionsResult (I[Ljava/lang/String;[I)V - protected fun onResume ()V + public fun onResume ()V public fun onWindowFocusChanged (Z)V public fun requestPermissions ([Ljava/lang/String;ILcom/facebook/react/modules/core/PermissionListener;)V } @@ -151,9 +150,14 @@ public class com/facebook/react/ReactDelegate { public fun loadApp (Ljava/lang/String;)V public fun onActivityResult (IILandroid/content/Intent;Z)V public fun onBackPressed ()Z + public fun onConfigurationChanged (Landroid/content/res/Configuration;)V public fun onHostDestroy ()V public fun onHostPause ()V public fun onHostResume ()V + public fun onKeyDown (ILandroid/view/KeyEvent;)Z + public fun onKeyLongPress (I)Z + public fun onNewIntent (Landroid/content/Intent;)Z + public fun onWindowFocusChanged (Z)V public fun shouldShowDevMenuOrReload (ILandroid/view/KeyEvent;)Z } @@ -195,14 +199,19 @@ public abstract interface class com/facebook/react/ReactHost { public abstract fun getDevSupportManager ()Lcom/facebook/react/devsupport/interfaces/DevSupportManager; public abstract fun getJsEngineResolutionAlgorithm ()Lcom/facebook/react/JSEngineResolutionAlgorithm; public abstract fun getLifecycleState ()Lcom/facebook/react/common/LifecycleState; + public abstract fun getMemoryPressureRouter ()Lcom/facebook/react/MemoryPressureRouter; public abstract fun getReactQueueConfiguration ()Lcom/facebook/react/bridge/queue/ReactQueueConfiguration; + public abstract fun onActivityResult (Landroid/app/Activity;IILandroid/content/Intent;)V public abstract fun onBackPressed ()Z + public abstract fun onConfigurationChanged (Landroid/content/Context;)V public abstract fun onHostDestroy ()V public abstract fun onHostDestroy (Landroid/app/Activity;)V public abstract fun onHostPause ()V public abstract fun onHostPause (Landroid/app/Activity;)V public abstract fun onHostResume (Landroid/app/Activity;)V public abstract fun onHostResume (Landroid/app/Activity;Lcom/facebook/react/modules/core/DefaultHardwareBackBtnHandler;)V + public abstract fun onNewIntent (Landroid/content/Intent;)V + public abstract fun onWindowFocusChange (Z)V public abstract fun reload (Ljava/lang/String;)Lcom/facebook/react/interfaces/TaskInterface; public abstract fun removeBeforeDestroyListener (Lkotlin/jvm/functions/Function0;)V public abstract fun setJsEngineResolutionAlgorithm (Lcom/facebook/react/JSEngineResolutionAlgorithm;)V @@ -322,7 +331,7 @@ public abstract class com/facebook/react/ReactPackageTurboModuleManagerDelegate protected fun (Lcom/facebook/react/bridge/ReactApplicationContext;Ljava/util/List;Lcom/facebook/jni/HybridData;)V public fun getEagerInitModuleNames ()Ljava/util/List; public fun getLegacyModule (Ljava/lang/String;)Lcom/facebook/react/bridge/NativeModule; - public fun getModule (Ljava/lang/String;)Lcom/facebook/react/internal/turbomodule/core/interfaces/TurboModule; + public fun getModule (Ljava/lang/String;)Lcom/facebook/react/turbomodule/core/interfaces/TurboModule; public fun unstable_enableSyncVoidMethods ()Z public fun unstable_isLegacyModuleRegistered (Ljava/lang/String;)Z public fun unstable_isModuleRegistered (Ljava/lang/String;)Z @@ -823,6 +832,7 @@ public class com/facebook/react/bridge/JavaOnlyArray : com/facebook/react/bridge public fun getDouble (I)D public fun getDynamic (I)Lcom/facebook/react/bridge/Dynamic; public fun getInt (I)I + public fun getLong (I)J public fun getMap (I)Lcom/facebook/react/bridge/ReadableMap; public fun getString (I)Ljava/lang/String; public fun getType (I)Lcom/facebook/react/bridge/ReadableType; @@ -833,6 +843,7 @@ public class com/facebook/react/bridge/JavaOnlyArray : com/facebook/react/bridge public fun pushBoolean (Z)V public fun pushDouble (D)V public fun pushInt (I)V + public fun pushLong (J)V public fun pushMap (Lcom/facebook/react/bridge/ReadableMap;)V public fun pushNull ()V public fun pushString (Ljava/lang/String;)V @@ -853,6 +864,7 @@ public class com/facebook/react/bridge/JavaOnlyMap : com/facebook/react/bridge/R public fun getDynamic (Ljava/lang/String;)Lcom/facebook/react/bridge/Dynamic; public fun getEntryIterator ()Ljava/util/Iterator; public fun getInt (Ljava/lang/String;)I + public fun getLong (Ljava/lang/String;)J public fun getMap (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableMap; public fun getString (Ljava/lang/String;)Ljava/lang/String; public fun getType (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableType; @@ -866,6 +878,7 @@ public class com/facebook/react/bridge/JavaOnlyMap : com/facebook/react/bridge/R public fun putBoolean (Ljava/lang/String;Z)V public fun putDouble (Ljava/lang/String;D)V public fun putInt (Ljava/lang/String;I)V + public fun putLong (Ljava/lang/String;J)V public fun putMap (Ljava/lang/String;Lcom/facebook/react/bridge/ReadableMap;)V public fun putNull (Ljava/lang/String;)V public fun putString (Ljava/lang/String;Ljava/lang/String;)V @@ -949,6 +962,10 @@ public abstract class com/facebook/react/bridge/NativeArray : com/facebook/react public fun toString ()Ljava/lang/String; } +public abstract interface class com/facebook/react/bridge/NativeArrayInterface { + public abstract fun toString ()Ljava/lang/String; +} + public abstract class com/facebook/react/bridge/NativeMap { public fun (Lcom/facebook/jni/HybridData;)V public fun toString ()Ljava/lang/String; @@ -1322,6 +1339,7 @@ public abstract interface class com/facebook/react/bridge/ReadableArray { public abstract fun getDouble (I)D public abstract fun getDynamic (I)Lcom/facebook/react/bridge/Dynamic; public abstract fun getInt (I)I + public abstract fun getLong (I)J public abstract fun getMap (I)Lcom/facebook/react/bridge/ReadableMap; public abstract fun getString (I)Ljava/lang/String; public abstract fun getType (I)Lcom/facebook/react/bridge/ReadableType; @@ -1337,6 +1355,7 @@ public abstract interface class com/facebook/react/bridge/ReadableMap { public abstract fun getDynamic (Ljava/lang/String;)Lcom/facebook/react/bridge/Dynamic; public abstract fun getEntryIterator ()Ljava/util/Iterator; public abstract fun getInt (Ljava/lang/String;)I + public abstract fun getLong (Ljava/lang/String;)J public abstract fun getMap (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableMap; public abstract fun getString (Ljava/lang/String;)Ljava/lang/String; public abstract fun getType (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableType; @@ -1361,6 +1380,7 @@ public class com/facebook/react/bridge/ReadableNativeArray : com/facebook/react/ public fun getDynamic (I)Lcom/facebook/react/bridge/Dynamic; public fun getInt (I)I public static fun getJNIPassCounter ()I + public fun getLong (I)J public synthetic fun getMap (I)Lcom/facebook/react/bridge/ReadableMap; public fun getMap (I)Lcom/facebook/react/bridge/ReadableNativeMap; public fun getString (I)Ljava/lang/String; @@ -1381,6 +1401,7 @@ public class com/facebook/react/bridge/ReadableNativeMap : com/facebook/react/br public fun getEntryIterator ()Ljava/util/Iterator; public fun getInt (Ljava/lang/String;)I public static fun getJNIPassCounter ()I + public fun getLong (Ljava/lang/String;)J public synthetic fun getMap (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableMap; public fun getMap (Ljava/lang/String;)Lcom/facebook/react/bridge/ReadableNativeMap; public fun getString (Ljava/lang/String;)Ljava/lang/String; @@ -1448,14 +1469,6 @@ public abstract interface class com/facebook/react/bridge/UIManager : com/facebo public abstract fun updateRootLayoutSpecs (IIIII)V } -public abstract interface class com/facebook/react/bridge/UIManagerListener { - public abstract fun didDispatchMountItems (Lcom/facebook/react/bridge/UIManager;)V - public abstract fun didMountItems (Lcom/facebook/react/bridge/UIManager;)V - public abstract fun didScheduleMountItems (Lcom/facebook/react/bridge/UIManager;)V - public abstract fun willDispatchViewUpdates (Lcom/facebook/react/bridge/UIManager;)V - public abstract fun willMountItems (Lcom/facebook/react/bridge/UIManager;)V -} - public abstract interface class com/facebook/react/bridge/UIManagerProvider { public abstract fun createUIManager (Lcom/facebook/react/bridge/ReactApplicationContext;)Lcom/facebook/react/bridge/UIManager; } @@ -1484,6 +1497,7 @@ public abstract interface class com/facebook/react/bridge/WritableArray : com/fa public abstract fun pushBoolean (Z)V public abstract fun pushDouble (D)V public abstract fun pushInt (I)V + public abstract fun pushLong (J)V public abstract fun pushMap (Lcom/facebook/react/bridge/ReadableMap;)V public abstract fun pushNull ()V public abstract fun pushString (Ljava/lang/String;)V @@ -1496,6 +1510,7 @@ public abstract interface class com/facebook/react/bridge/WritableMap : com/face public abstract fun putBoolean (Ljava/lang/String;Z)V public abstract fun putDouble (Ljava/lang/String;D)V public abstract fun putInt (Ljava/lang/String;I)V + public abstract fun putLong (Ljava/lang/String;J)V public abstract fun putMap (Ljava/lang/String;Lcom/facebook/react/bridge/ReadableMap;)V public abstract fun putNull (Ljava/lang/String;)V public abstract fun putString (Ljava/lang/String;Ljava/lang/String;)V @@ -1507,6 +1522,7 @@ public class com/facebook/react/bridge/WritableNativeArray : com/facebook/react/ public fun pushBoolean (Z)V public fun pushDouble (D)V public fun pushInt (I)V + public fun pushLong (J)V public fun pushMap (Lcom/facebook/react/bridge/ReadableMap;)V public fun pushNull ()V public fun pushString (Ljava/lang/String;)V @@ -1520,6 +1536,7 @@ public class com/facebook/react/bridge/WritableNativeMap : com/facebook/react/br public fun putBoolean (Ljava/lang/String;Z)V public fun putDouble (Ljava/lang/String;D)V public fun putInt (Ljava/lang/String;I)V + public fun putLong (Ljava/lang/String;J)V public fun putMap (Ljava/lang/String;Lcom/facebook/react/bridge/ReadableMap;)V public fun putNull (Ljava/lang/String;)V public fun putString (Ljava/lang/String;Ljava/lang/String;)V @@ -1801,6 +1818,7 @@ public abstract interface class com/facebook/react/common/mapbuffer/MapBuffer : public abstract fun getDouble (I)D public abstract fun getInt (I)I public abstract fun getKeyOffset (I)I + public abstract fun getLong (I)J public abstract fun getMapBuffer (I)Lcom/facebook/react/common/mapbuffer/MapBuffer; public abstract fun getMapBufferList (I)Ljava/util/List; public abstract fun getString (I)Ljava/lang/String; @@ -1814,6 +1832,7 @@ public final class com/facebook/react/common/mapbuffer/MapBuffer$DataType : java public static final field BOOL Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; public static final field DOUBLE Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; public static final field INT Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; + public static final field LONG Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; public static final field MAP Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; public static final field STRING Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; public static fun valueOf (Ljava/lang/String;)Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; @@ -1825,6 +1844,7 @@ public abstract interface class com/facebook/react/common/mapbuffer/MapBuffer$En public abstract fun getDoubleValue ()D public abstract fun getIntValue ()I public abstract fun getKey ()I + public abstract fun getLongValue ()J public abstract fun getMapBufferValue ()Lcom/facebook/react/common/mapbuffer/MapBuffer; public abstract fun getStringValue ()Ljava/lang/String; public abstract fun getType ()Lcom/facebook/react/common/mapbuffer/MapBuffer$DataType; @@ -1845,6 +1865,7 @@ public final class com/facebook/react/common/mapbuffer/ReadableMapBuffer : com/f public fun getDouble (I)D public fun getInt (I)I public fun getKeyOffset (I)I + public fun getLong (I)J public synthetic fun getMapBuffer (I)Lcom/facebook/react/common/mapbuffer/MapBuffer; public fun getMapBuffer (I)Lcom/facebook/react/common/mapbuffer/ReadableMapBuffer; public fun getMapBufferList (I)Ljava/util/List; @@ -1867,6 +1888,7 @@ public final class com/facebook/react/common/mapbuffer/WritableMapBuffer : com/f public fun getDouble (I)D public fun getInt (I)I public fun getKeyOffset (I)I + public fun getLong (I)J public fun getMapBuffer (I)Lcom/facebook/react/common/mapbuffer/MapBuffer; public fun getMapBufferList (I)Ljava/util/List; public fun getString (I)Ljava/lang/String; @@ -1874,6 +1896,7 @@ public final class com/facebook/react/common/mapbuffer/WritableMapBuffer : com/f public fun iterator ()Ljava/util/Iterator; public final fun put (ID)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; public final fun put (II)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; + public final fun put (IJ)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; public final fun put (ILcom/facebook/react/common/mapbuffer/MapBuffer;)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; public final fun put (ILjava/lang/String;)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; public final fun put (IZ)Lcom/facebook/react/common/mapbuffer/WritableMapBuffer; @@ -1888,7 +1911,6 @@ public class com/facebook/react/config/ReactFeatureFlags { public static field dispatchPointerEvents Z public static field enableBridgelessArchitecture Z public static field enableBridgelessArchitectureNewCreateReloadDestroy Z - public static field enableBridgelessArchitectureSoftExceptions Z public static field enableClonelessStateProgression Z public static field enableCppPropsIteratorSetter Z public static field enableEagerRootViewAttachment Z @@ -1896,14 +1918,12 @@ public class com/facebook/react/config/ReactFeatureFlags { public static field enableFabricPendingEventQueue Z public static field enableFabricRenderer Z public static field enableFabricRendererExclusively Z - public static field enableMountHooks Z public static field enableRemoveDeleteTreeInstruction Z public static field enableTextSpannableCache Z public static field enableViewRecycling Z public static field excludeYogaFromRawProps Z public static field rejectTurboModulePromiseOnNativeError Z public static field traceTurboModulePromiseRejections Z - public static field unstable_bridgelessArchitectureMemoryPressureHackyBoltsFix Z public static field unstable_enableTurboModuleSyncVoidMethods Z public static field unstable_useFabricInterop Z public static field unstable_useTurboModuleInterop Z @@ -1940,8 +1960,6 @@ public class com/facebook/react/defaults/DefaultReactActivityDelegate : com/face public fun (Lcom/facebook/react/ReactActivity;Ljava/lang/String;Z)V public synthetic fun (Lcom/facebook/react/ReactActivity;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V public fun (Lcom/facebook/react/ReactActivity;Ljava/lang/String;ZZ)V - protected fun createRootView ()Lcom/facebook/react/ReactRootView; - protected fun createRootView (Landroid/os/Bundle;)Lcom/facebook/react/ReactRootView; protected fun isFabricEnabled ()Z } @@ -2634,14 +2652,6 @@ public class com/facebook/react/fabric/events/FabricEventEmitter : com/facebook/ public fun receiveTouches (Ljava/lang/String;Lcom/facebook/react/bridge/WritableArray;Lcom/facebook/react/bridge/WritableArray;)V } -public abstract interface class com/facebook/react/fabric/interop/UIBlock { - public abstract fun execute (Lcom/facebook/react/fabric/interop/UIBlockViewResolver;)V -} - -public abstract interface class com/facebook/react/fabric/interop/UIBlockViewResolver { - public abstract fun resolveView (I)Landroid/view/View; -} - public abstract interface class com/facebook/react/fabric/mounting/LayoutMetricsConversions { public static fun getMaxSize (I)F public static fun getMinSize (I)F @@ -2856,6 +2866,7 @@ public class com/facebook/react/module/model/ReactModuleInfo { public fun (Ljava/lang/String;Ljava/lang/String;ZZZZ)V public fun (Ljava/lang/String;Ljava/lang/String;ZZZZZ)V public fun canOverrideExistingModule ()Z + public static fun classIsTurboModule (Ljava/lang/Class;)Z public fun className ()Ljava/lang/String; public fun hasConstants ()Z public fun isCxxModule ()Z @@ -3025,7 +3036,7 @@ public abstract interface class com/facebook/react/modules/core/JavaScriptTimerE public abstract fun emitTimeDriftWarning (Ljava/lang/String;)V } -public class com/facebook/react/modules/core/JavaTimerManager { +public class com/facebook/react/modules/core/JavaTimerManager : com/facebook/react/bridge/LifecycleEventListener, com/facebook/react/jstasks/HeadlessJsTaskEventListener { public fun (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/react/modules/core/JavaScriptTimerExecutor;Lcom/facebook/react/modules/core/ReactChoreographer;Lcom/facebook/react/devsupport/interfaces/DevSupportManager;)V public fun createAndMaybeCallTimer (IIDZ)V public fun createTimer (IJZ)V @@ -3071,27 +3082,18 @@ public final class com/facebook/react/modules/core/ReactChoreographer$CallbackTy public static fun values ()[Lcom/facebook/react/modules/core/ReactChoreographer$CallbackType; } -public final class com/facebook/react/modules/core/TimingModule : com/facebook/fbreact/specs/NativeTimingSpec, com/facebook/react/bridge/LifecycleEventListener, com/facebook/react/jstasks/HeadlessJsTaskEventListener { +public final class com/facebook/react/modules/core/TimingModule : com/facebook/fbreact/specs/NativeTimingSpec, com/facebook/react/modules/core/JavaScriptTimerExecutor { public fun (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/react/devsupport/interfaces/DevSupportManager;)V + public fun callIdleCallbacks (D)V + public fun callTimers (Lcom/facebook/react/bridge/WritableArray;)V public fun createTimer (DDDZ)V public fun deleteTimer (D)V + public fun emitTimeDriftWarning (Ljava/lang/String;)V public fun initialize ()V public fun invalidate ()V - public fun onHeadlessJsTaskFinish (I)V - public fun onHeadlessJsTaskStart (I)V - public fun onHostDestroy ()V - public fun onHostPause ()V - public fun onHostResume ()V public fun setSendIdleEvents (Z)V } -public class com/facebook/react/modules/core/TimingModule$BridgeTimerExecutor : com/facebook/react/modules/core/JavaScriptTimerExecutor { - public fun (Lcom/facebook/react/modules/core/TimingModule;)V - public fun callIdleCallbacks (D)V - public fun callTimers (Lcom/facebook/react/bridge/WritableArray;)V - public fun emitTimeDriftWarning (Ljava/lang/String;)V -} - public class com/facebook/react/modules/debug/DevSettingsModule : com/facebook/fbreact/specs/NativeDevSettingsSpec { public fun (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/react/devsupport/interfaces/DevSupportManager;)V public fun addListener (Ljava/lang/String;)V @@ -3199,7 +3201,7 @@ public class com/facebook/react/modules/dialog/DialogModule : com/facebook/fbrea public fun showAlert (Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Callback;Lcom/facebook/react/bridge/Callback;)V } -public class com/facebook/react/modules/fresco/FrescoModule : com/facebook/react/bridge/ReactContextBaseJavaModule, com/facebook/react/bridge/LifecycleEventListener, com/facebook/react/internal/turbomodule/core/interfaces/TurboModule, com/facebook/react/modules/common/ModuleDataCleaner$Cleanable { +public class com/facebook/react/modules/fresco/FrescoModule : com/facebook/react/bridge/ReactContextBaseJavaModule, com/facebook/react/bridge/LifecycleEventListener, com/facebook/react/modules/common/ModuleDataCleaner$Cleanable, com/facebook/react/turbomodule/core/interfaces/TurboModule { public static final field NAME Ljava/lang/String; public fun (Lcom/facebook/react/bridge/ReactApplicationContext;)V public fun (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/imagepipeline/core/ImagePipeline;Z)V @@ -3440,7 +3442,7 @@ public class com/facebook/react/modules/systeminfo/AndroidInfoHelpers { public static fun getServerHost (Ljava/lang/Integer;)Ljava/lang/String; } -public class com/facebook/react/modules/systeminfo/AndroidInfoModule : com/facebook/fbreact/specs/NativePlatformConstantsAndroidSpec, com/facebook/react/internal/turbomodule/core/interfaces/TurboModule { +public class com/facebook/react/modules/systeminfo/AndroidInfoModule : com/facebook/fbreact/specs/NativePlatformConstantsAndroidSpec, com/facebook/react/turbomodule/core/interfaces/TurboModule { public fun (Lcom/facebook/react/bridge/ReactApplicationContext;)V public fun getAndroidID ()Ljava/lang/String; public fun getTypedExportedConstants ()Ljava/util/Map; @@ -3574,6 +3576,43 @@ public abstract class com/facebook/react/runtime/BindingsInstaller { public fun (Lcom/facebook/jni/HybridData;)V } +public final class com/facebook/react/runtime/BridgelessCatalystInstance : com/facebook/react/bridge/CatalystInstance { + public fun (Lcom/facebook/react/runtime/ReactHostImpl;)V + public fun addBridgeIdleDebugListener (Lcom/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener;)V + public fun addJSIModules (Ljava/util/List;)V + public fun callFunction (Ljava/lang/String;Ljava/lang/String;Lcom/facebook/react/bridge/NativeArray;)V + public fun destroy ()V + public fun extendNativeModules (Lcom/facebook/react/bridge/NativeModuleRegistry;)V + public fun getFabricUIManager ()Lcom/facebook/react/bridge/UIManager; + public fun getJSCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/interfaces/CallInvokerHolder; + public fun getJSIModule (Lcom/facebook/react/bridge/JSIModuleType;)Lcom/facebook/react/bridge/JSIModule; + public fun getJSModule (Ljava/lang/Class;)Lcom/facebook/react/bridge/JavaScriptModule; + public fun getJavaScriptContextHolder ()Lcom/facebook/react/bridge/JavaScriptContextHolder; + public fun getNativeMethodCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/interfaces/NativeMethodCallInvokerHolder; + public fun getNativeModule (Ljava/lang/Class;)Lcom/facebook/react/bridge/NativeModule; + public fun getNativeModule (Ljava/lang/String;)Lcom/facebook/react/bridge/NativeModule; + public fun getNativeModules ()Ljava/util/Collection; + public fun getReactQueueConfiguration ()Lcom/facebook/react/bridge/queue/ReactQueueConfiguration; + public fun getRuntimeExecutor ()Lcom/facebook/react/bridge/RuntimeExecutor; + public fun getRuntimeScheduler ()Lcom/facebook/react/bridge/RuntimeScheduler; + public fun getSourceURL ()Ljava/lang/String; + public fun handleMemoryPressure (I)V + public fun hasNativeModule (Ljava/lang/Class;)Z + public fun hasRunJSBundle ()Z + public fun invokeCallback (ILcom/facebook/react/bridge/NativeArrayInterface;)V + public fun isDestroyed ()Z + public fun loadScriptFromAssets (Landroid/content/res/AssetManager;Ljava/lang/String;Z)V + public fun loadScriptFromFile (Ljava/lang/String;Ljava/lang/String;Z)V + public fun loadSplitBundleFromFile (Ljava/lang/String;Ljava/lang/String;)V + public fun registerSegment (ILjava/lang/String;)V + public fun removeBridgeIdleDebugListener (Lcom/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener;)V + public fun runJSBundle ()V + public fun setFabricUIManager (Lcom/facebook/react/bridge/UIManager;)V + public fun setSourceURLs (Ljava/lang/String;Ljava/lang/String;)V + public fun setTurboModuleManager (Lcom/facebook/react/bridge/JSIModule;)V + public fun setTurboModuleRegistry (Lcom/facebook/react/internal/turbomodule/core/interfaces/TurboModuleRegistry;)V +} + public class com/facebook/react/runtime/CoreReactPackage$$ReactModuleInfoProvider : com/facebook/react/module/model/ReactModuleInfoProvider { public fun ()V public fun getReactModuleInfos ()Ljava/util/Map; @@ -3601,13 +3640,17 @@ public class com/facebook/react/runtime/ReactHostImpl : com/facebook/react/React public fun getLifecycleState ()Lcom/facebook/react/common/LifecycleState; public fun getMemoryPressureRouter ()Lcom/facebook/react/MemoryPressureRouter; public fun getReactQueueConfiguration ()Lcom/facebook/react/bridge/queue/ReactQueueConfiguration; + public fun onActivityResult (Landroid/app/Activity;IILandroid/content/Intent;)V public fun onBackPressed ()Z + public fun onConfigurationChanged (Landroid/content/Context;)V public fun onHostDestroy ()V public fun onHostDestroy (Landroid/app/Activity;)V public fun onHostPause ()V public fun onHostPause (Landroid/app/Activity;)V public fun onHostResume (Landroid/app/Activity;)V public fun onHostResume (Landroid/app/Activity;Lcom/facebook/react/modules/core/DefaultHardwareBackBtnHandler;)V + public fun onNewIntent (Landroid/content/Intent;)V + public fun onWindowFocusChange (Z)V public fun reload (Ljava/lang/String;)Lcom/facebook/react/interfaces/TaskInterface; public fun removeBeforeDestroyListener (Lkotlin/jvm/functions/Function0;)V public fun removeReactInstanceEventListener (Lcom/facebook/react/ReactInstanceEventListener;)V @@ -3683,6 +3726,7 @@ public abstract interface class com/facebook/react/runtime/internal/bolts/Contin public class com/facebook/react/runtime/internal/bolts/Task : com/facebook/react/interfaces/TaskInterface { public static final field BACKGROUND_EXECUTOR Ljava/util/concurrent/ExecutorService; + public static final field UI_THREAD_CONDITIONAL_SYNC_EXECUTOR Ljava/util/concurrent/Executor; public static final field UI_THREAD_EXECUTOR Ljava/util/concurrent/Executor; public static fun call (Ljava/util/concurrent/Callable;)Lcom/facebook/react/runtime/internal/bolts/Task; public static fun call (Ljava/util/concurrent/Callable;Lcom/facebook/react/runtime/internal/bolts/CancellationToken;)Lcom/facebook/react/runtime/internal/bolts/Task; @@ -3806,7 +3850,9 @@ public abstract interface class com/facebook/react/turbomodule/core/interfaces/C public abstract interface class com/facebook/react/turbomodule/core/interfaces/NativeMethodCallInvokerHolder { } -public abstract interface class com/facebook/react/turbomodule/core/interfaces/TurboModule : com/facebook/react/internal/turbomodule/core/interfaces/TurboModule { +public abstract interface class com/facebook/react/turbomodule/core/interfaces/TurboModule { + public abstract fun initialize ()V + public abstract fun invalidate ()V } public abstract class com/facebook/react/uimanager/BaseViewManager : com/facebook/react/uimanager/ViewManager, android/view/View$OnLayoutChangeListener, com/facebook/react/uimanager/BaseViewManagerInterface { @@ -5619,20 +5665,20 @@ public abstract interface class com/facebook/react/util/RCTLog : com/facebook/re public abstract fun logIfNoNativeHook (Ljava/lang/String;Ljava/lang/String;)V } -public class com/facebook/react/util/RNLog { +public final class com/facebook/react/util/RNLog { public static final field ADVICE I public static final field ERROR I + public static final field INSTANCE Lcom/facebook/react/util/RNLog; public static final field LOG I public static final field MINIMUM_LEVEL_FOR_UI I public static final field TRACE I public static final field WARN I - public fun ()V - public static fun a (Ljava/lang/String;)V - public static fun e (Lcom/facebook/react/bridge/ReactContext;Ljava/lang/String;)V - public static fun e (Ljava/lang/String;)V - public static fun l (Ljava/lang/String;)V - public static fun t (Ljava/lang/String;)V - public static fun w (Lcom/facebook/react/bridge/ReactContext;Ljava/lang/String;)V + public static final fun a (Ljava/lang/String;)V + public static final fun e (Lcom/facebook/react/bridge/ReactContext;Ljava/lang/String;)V + public static final fun e (Ljava/lang/String;)V + public static final fun l (Ljava/lang/String;)V + public static final fun t (Ljava/lang/String;)V + public static final fun w (Lcom/facebook/react/bridge/ReactContext;Ljava/lang/String;)V } public class com/facebook/react/viewmanagers/ActivityIndicatorViewManagerDelegate : com/facebook/react/uimanager/BaseViewManagerDelegate { @@ -5673,17 +5719,6 @@ public abstract interface class com/facebook/react/viewmanagers/AndroidHorizonta public abstract fun setRemoveClippedSubviews (Landroid/view/View;Z)V } -public class com/facebook/react/viewmanagers/AndroidPopupMenuManagerDelegate : com/facebook/react/uimanager/BaseViewManagerDelegate { - public fun (Lcom/facebook/react/uimanager/BaseViewManagerInterface;)V - public fun receiveCommand (Landroid/view/View;Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V - public fun setProperty (Landroid/view/View;Ljava/lang/String;Ljava/lang/Object;)V -} - -public abstract interface class com/facebook/react/viewmanagers/AndroidPopupMenuManagerInterface { - public abstract fun setMenuItems (Landroid/view/View;Lcom/facebook/react/bridge/ReadableArray;)V - public abstract fun show (Landroid/view/View;)V -} - public class com/facebook/react/viewmanagers/AndroidProgressBarManagerDelegate : com/facebook/react/uimanager/BaseViewManagerDelegate { public fun (Lcom/facebook/react/uimanager/BaseViewManagerInterface;)V public fun setProperty (Landroid/view/View;Ljava/lang/String;Ljava/lang/Object;)V @@ -6153,47 +6188,6 @@ public abstract interface class com/facebook/react/views/modal/ReactModalHostVie public abstract fun onRequestClose (Landroid/content/DialogInterface;)V } -public final class com/facebook/react/views/popupmenu/PopupMenuSelectionEvent : com/facebook/react/uimanager/events/Event { - public static final field Companion Lcom/facebook/react/views/popupmenu/PopupMenuSelectionEvent$Companion; - public static final field EVENT_NAME Ljava/lang/String; - public fun (III)V - public fun dispatch (Lcom/facebook/react/uimanager/events/RCTEventEmitter;)V - public fun getEventName ()Ljava/lang/String; -} - -public final class com/facebook/react/views/popupmenu/PopupMenuSelectionEvent$Companion { -} - -public final class com/facebook/react/views/popupmenu/ReactPopupMenuContainer : android/widget/FrameLayout { - public fun (Landroid/content/Context;)V - public final fun setMenuItems (Lcom/facebook/react/bridge/ReadableArray;)V - public final fun showPopupMenu ()V -} - -public final class com/facebook/react/views/popupmenu/ReactPopupMenuManager : com/facebook/react/uimanager/ViewGroupManager, com/facebook/react/viewmanagers/AndroidPopupMenuManagerInterface { - public static final field Companion Lcom/facebook/react/views/popupmenu/ReactPopupMenuManager$Companion; - public static final field REACT_CLASS Ljava/lang/String; - public fun ()V - public synthetic fun createViewInstance (Lcom/facebook/react/uimanager/ThemedReactContext;)Landroid/view/View; - public fun getName ()Ljava/lang/String; - public synthetic fun receiveCommand (Landroid/view/View;Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V - public fun receiveCommand (Lcom/facebook/react/views/popupmenu/ReactPopupMenuContainer;Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V - public synthetic fun setMenuItems (Landroid/view/View;Lcom/facebook/react/bridge/ReadableArray;)V - public fun setMenuItems (Lcom/facebook/react/views/popupmenu/ReactPopupMenuContainer;Lcom/facebook/react/bridge/ReadableArray;)V - public synthetic fun show (Landroid/view/View;)V - public fun show (Lcom/facebook/react/views/popupmenu/ReactPopupMenuContainer;)V -} - -public class com/facebook/react/views/popupmenu/ReactPopupMenuManager$$PropsSetter : com/facebook/react/uimanager/ViewManagerPropertyUpdater$ViewManagerSetter { - public fun ()V - public fun getProperties (Ljava/util/Map;)V - public synthetic fun setProperty (Lcom/facebook/react/uimanager/ViewManager;Landroid/view/View;Ljava/lang/String;Ljava/lang/Object;)V - public fun setProperty (Lcom/facebook/react/views/popupmenu/ReactPopupMenuManager;Lcom/facebook/react/views/popupmenu/ReactPopupMenuContainer;Ljava/lang/String;Ljava/lang/Object;)V -} - -public final class com/facebook/react/views/popupmenu/ReactPopupMenuManager$Companion { -} - public class com/facebook/react/views/progressbar/ProgressBarShadowNode : com/facebook/react/uimanager/LayoutShadowNode, com/facebook/yoga/YogaMeasureFunction { public fun ()V public fun getStyle ()Ljava/lang/String; @@ -6288,7 +6282,7 @@ public class com/facebook/react/views/scroll/ReactHorizontalScrollView : android public fun addFocusables (Ljava/util/ArrayList;II)V public fun arrowScroll (I)Z public fun canScrollHorizontally (I)Z - public fun dispatchGenericPointerEvent (Landroid/view/MotionEvent;)Z + public fun dispatchGenericMotionEvent (Landroid/view/MotionEvent;)Z public fun draw (Landroid/graphics/Canvas;)V public fun executeKeyEvent (Landroid/view/KeyEvent;)Z public fun flashScrollIndicators ()V @@ -6325,6 +6319,7 @@ public class com/facebook/react/views/scroll/ReactHorizontalScrollView : android public fun reactSmoothScrollTo (II)V public fun requestChildFocus (Landroid/view/View;Landroid/view/View;)V public fun scrollTo (II)V + public fun scrollToPreservingMomentum (II)V public fun setBackgroundColor (I)V public fun setBorderColor (IFF)V public fun setBorderRadius (F)V @@ -6414,7 +6409,7 @@ public class com/facebook/react/views/scroll/ReactScrollView : android/widget/Sc public fun (Landroid/content/Context;)V public fun (Landroid/content/Context;Lcom/facebook/react/views/scroll/FpsListener;)V public fun abortAnimation ()V - public fun dispatchGenericPointerEvent (Landroid/view/MotionEvent;)Z + public fun dispatchGenericMotionEvent (Landroid/view/MotionEvent;)Z public fun draw (Landroid/graphics/Canvas;)V public fun executeKeyEvent (Landroid/view/KeyEvent;)Z public fun flashScrollIndicators ()V @@ -6449,6 +6444,7 @@ public class com/facebook/react/views/scroll/ReactScrollView : android/widget/Sc public fun reactSmoothScrollTo (II)V public fun requestChildFocus (Landroid/view/View;Landroid/view/View;)V public fun scrollTo (II)V + public fun scrollToPreservingMomentum (II)V public fun setBackgroundColor (I)V public fun setBorderColor (IFF)V public fun setBorderRadius (F)V @@ -6557,6 +6553,7 @@ public abstract interface class com/facebook/react/views/scroll/ReactScrollViewH public abstract interface class com/facebook/react/views/scroll/ReactScrollViewHelper$HasSmoothScroll { public abstract fun reactSmoothScrollTo (II)V + public abstract fun scrollToPreservingMomentum (II)V } public abstract interface class com/facebook/react/views/scroll/ReactScrollViewHelper$HasStateWrapper { @@ -7091,6 +7088,7 @@ public class com/facebook/react/views/text/TextAttributeProps : com/facebook/rea public static final field TA_KEY_TEXT_SHADOW_OFFSET_DY S public static final field TA_KEY_TEXT_SHADOW_RADIUS S public static final field TA_KEY_TEXT_TRANSFORM S + public static final field UNSET I protected field mAccessibilityRole Lcom/facebook/react/uimanager/ReactAccessibilityDelegate$AccessibilityRole; protected field mAllowFontScaling Z protected field mBackgroundColor I @@ -7577,7 +7575,7 @@ public class com/facebook/react/views/view/ReactViewGroup : android/view/ViewGro public fun addView (Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V protected fun addViewInLayout (Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;Z)Z protected fun dispatchDraw (Landroid/graphics/Canvas;)V - public fun dispatchGenericPointerEvent (Landroid/view/MotionEvent;)Z + public fun dispatchGenericMotionEvent (Landroid/view/MotionEvent;)Z public fun dispatchProvideStructure (Landroid/view/ViewStructure;)V protected fun dispatchSetPressed (Z)V protected fun drawChild (Landroid/graphics/Canvas;Landroid/view/View;J)Z diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index 7e0640a0e50a66..0c7d24db69ec6e 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -125,6 +125,16 @@ val preparePrefab by "react/renderer/components/view/"), Pair("../ReactCommon/react/renderer/components/view/platform/android/", ""), )), + PrefabPreprocessingEntry( + "rrc_text", + Pair( + "../ReactCommon/react/renderer/components/text/", + "react/renderer/components/text/")), + PrefabPreprocessingEntry( + "rrc_textinput", + Pair( + "../ReactCommon/react/renderer/components/textinput/", + "react/renderer/components/androidtextinput/")), PrefabPreprocessingEntry( "rrc_legacyviewmanagerinterop", Pair( @@ -138,6 +148,14 @@ val preparePrefab by PrefabPreprocessingEntry( "react_render_mapbuffer", Pair("../ReactCommon/react/renderer/mapbuffer/", "react/renderer/mapbuffer/")), + PrefabPreprocessingEntry( + "react_render_textlayoutmanager", + listOf( + Pair( + "../ReactCommon/react/renderer/textlayoutmanager/", + "react/renderer/textlayoutmanager/"), + Pair("../ReactCommon/react/renderer/textlayoutmanager/platform/android/", ""), + )), PrefabPreprocessingEntry( "yoga", listOf( @@ -159,7 +177,6 @@ val preparePrefab by Pair(File(buildDir, "third-party-ndk/fmt/include/").absolutePath, ""), Pair(File(buildDir, "third-party-ndk/folly/").absolutePath, ""), Pair(File(buildDir, "third-party-ndk/glog/exported/").absolutePath, ""), - Pair("../ReactCommon/butter/", "butter/"), Pair("../ReactCommon/callinvoker/", ""), Pair("../ReactCommon/cxxreact/", "cxxreact/"), Pair("../ReactCommon/react/bridging/", "react/bridging/"), @@ -470,6 +487,8 @@ android { } if (rootProject.hasProperty("ndkVersion") && rootProject.properties["ndkVersion"] != null) { ndkVersion = rootProject.properties["ndkVersion"].toString() + } else { + ndkVersion = libs.versions.ndkVersion.get() } compileOptions { @@ -538,11 +557,14 @@ android { "rrc_image", "rrc_root", "rrc_view", + "rrc_text", + "rrc_textinput", "rrc_legacyviewmanagerinterop", "jsi", "glog", "fabricjni", "react_render_mapbuffer", + "react_render_textlayoutmanager", "yoga", "folly_runtime", "react_nativemodule_core", @@ -662,6 +684,8 @@ android { create("rrc_image") { headers = File(prefabHeadersDir, "rrc_image").absolutePath } create("rrc_root") { headers = File(prefabHeadersDir, "rrc_root").absolutePath } create("rrc_view") { headers = File(prefabHeadersDir, "rrc_view").absolutePath } + create("rrc_text") { headers = File(prefabHeadersDir, "rrc_text").absolutePath } + create("rrc_textinput") { headers = File(prefabHeadersDir, "rrc_textinput").absolutePath } create("rrc_legacyviewmanagerinterop") { headers = File(prefabHeadersDir, "rrc_legacyviewmanagerinterop").absolutePath } @@ -671,6 +695,9 @@ android { create("react_render_mapbuffer") { headers = File(prefabHeadersDir, "react_render_mapbuffer").absolutePath } + create("react_render_textlayoutmanager") { + headers = File(prefabHeadersDir, "react_render_textlayoutmanager").absolutePath + } create("yoga") { headers = File(prefabHeadersDir, "yoga").absolutePath } create("folly_runtime") { headers = File(prefabHeadersDir, "folly_runtime").absolutePath } create("react_nativemodule_core") { diff --git a/packages/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake b/packages/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake index 1ad0af8843dbc1..e2efc266ca0f68 100644 --- a/packages/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake +++ b/packages/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake @@ -74,10 +74,13 @@ add_library(react_cxxreactpackage ALIAS ReactAndroid::react_cxxreactpackage) add_library(react_render_core ALIAS ReactAndroid::react_render_core) add_library(react_render_graphics ALIAS ReactAndroid::react_render_graphics) add_library(rrc_view ALIAS ReactAndroid::rrc_view) +add_library(rrc_text ALIAS ReactAndroid::rrc_text) +add_library(rrc_textinput ALIAS ReactAndroid::rrc_textinput) add_library(jsi ALIAS ReactAndroid::jsi) add_library(glog ALIAS ReactAndroid::glog) add_library(fabricjni ALIAS ReactAndroid::fabricjni) add_library(react_render_mapbuffer ALIAS ReactAndroid::react_render_mapbuffer) +add_library(react_render_textlayoutmanager ALIAS ReactAndroid::react_render_textlayoutmanager) add_library(yoga ALIAS ReactAndroid::yoga) add_library(folly_runtime ALIAS ReactAndroid::folly_runtime) add_library(react_nativemodule_core ALIAS ReactAndroid::react_nativemodule_core) @@ -106,8 +109,11 @@ target_link_libraries(${CMAKE_PROJECT_NAME} react_render_graphics # prefab ready react_render_imagemanager # prefab ready react_render_mapbuffer # prefab ready + react_render_textlayoutmanager # prefab ready rrc_image # prefab ready rrc_view # prefab ready + rrc_text # prefab ready + rrc_textinput # prefab ready rrc_legacyviewmanagerinterop # prefab ready runtimeexecutor # prefab ready turbomodulejsijni # prefab ready diff --git a/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp b/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp index d206b123ad44bb..56a38374370ab6 100644 --- a/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp +++ b/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp @@ -62,8 +62,16 @@ void registerComponents( std::shared_ptr cxxModuleProvider( const std::string& name, const std::shared_ptr& jsInvoker) { - // Not implemented yet: provide pure-C++ NativeModules here. - return nullptr; + // Here you can provide your CXX Turbo Modules coming from + // either your application or from external libraries. The approach to follow + // is similar to the following (for a module called `NativeCxxModuleExample`): + // + // if (name == NativeCxxModuleExample::kModuleName) { + // return std::make_shared(jsInvoker); + // } + + // And we fallback to the CXX module providers autolinked by RN CLI + return rncli_cxxModuleProvider(name, jsInvoker); } std::shared_ptr javaModuleProvider( diff --git a/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts b/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts index 17eb24f355b55b..1e2552ef6a7c58 100644 --- a/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts +++ b/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts @@ -20,22 +20,27 @@ group = "com.facebook.react" version = parent?.properties?.get("publishing_version")?.toString()!! val cmakeVersion = parent?.properties?.get("cmake_version")?.toString()!! - -/** - * We use the bundled version of CMake in the Android SDK if available, to don't force Android users - * to install CMake externally. - */ -fun findCmakePath(cmakeVersion: String): String { - val cmakeRelativePath = "cmake/${cmakeVersion}/bin/cmake" - if (System.getenv("ANDROID_SDK_ROOT") != null && - File("${System.getenv("ANDROID_SDK_ROOT")}/${cmakeRelativePath}").exists()) { - return "${System.getenv("ANDROID_SDK_ROOT")}/${cmakeRelativePath}" +val cmakePath = "${getSDKPath()}/cmake/$cmakeVersion" +val cmakeBinaryPath = "${cmakePath}/bin/cmake" + +fun getSDKPath(): String { + val androidSdkRoot = System.getenv("ANDROID_SDK_ROOT") + val androidHome = System.getenv("ANDROID_HOME") + return when { + !androidSdkRoot.isNullOrBlank() -> androidSdkRoot + !androidHome.isNullOrBlank() -> androidHome + else -> throw IllegalStateException("Neither ANDROID_SDK_ROOT nor ANDROID_HOME is set.") } - if (System.getenv("ANDROID_HOME") != null && - File("${System.getenv("ANDROID_HOME")}/${cmakeRelativePath}").exists()) { - return "${System.getenv("ANDROID_HOME")}/${cmakeRelativePath}" +} + +fun getSDKManagerPath(): String { + val metaSdkManagerPath = File("${getSDKPath()}/cmdline-tools/latest/bin/sdkmanager") + val ossSdkManagerPath = File("${getSDKPath()}/tools/bin/sdkmanager") + return when { + metaSdkManagerPath.exists() -> metaSdkManagerPath.absolutePath + ossSdkManagerPath.exists() -> ossSdkManagerPath.absolutePath + else -> throw GradleException("Could not find sdkmanager executable.") } - return "cmake" } val reactNativeRootDir = project(":packages:react-native:ReactAndroid").projectDir.parent @@ -111,14 +116,28 @@ val unzipHermes by into(hermesDir) } +// NOTE: ideally, we would like CMake to be installed automatically by the `externalNativeBuild` +// below. To do that, we would need the various `ConfigureCMake*` tasks to run *before* +// `configureBuildForHermes` and `buildHermesC` so that CMake is available for their run. But the +// `ConfigureCMake*` tasks depend upon the `ImportHermesc.cmake` file which is actually generated by +// the two tasks mentioned before, so we install CMake manually to break the circular dependency. + +val installCMake by + tasks.registering(Exec::class) { + onlyIf { !File(cmakePath).exists() } + commandLine( + windowsAwareCommandLine(getSDKManagerPath(), "--install", "cmake;${cmakeVersion}")) + } + val configureBuildForHermes by tasks.registering(Exec::class) { + dependsOn(installCMake) workingDir(hermesDir) inputs.dir(hermesDir) outputs.files(hermesBuildOutputFileTree) commandLine( windowsAwareCommandLine( - findCmakePath(cmakeVersion), + cmakeBinaryPath, if (Os.isFamily(Os.FAMILY_WINDOWS)) "-GNMake Makefiles" else "", "-S", ".", @@ -135,7 +154,7 @@ val buildHermesC by outputs.file(hermesCOutputBinary) commandLine( windowsAwareCommandLine( - findCmakePath(cmakeVersion), + cmakeBinaryPath, "--build", hermesBuildDir.toString(), "--target", diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java index 3ffbc8aa28d22d..ae1bb0131fd22e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java @@ -17,7 +17,6 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.devsupport.LogBoxModule; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; @@ -115,7 +114,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { reactModule.canOverrideExistingModule(), reactModule.needsEagerInit(), reactModule.isCxxModule(), - TurboModule.class.isAssignableFrom(moduleClass))); + ReactModuleInfo.classIsTurboModule(moduleClass))); } return () -> reactModuleInfoMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java index 69471937ab8501..2e1d3d976cdf3b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java @@ -12,7 +12,6 @@ import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.devsupport.JSCHeapCapture; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; @@ -74,7 +73,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { reactModule.canOverrideExistingModule(), reactModule.needsEagerInit(), reactModule.isCxxModule(), - TurboModule.class.isAssignableFrom(moduleClass))); + ReactModuleInfo.classIsTurboModule(moduleClass))); } return () -> reactModuleInfoMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java index 75777adb036c36..41dfc24588b6a4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java @@ -11,14 +11,12 @@ import android.content.Context; import android.content.res.Configuration; import com.facebook.react.bridge.MemoryPressureListener; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; -/** Translates and routes memory pressure events to the current catalyst instance. */ +/** Translates and routes memory pressure events. */ public class MemoryPressureRouter implements ComponentCallbacks2 { - private final Set mListeners = - Collections.synchronizedSet(new LinkedHashSet<>()); + private final CopyOnWriteArrayList mListeners = + new CopyOnWriteArrayList(); public MemoryPressureRouter(Context context) { context.getApplicationContext().registerComponentCallbacks(this); @@ -30,7 +28,9 @@ public void destroy(Context context) { /** Add a listener to be notified of memory pressure events. */ public void addMemoryPressureListener(MemoryPressureListener listener) { - mListeners.add(listener); + if (!mListeners.contains(listener)) { + mListeners.add(listener); + } } /** Remove a listener previously added with {@link #addMemoryPressureListener}. */ @@ -50,11 +50,7 @@ public void onConfigurationChanged(Configuration newConfig) {} public void onLowMemory() {} private void dispatchMemoryPressure(int level) { - // copy listeners array to avoid ConcurrentModificationException if any of the listeners remove - // themselves in handleMemoryPressure() - MemoryPressureListener[] listeners = - mListeners.toArray(new MemoryPressureListener[mListeners.size()]); - for (MemoryPressureListener listener : listeners) { + for (MemoryPressureListener listener : mListeners) { listener.handleMemoryPressure(level); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java index 87ffae6ef54d01..54022ed27d5918 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java @@ -31,8 +31,12 @@ public class ReactActivityDelegate { private @Nullable PermissionListener mPermissionListener; private @Nullable Callback mPermissionsCallback; - private ReactDelegate mReactDelegate; + private @Nullable ReactDelegate mReactDelegate; + /** + * Prefer using ReactActivity when possible, as it hooks up all Activity lifecycle methods by + * default. It also implements DefaultHardwareBackBtnHandler, which ReactDelegate requires. + */ @Deprecated public ReactActivityDelegate(@Nullable Activity activity, @Nullable String mainComponentName) { mActivity = activity; @@ -56,21 +60,16 @@ public ReactActivityDelegate( } protected @Nullable Bundle composeLaunchOptions() { - Bundle composedLaunchOptions = getLaunchOptions(); - if (isFabricEnabled()) { - if (composedLaunchOptions == null) { - composedLaunchOptions = new Bundle(); - } - } - return composedLaunchOptions; + return getLaunchOptions(); } + /** + * Override to customize ReactRootView creation. + * + *

Not used on bridgeless + */ protected ReactRootView createRootView() { - return new ReactRootView(getContext()); - } - - protected ReactRootView createRootView(Bundle initialProps) { - return new ReactRootView(getContext()); + return null; } /** @@ -96,7 +95,7 @@ public String getMainComponentName() { return mMainComponentName; } - protected void onCreate(Bundle savedInstanceState) { + public void onCreate(Bundle savedInstanceState) { String mainComponentName = getMainComponentName(); final Bundle launchOptions = composeLaunchOptions(); if (ReactFeatureFlags.enableBridgelessArchitecture) { @@ -108,7 +107,11 @@ protected void onCreate(Bundle savedInstanceState) { getPlainActivity(), getReactNativeHost(), mainComponentName, launchOptions) { @Override protected ReactRootView createRootView() { - return ReactActivityDelegate.this.createRootView(launchOptions); + ReactRootView rootView = ReactActivityDelegate.this.createRootView(); + if (rootView == null) { + rootView = super.createRootView(); + } + return rootView; } }; } @@ -122,11 +125,11 @@ protected void loadApp(String appKey) { getPlainActivity().setContentView(mReactDelegate.getReactRootView()); } - protected void onPause() { + public void onPause() { mReactDelegate.onHostPause(); } - protected void onResume() { + public void onResume() { mReactDelegate.onHostResume(); if (mPermissionsCallback != null) { @@ -135,7 +138,7 @@ protected void onResume() { } } - protected void onDestroy() { + public void onDestroy() { mReactDelegate.onHostDestroy(); } @@ -144,15 +147,7 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { } public boolean onKeyDown(int keyCode, KeyEvent event) { - if (!ReactFeatureFlags.enableBridgelessArchitecture) { - if (getReactNativeHost().hasInstance() - && getReactNativeHost().getUseDeveloperSupport() - && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { - event.startTracking(); - return true; - } - } - return false; + return mReactDelegate.onKeyDown(keyCode, event); } public boolean onKeyUp(int keyCode, KeyEvent event) { @@ -160,15 +155,7 @@ public boolean onKeyUp(int keyCode, KeyEvent event) { } public boolean onKeyLongPress(int keyCode, KeyEvent event) { - if (!ReactFeatureFlags.enableBridgelessArchitecture) { - if (getReactNativeHost().hasInstance() - && getReactNativeHost().getUseDeveloperSupport() - && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { - getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); - return true; - } - } - return false; + return mReactDelegate.onKeyLongPress(keyCode); } public boolean onBackPressed() { @@ -176,29 +163,15 @@ public boolean onBackPressed() { } public boolean onNewIntent(Intent intent) { - if (!ReactFeatureFlags.enableBridgelessArchitecture) { - if (getReactNativeHost().hasInstance()) { - getReactNativeHost().getReactInstanceManager().onNewIntent(intent); - return true; - } - } - return false; + return mReactDelegate.onNewIntent(intent); } public void onWindowFocusChanged(boolean hasFocus) { - if (!ReactFeatureFlags.enableBridgelessArchitecture) { - if (getReactNativeHost().hasInstance()) { - getReactNativeHost().getReactInstanceManager().onWindowFocusChange(hasFocus); - } - } + mReactDelegate.onWindowFocusChanged(hasFocus); } public void onConfigurationChanged(Configuration newConfig) { - if (!ReactFeatureFlags.enableBridgelessArchitecture) { - if (getReactNativeHost().hasInstance()) { - getReactInstanceManager().onConfigurationChanged(getContext(), newConfig); - } - } + mReactDelegate.onConfigurationChanged(newConfig); } public void requestPermissions( @@ -210,14 +183,11 @@ public void requestPermissions( public void onRequestPermissionsResult( final int requestCode, final String[] permissions, final int[] grantResults) { mPermissionsCallback = - new Callback() { - @Override - public void invoke(Object... args) { - if (mPermissionListener != null - && mPermissionListener.onRequestPermissionsResult( - requestCode, permissions, grantResults)) { - mPermissionListener = null; - } + args -> { + if (mPermissionListener != null + && mPermissionListener.onRequestPermissionsResult( + requestCode, permissions, grantResults)) { + mPermissionListener = null; } }; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java index 2140f4a0a1ba53..9650a57c9aeb88 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java @@ -9,13 +9,14 @@ import android.app.Activity; import android.content.Intent; +import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; -import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.facebook.infer.annotation.Assertions; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.devsupport.DoubleTapReloadRecognizer; +import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.interfaces.fabric.ReactSurface; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; @@ -75,26 +76,37 @@ public ReactDelegate( mFabricEnabled = fabricEnabled; mActivity = activity; mMainComponentName = appKey; - mLaunchOptions = composeLaunchOptions(launchOptions); + mLaunchOptions = launchOptions; mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer(); mReactNativeHost = reactNativeHost; } + @Nullable + private DevSupportManager getDevSupportManager() { + if (ReactFeatureFlags.enableBridgelessArchitecture + && mReactHost != null + && mReactHost.getDevSupportManager() != null) { + return mReactHost.getDevSupportManager(); + } else if (getReactNativeHost().hasInstance() + && getReactNativeHost().getUseDeveloperSupport()) { + return getReactNativeHost().getReactInstanceManager().getDevSupportManager(); + } else { + return null; + } + } + public void onHostResume() { + if (!(mActivity instanceof DefaultHardwareBackBtnHandler)) { + throw new ClassCastException( + "Host Activity does not implement DefaultHardwareBackBtnHandler"); + } if (ReactFeatureFlags.enableBridgelessArchitecture) { - if (mActivity instanceof DefaultHardwareBackBtnHandler) { - mReactHost.onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); - } + mReactHost.onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); } else { if (getReactNativeHost().hasInstance()) { - if (mActivity instanceof DefaultHardwareBackBtnHandler) { - getReactNativeHost() - .getReactInstanceManager() - .onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); - } else { - throw new ClassCastException( - "Host Activity does not implement DefaultHardwareBackBtnHandler"); - } + getReactNativeHost() + .getReactInstanceManager() + .onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); } } } @@ -136,11 +148,23 @@ public boolean onBackPressed() { return false; } + public boolean onNewIntent(Intent intent) { + if (ReactFeatureFlags.enableBridgelessArchitecture) { + mReactHost.onNewIntent(intent); + return true; + } else { + if (getReactNativeHost().hasInstance()) { + getReactNativeHost().getReactInstanceManager().onNewIntent(intent); + return true; + } + } + return false; + } + public void onActivityResult( int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) { if (ReactFeatureFlags.enableBridgelessArchitecture) { - // TODO T156475655: Implement onActivityResult for Bridgeless - return; + mReactHost.onActivityResult(mActivity, requestCode, resultCode, data); } else { if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) { getReactNativeHost() @@ -150,6 +174,57 @@ public void onActivityResult( } } + public void onWindowFocusChanged(boolean hasFocus) { + if (ReactFeatureFlags.enableBridgelessArchitecture) { + mReactHost.onWindowFocusChange(hasFocus); + } else { + if (getReactNativeHost().hasInstance()) { + getReactNativeHost().getReactInstanceManager().onWindowFocusChange(hasFocus); + } + } + } + + public void onConfigurationChanged(Configuration newConfig) { + if (ReactFeatureFlags.enableBridgelessArchitecture) { + mReactHost.onConfigurationChanged(Assertions.assertNotNull(mActivity)); + } else { + if (getReactNativeHost().hasInstance()) { + getReactInstanceManager() + .onConfigurationChanged(Assertions.assertNotNull(mActivity), newConfig); + } + } + } + + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD + && ((ReactFeatureFlags.enableBridgelessArchitecture + && mReactHost != null + && mReactHost.getDevSupportManager() != null) + || (getReactNativeHost().hasInstance() + && getReactNativeHost().getUseDeveloperSupport()))) { + event.startTracking(); + return true; + } + return false; + } + + public boolean onKeyLongPress(int keyCode) { + if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { + if (ReactFeatureFlags.enableBridgelessArchitecture + && mReactHost != null + && mReactHost.getDevSupportManager() != null) { + mReactHost.getDevSupportManager().showDevOptionsDialog(); + return true; + } else { + if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) { + getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); + return true; + } + } + } + return false; + } + public void loadApp() { loadApp(mMainComponentName); } @@ -182,6 +257,7 @@ public ReactRootView getReactRootView() { } } + // Not used in bridgeless protected ReactRootView createRootView() { ReactRootView reactRootView = new ReactRootView(mActivity); reactRootView.setIsFabric(isFabricEnabled()); @@ -196,22 +272,21 @@ protected ReactRootView createRootView() { * application. */ public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) { - if (ReactFeatureFlags.enableBridgelessArchitecture) { - // TODO T156475655: Implement shouldShowDevMenuOrReload for Bridgeless + DevSupportManager devSupportManager = getDevSupportManager(); + if (devSupportManager == null) { return false; - } else if (getReactNativeHost().hasInstance() - && getReactNativeHost().getUseDeveloperSupport()) { - if (keyCode == KeyEvent.KEYCODE_MENU) { - getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); - return true; - } - boolean didDoubleTapR = - Assertions.assertNotNull(mDoubleTapReloadRecognizer) - .didDoubleTapR(keyCode, mActivity.getCurrentFocus()); - if (didDoubleTapR) { - getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS(); - return true; - } + } + + if (keyCode == KeyEvent.KEYCODE_MENU) { + devSupportManager.showDevOptionsDialog(); + return true; + } + boolean didDoubleTapR = + Assertions.assertNotNull(mDoubleTapReloadRecognizer) + .didDoubleTapR(keyCode, mActivity.getCurrentFocus()); + if (didDoubleTapR) { + devSupportManager.handleReloadJS(); + return true; } return false; } @@ -234,13 +309,4 @@ public ReactInstanceManager getReactInstanceManager() { protected boolean isFabricEnabled() { return mFabricEnabled; } - - private @NonNull Bundle composeLaunchOptions(Bundle composedLaunchOptions) { - if (isFabricEnabled()) { - if (composedLaunchOptions == null) { - composedLaunchOptions = new Bundle(); - } - } - return composedLaunchOptions; - } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactHost.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactHost.kt index 966bbb54fda32e..5f09366417af32 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactHost.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactHost.kt @@ -9,6 +9,7 @@ package com.facebook.react import android.app.Activity import android.content.Context +import android.content.Intent import android.os.Bundle import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.queue.ReactQueueConfiguration @@ -47,6 +48,9 @@ public interface ReactHost { /** [JSEngineResolutionAlgorithm] used by this host. */ public var jsEngineResolutionAlgorithm: JSEngineResolutionAlgorithm? + /** Routes memory pressure events to interested components */ + public val memoryPressureRouter: MemoryPressureRouter + /** To be called when back button is pressed */ public fun onBackPressed(): Boolean @@ -111,6 +115,22 @@ public interface ReactHost { */ public fun destroy(reason: String, ex: Exception?): TaskInterface + /* To be called when the host activity receives an activity result. */ + public fun onActivityResult( + activity: Activity, + requestCode: Int, + resultCode: Int, + data: Intent?, + ) + + /* To be called when focus has changed for the hosting window. */ + public fun onWindowFocusChange(hasFocus: Boolean) + + /* This method will give JS the opportunity to receive intents via Linking. */ + public fun onNewIntent(intent: Intent) + + public fun onConfigurationChanged(context: Context) + public fun addBeforeDestroyListener(onBeforeDestroy: () -> Unit) public fun removeBeforeDestroyListener(onBeforeDestroy: () -> Unit) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java index a600833e264a4a..7258ab91f4dbc1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java @@ -998,6 +998,11 @@ public Collection getViewManagerNames() { if (names != null) { uniqueNames.addAll(names); } + } else { + FLog.w( + ReactConstants.TAG, + "Package %s is not a ViewManagerOnDemandReactPackage, view managers will not be loaded", + reactPackage.getClass().getSimpleName()); } Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.java index aba8502f55c405..2d674204089752 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.java @@ -8,19 +8,17 @@ package com.facebook.react; import androidx.annotation.Nullable; -import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.jni.HybridData; import com.facebook.react.bridge.CxxModuleWrapper; import com.facebook.react.bridge.ModuleSpec; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.common.ReactConstants; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.internal.turbomodule.core.TurboModuleManagerDelegate; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.model.ReactModuleInfo; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -123,14 +121,14 @@ private void initialize( reactModule.canOverrideExistingModule(), true, reactModule.isCxxModule(), - TurboModule.class.isAssignableFrom(moduleClass)) + ReactModuleInfo.classIsTurboModule(moduleClass)) : new ReactModuleInfo( moduleName, moduleClass.getName(), module.canOverrideExistingModule(), true, CxxModuleWrapper.class.isAssignableFrom(moduleClass), - TurboModule.class.isAssignableFrom(moduleClass)); + ReactModuleInfo.classIsTurboModule(moduleClass)); reactModuleInfoMap.put(moduleName, moduleInfo); moduleMap.put(moduleName, module); @@ -164,25 +162,15 @@ public TurboModule getModule(String moduleName) { NativeModule resolvedModule = null; for (final ModuleProvider moduleProvider : mModuleProviders) { - try { - final ReactModuleInfo moduleInfo = mPackageModuleInfos.get(moduleProvider).get(moduleName); - if (moduleInfo != null - && moduleInfo.isTurboModule() - && (resolvedModule == null || moduleInfo.canOverrideExistingModule())) { - - final NativeModule module = moduleProvider.getModule(moduleName); - if (module != null) { - resolvedModule = module; - } - } + final ReactModuleInfo moduleInfo = mPackageModuleInfos.get(moduleProvider).get(moduleName); + if (moduleInfo != null + && moduleInfo.isTurboModule() + && (resolvedModule == null || moduleInfo.canOverrideExistingModule())) { - } catch (IllegalArgumentException ex) { - // TODO T170570617: remove this catch statement and let exception bubble up - FLog.e( - ReactConstants.TAG, - ex, - "Caught exception while constructing module '%s'. This was previously ignored but will not be caught in the future.", - moduleName); + final NativeModule module = moduleProvider.getModule(moduleName); + if (module != null) { + resolvedModule = module; + } } } @@ -227,24 +215,15 @@ public NativeModule getLegacyModule(String moduleName) { NativeModule resolvedModule = null; for (final ModuleProvider moduleProvider : mModuleProviders) { - try { - final ReactModuleInfo moduleInfo = mPackageModuleInfos.get(moduleProvider).get(moduleName); - if (moduleInfo != null - && !moduleInfo.isTurboModule() - && (resolvedModule == null || moduleInfo.canOverrideExistingModule())) { - - final NativeModule module = moduleProvider.getModule(moduleName); - if (module != null) { - resolvedModule = module; - } + final ReactModuleInfo moduleInfo = mPackageModuleInfos.get(moduleProvider).get(moduleName); + if (moduleInfo != null + && !moduleInfo.isTurboModule() + && (resolvedModule == null || moduleInfo.canOverrideExistingModule())) { + + final NativeModule module = moduleProvider.getModule(moduleName); + if (module != null) { + resolvedModule = module; } - } catch (IllegalArgumentException ex) { - // TODO T170570617: remove this catch statement and let exception bubble up - FLog.e( - ReactConstants.TAG, - ex, - "Caught exception while constructing module '%s'. This was previously ignored but will not be caught in the future.", - moduleName); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java index 766836fd0b16d1..a01f7213e1604a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java @@ -452,7 +452,7 @@ public void startReactApplication(ReactInstanceManager reactInstanceManager, Str /** * Schedule rendering of the react component rendered by the JS application from the given JS * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the JS - * context of that manager. Extra parameter {@param launchOptions} can be used to pass initial + * context of that manager. Extra parameter {@param initialProperties} can be used to pass initial * properties for the react component. */ @ThreadConfined(UI) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java index 0ee0dd6df275ee..b2e2d7cadc1ff1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java @@ -120,7 +120,7 @@ public interface CatalystInstance RuntimeScheduler getRuntimeScheduler(); @Deprecated - void addJSIModules(List jsiModules); + void addJSIModules(List> jsiModules); /** * Returns a hybrid object that contains a pointer to a JS CallInvoker, which is used to schedule diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java index 3658f68cac44f7..f86dffbf341dd2 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java @@ -537,7 +537,8 @@ public JavaScriptContextHolder getJavaScriptContextHolder() { public native RuntimeScheduler getRuntimeScheduler(); @Override - public void addJSIModules(List jsiModules) { + @Deprecated + public void addJSIModules(List> jsiModules) { mJSIModuleRegistry.registerModules(jsiModules); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java index e81b361d16841d..90d5cde4fcbce5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java @@ -26,8 +26,8 @@ public JSIModule getModule(JSIModuleType moduleType) { return Assertions.assertNotNull(jsiModuleHolder.getJSIModule()); } - public void registerModules(List jsiModules) { - for (JSIModuleSpec spec : jsiModules) { + public void registerModules(List> jsiModules) { + for (JSIModuleSpec spec : jsiModules) { mModules.put(spec.getJSIModuleType(), new JSIModuleHolder(spec)); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java index 5e08e165801c6a..44abd25f26a761 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java @@ -15,7 +15,7 @@ import androidx.annotation.Nullable; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.systrace.Systrace; import com.facebook.systrace.SystraceMessage; import java.lang.reflect.Method; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java index f81766a4c0243d..8f63d7a2add58d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java @@ -96,6 +96,11 @@ public int getInt(int index) { return ((Number) mBackingList.get(index)).intValue(); } + @Override + public long getLong(int index) { + return ((Number) mBackingList.get(index)).longValue(); + } + @Override public @Nullable String getString(int index) { return (String) mBackingList.get(index); @@ -129,7 +134,10 @@ public ReadableMap getMap(int index) { return ReadableType.Null; } else if (object instanceof Boolean) { return ReadableType.Boolean; - } else if (object instanceof Double || object instanceof Float || object instanceof Integer) { + } else if (object instanceof Double + || object instanceof Float + || object instanceof Integer + || object instanceof Long) { return ReadableType.Number; } else if (object instanceof String) { return ReadableType.String; @@ -156,6 +164,11 @@ public void pushInt(int value) { mBackingList.add(new Double(value)); } + @Override + public void pushLong(long value) { + mBackingList.add(value); + } + @Override public void pushString(@Nullable String value) { mBackingList.add(value); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java index ccce30a7d60e36..d54cb797fbc943 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java @@ -7,6 +7,8 @@ package com.facebook.react.bridge; +import static androidx.core.util.Preconditions.checkNotNull; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.HashMap; @@ -110,6 +112,11 @@ public int getInt(@NonNull String name) { return ((Number) mBackingMap.get(name)).intValue(); } + @Override + public long getLong(@NonNull String name) { + return ((Number) checkNotNull(mBackingMap.get(name))).longValue(); + } + @Override public String getString(@NonNull String name) { return (String) mBackingMap.get(name); @@ -190,6 +197,11 @@ public void putInt(@NonNull String key, int value) { mBackingMap.put(key, new Double(value)); } + @Override + public void putLong(@NonNull String key, long value) { + mBackingMap.put(key, value); + } + @Override public void putString(@NonNull String key, @Nullable String value) { mBackingMap.put(key, value); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java index 25f170f1134a92..77d011b93cfaa9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java @@ -20,7 +20,6 @@ import com.facebook.infer.annotation.Assertions; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.common.ReactConstants; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.systrace.SystraceMessage; import java.util.concurrent.atomic.AtomicInteger; @@ -73,7 +72,7 @@ public ModuleHolder(NativeModule nativeModule) { nativeModule.canOverrideExistingModule(), true, CxxModuleWrapper.class.isAssignableFrom(nativeModule.getClass()), - TurboModule.class.isAssignableFrom(nativeModule.getClass())); + ReactModuleInfo.classIsTurboModule(nativeModule.getClass())); mModule = nativeModule; PrinterHolder.getPrinter() diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java index a410a3aeb289b3..6791df05e6d510 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java @@ -7,7 +7,7 @@ package com.facebook.react.bridge; -interface NativeArrayInterface { +public interface NativeArrayInterface { @Override String toString(); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java index 26a88911b30cae..9a5e84aaeae848 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java @@ -26,6 +26,8 @@ public interface ReadableArray { int getInt(int index); + long getLong(int index); + @NonNull String getString(int index); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java index a3bae65f7224c4..3dcc141a8cc232 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java @@ -29,6 +29,8 @@ public interface ReadableMap { int getInt(@NonNull String name); + long getLong(@NonNull String name); + @Nullable String getString(@NonNull String name); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java index 1a117a6b46928c..2f74df2334cac6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java @@ -97,6 +97,11 @@ public int getInt(int index) { return ((Double) getLocalArray()[index]).intValue(); } + @Override + public long getLong(int index) { + return ((Long) getLocalArray()[index]).longValue(); + } + @Override public @NonNull String getString(int index) { return (String) getLocalArray()[index]; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java index 0ade85c10090f1..7e796f7cdaf7f5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java @@ -160,6 +160,11 @@ public int getInt(@NonNull String name) { return getValue(name, Double.class).intValue(); } + @Override + public long getLong(@NonNull String name) { + return getValue(name, Long.class).longValue(); + } + @Override public @Nullable String getString(@NonNull String name) { return getNullableValue(name, String.class); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManagerListener.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManagerListener.kt index d2989b677d5415..10cdf1e715a0f9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManagerListener.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManagerListener.kt @@ -7,7 +7,10 @@ package com.facebook.react.bridge +import com.facebook.react.common.annotations.UnstableReactNativeAPI + /** Listener used to hook into the UIManager update process. */ +@UnstableReactNativeAPI public interface UIManagerListener { /** * Called right before view updates are dispatched at the end of a batch. This is useful if a diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java index 8ec699c3970ed9..0b7cb17f69487c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java @@ -20,6 +20,8 @@ public interface WritableArray extends ReadableArray { void pushInt(int value); + void pushLong(long value); + void pushString(@Nullable String value); void pushArray(@Nullable ReadableArray array); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java index 1f6ec6500970f1..a7ef7818f51bb5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java @@ -21,6 +21,8 @@ public interface WritableMap extends ReadableMap { void putInt(@NonNull String key, int value); + void putLong(@NonNull String key, long value); + void putString(@NonNull String key, @Nullable String value); void putArray(@NonNull String key, @Nullable ReadableArray value); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java index 46a2c8d9e67e34..06ad5650e11c45 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java @@ -38,6 +38,9 @@ public WritableNativeArray() { @Override public native void pushInt(int value); + @Override + public native void pushLong(long value); + @Override public native void pushString(@Nullable String value); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java index 809cc9127f555e..228b3065de7a39 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java @@ -32,6 +32,9 @@ public class WritableNativeMap extends ReadableNativeMap implements WritableMap @Override public native void putInt(@NonNull String key, int value); + @Override + public native void putLong(@NonNull String key, long value); + @Override public native void putNull(@NonNull String key); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java index ddac0bfec7360f..010b6871593ea1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java @@ -10,8 +10,6 @@ import android.os.Handler; import android.os.Looper; import android.os.Message; -import com.facebook.common.logging.FLog; -import com.facebook.react.common.ReactConstants; /** Handler that can catch and dispatch Exceptions to an Exception handler. */ public class MessageQueueThreadHandler extends Handler { @@ -28,15 +26,6 @@ public void dispatchMessage(Message msg) { try { super.dispatchMessage(msg); } catch (Exception e) { - if (e instanceof NullPointerException) { - FLog.e( - ReactConstants.TAG, - "Caught NullPointerException when dispatching message in MessageQueueThreadHandler. This is likely caused by runnable" - + "(msg.callback) being nulled in Android Handler after dispatching and before handling (see T170239922 for more details)." - + "Currently we observe that it only happen once which is during initialisation. Due to fixing probably involve Android " - + "System code, we decide to ignore here for now and print an error message for debugging purpose in case this cause more serious issues in future."); - return; - } mExceptionHandler.handleException(e); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/MapBuffer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/MapBuffer.kt index 301837032fbbf0..53bb6b855434f1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/MapBuffer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/MapBuffer.kt @@ -44,7 +44,8 @@ public interface MapBuffer : Iterable { INT, DOUBLE, STRING, - MAP + MAP, + LONG } /** @@ -109,6 +110,16 @@ public interface MapBuffer : Iterable { */ public fun getInt(key: Int): Int + /** + * Provides parsed [Long] value if the entry for given key exists with [DataType.LONG] type + * + * @param key key to lookup [Long] value for + * @return value associated with the requested key + * @throws IllegalArgumentException if the key doesn't exist + * @throws IllegalStateException if the data type doesn't match + */ + public fun getLong(key: Int): Long + /** * Provides parsed [Double] value if the entry for given key exists with [DataType.DOUBLE] type * @@ -175,6 +186,13 @@ public interface MapBuffer : Iterable { */ public val intValue: Int + /** + * Entry value represented as [Long] + * + * @throws IllegalStateException if the data type doesn't match [DataType.LONG] + */ + public val longValue: Long + /** * Entry value represented as [Double] * diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/ReadableMapBuffer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/ReadableMapBuffer.kt index 66add82a7e9e23..80371e93c27131 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/ReadableMapBuffer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/ReadableMapBuffer.kt @@ -115,6 +115,10 @@ public class ReadableMapBuffer : MapBuffer { return buffer.getInt(bufferPosition) } + private fun readLongValue(bufferPosition: Int): Long { + return buffer.getLong(bufferPosition) + } + private fun readBooleanValue(bufferPosition: Int): Boolean { return readIntValue(bufferPosition) == 1 } @@ -180,6 +184,9 @@ public class ReadableMapBuffer : MapBuffer { override fun getInt(key: Int): Int = readIntValue(getTypedValueOffsetForKey(key, MapBuffer.DataType.INT)) + override fun getLong(key: Int): Long = + readLongValue(getTypedValueOffsetForKey(key, MapBuffer.DataType.LONG)) + override fun getDouble(key: Int): Double = readDoubleValue(getTypedValueOffsetForKey(key, MapBuffer.DataType.DOUBLE)) @@ -223,6 +230,7 @@ public class ReadableMapBuffer : MapBuffer { when (entry.type) { MapBuffer.DataType.BOOL -> builder.append(entry.booleanValue) MapBuffer.DataType.INT -> builder.append(entry.intValue) + MapBuffer.DataType.LONG -> builder.append(entry.longValue) MapBuffer.DataType.DOUBLE -> builder.append(entry.doubleValue) MapBuffer.DataType.STRING -> builder.append(entry.stringValue) MapBuffer.DataType.MAP -> builder.append(entry.mapBufferValue.toString()) @@ -280,6 +288,12 @@ public class ReadableMapBuffer : MapBuffer { return readIntValue(bucketOffset + VALUE_OFFSET) } + override val longValue: Long + get() { + assertType(MapBuffer.DataType.LONG) + return readLongValue(bucketOffset + VALUE_OFFSET) + } + override val booleanValue: Boolean get() { assertType(MapBuffer.DataType.BOOL) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/WritableMapBuffer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/WritableMapBuffer.kt index fb145f4dddf697..f79e9122b53b98 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/WritableMapBuffer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/WritableMapBuffer.kt @@ -48,6 +48,15 @@ public class WritableMapBuffer : MapBuffer { */ public fun put(key: Int, value: Int): WritableMapBuffer = putInternal(key, value) + /** + * Adds a long value for given key to the MapBuffer. + * + * @param key entry key + * @param value entry value + * @throws IllegalArgumentException if key is out of [UShort] range + */ + public fun put(key: Int, value: Long): WritableMapBuffer = putInternal(key, value) + /** * Adds a double value for given key to the MapBuffer. * @@ -107,6 +116,8 @@ public class WritableMapBuffer : MapBuffer { override fun getInt(key: Int): Int = verifyValue(key, values.get(key)) + override fun getLong(key: Int): Long = verifyValue(key, values.get(key)) + override fun getDouble(key: Int): Double = verifyValue(key, values.get(key)) override fun getString(key: Int): String = verifyValue(key, values.get(key)) @@ -128,6 +139,7 @@ public class WritableMapBuffer : MapBuffer { return when (val value = this) { is Boolean -> DataType.BOOL is Int -> DataType.INT + is Long -> DataType.LONG is Double -> DataType.DOUBLE is String -> DataType.STRING is MapBuffer -> DataType.MAP @@ -153,6 +165,9 @@ public class WritableMapBuffer : MapBuffer { override val intValue: Int get() = verifyValue(key, values.valueAt(index)) + override val longValue: Long + get() = verifyValue(key, values.valueAt(index)) + override val doubleValue: Double get() = verifyValue(key, values.valueAt(index)) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java index f122d195bbab6b..7809333d8e4256 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java @@ -66,14 +66,6 @@ public class ReactFeatureFlags { */ public static boolean enableBridgelessArchitecture = false; - /** Server-side gating for a hacky fix to an ANR in the bridgeless core, related to Bolts task. */ - public static boolean unstable_bridgelessArchitectureMemoryPressureHackyBoltsFix = false; - - /** - * Does the bridgeless architecture log soft exceptions. Could be useful for tracking down issues. - */ - public static volatile boolean enableBridgelessArchitectureSoftExceptions = false; - /** Does the bridgeless architecture use the new create/reload/destroy routines */ public static volatile boolean enableBridgelessArchitectureNewCreateReloadDestroy = true; @@ -109,9 +101,6 @@ public class ReactFeatureFlags { */ public static boolean enableRemoveDeleteTreeInstruction = false; - /** Report mount operations from the host platform to notify mount hooks. */ - public static boolean enableMountHooks = false; - /** Use native view configs in bridgeless mode. */ public static boolean useNativeViewConfigsInBridgelessMode = false; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultBindingsInstaller.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultBindingsInstaller.kt deleted file mode 100644 index 06a47d80908ebb..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultBindingsInstaller.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -package com.facebook.react.defaults - -import com.facebook.jni.annotations.DoNotStrip -import com.facebook.react.common.annotations.UnstableReactNativeAPI -import com.facebook.react.runtime.BindingsInstaller - -/** - * A utility class that provides users a default [BindingsInstaller] class that's used to initialize - * [ReactHostDelegate] - */ -@DoNotStrip -@UnstableReactNativeAPI -public class DefaultBindingsInstaller : BindingsInstaller(null) {} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt index 59ffe9bccb7875..051effc8525d58 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt @@ -11,6 +11,8 @@ package com.facebook.react.defaults import com.facebook.react.common.annotations.VisibleForTesting import com.facebook.react.config.ReactFeatureFlags +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults /** * A utility class that serves as an entry point for users setup the New Architecture. @@ -45,6 +47,17 @@ public object DefaultNewArchitectureEntryPoint { ReactFeatureFlags.unstable_useTurboModuleInterop = bridgelessEnabled ReactFeatureFlags.enableFabricPendingEventQueue = fabricEnabled + if (bridgelessEnabled) { + ReactNativeFeatureFlags.override( + object : ReactNativeFeatureFlagsDefaults() { + override fun useModernRuntimeScheduler(): Boolean = true + + override fun enableMicrotasks(): Boolean = true + + override fun batchRenderingUpdatesInEventLoop(): Boolean = true + }) + } + privateFabricEnabled = fabricEnabled privateTurboModulesEnabled = turboModulesEnabled privateConcurrentReactEnabled = fabricEnabled diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactActivityDelegate.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactActivityDelegate.kt index 07f7ce270b2da9..4cb4263c41c4d9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactActivityDelegate.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactActivityDelegate.kt @@ -7,10 +7,8 @@ package com.facebook.react.defaults -import android.os.Bundle import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate -import com.facebook.react.ReactRootView /** * A utility class that allows you to simplify the setup of a [ReactActivityDelegate] for new apps @@ -43,10 +41,4 @@ public open class DefaultReactActivityDelegate( ) : this(activity, mainComponentName, fabricEnabled) override fun isFabricEnabled(): Boolean = fabricEnabled - - override fun createRootView(): ReactRootView = - ReactRootView(context).apply { setIsFabric(fabricEnabled) } - - override fun createRootView(bundle: Bundle?): ReactRootView = - ReactRootView(context).apply { setIsFabric(fabricEnabled) } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHostDelegate.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHostDelegate.kt index 5f53398208a74d..3c50cac823e6f7 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHostDelegate.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHostDelegate.kt @@ -43,7 +43,7 @@ public class DefaultReactHostDelegate( override val jsBundleLoader: JSBundleLoader, override val reactPackages: List = emptyList(), override val jsRuntimeFactory: JSRuntimeFactory = HermesInstance(), - override val bindingsInstaller: BindingsInstaller = DefaultBindingsInstaller(), + override val bindingsInstaller: BindingsInstaller? = null, private val reactNativeConfig: ReactNativeConfig = ReactNativeConfig.DEFAULT_CONFIG, private val exceptionHandler: (Exception) -> Unit = {}, override val turboModuleManagerDelegateBuilder: ReactPackageTurboModuleManagerDelegate.Builder diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt index da82f02ea68262..817e953d0de25f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt @@ -49,13 +49,18 @@ protected constructor( DefaultComponentsRegistry.register(componentFactory) val viewManagerRegistry = - ViewManagerRegistry( - object : ViewManagerResolver { - override fun getViewManager(viewManagerName: String) = - reactInstanceManager.createViewManager(viewManagerName) + if (lazyViewManagersEnabled) { + ViewManagerRegistry( + object : ViewManagerResolver { + override fun getViewManager(viewManagerName: String) = + reactInstanceManager.createViewManager(viewManagerName) - override fun getViewManagerNames() = reactInstanceManager.viewManagerNames - }) + override fun getViewManagerNames() = reactInstanceManager.viewManagerNames + }) + } else { + ViewManagerRegistry( + reactInstanceManager.getOrCreateViewManagers(reactApplicationContext)) + } FabricUIManagerProviderImpl( componentFactory, ReactNativeConfig.DEFAULT_CONFIG, viewManagerRegistry) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/.clang-tidy b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index f091faaf87c6fd..476dd2318d3bd0 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -65,6 +65,7 @@ import com.facebook.react.fabric.mounting.mountitems.MountItem; import com.facebook.react.fabric.mounting.mountitems.MountItemFactory; import com.facebook.react.interfaces.fabric.SurfaceHandler; +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags; import com.facebook.react.internal.interop.InteropEventEmitter; import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.modules.i18nmanager.I18nUtil; @@ -91,7 +92,6 @@ import java.util.Map; import java.util.Queue; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; /** * We instruct ProGuard not to strip out any fields or methods, because many of these methods are @@ -173,7 +173,8 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { @NonNull private final CopyOnWriteArrayList mListeners = new CopyOnWriteArrayList<>(); - @NonNull private final AtomicBoolean mMountNotificationScheduled = new AtomicBoolean(false); + private boolean mMountNotificationScheduled = false; + private final List mMountedSurfaceIds = new ArrayList<>(); @ThreadConfined(UI) @NonNull @@ -1203,6 +1204,8 @@ public Map getPerformanceCounters() { } private class MountItemDispatchListener implements MountItemDispatcher.ItemDispatchListener { + @UiThread + @ThreadConfined(UI) @Override public void willMountItems(@Nullable List mountItems) { for (UIManagerListener listener : mListeners) { @@ -1210,18 +1213,28 @@ public void willMountItems(@Nullable List mountItems) { } } + @UiThread + @ThreadConfined(UI) @Override public void didMountItems(@Nullable List mountItems) { for (UIManagerListener listener : mListeners) { listener.didMountItems(FabricUIManager.this); } - if (!ReactFeatureFlags.enableMountHooks) { + if (!ReactNativeFeatureFlags.enableMountHooksAndroid() + || mountItems == null + || mountItems.isEmpty()) { return; } - boolean mountNotificationScheduled = mMountNotificationScheduled.getAndSet(true); - if (!mountNotificationScheduled) { + // Collect surface IDs for all the mount items + for (MountItem mountItem : mountItems) { + if (mountItem != null && !mMountedSurfaceIds.contains(mountItem.getSurfaceId())) { + mMountedSurfaceIds.add(mountItem.getSurfaceId()); + } + } + + if (!mMountNotificationScheduled && !mMountedSurfaceIds.isEmpty()) { // Notify mount when the effects are visible and prevent mount hooks to // delay paint. UiThreadUtil.getUiThreadHandler() @@ -1229,24 +1242,19 @@ public void didMountItems(@Nullable List mountItems) { new Runnable() { @Override public void run() { - mMountNotificationScheduled.set(false); + mMountNotificationScheduled = false; final @Nullable Binding binding = mBinding; - if (mountItems == null || binding == null) { + if (binding == null || mDestroyed) { + mMountedSurfaceIds.clear(); return; } - // Collect surface IDs for all the mount items - List surfaceIds = new ArrayList<>(); - for (MountItem mountItem : mountItems) { - if (mountItem != null && !surfaceIds.contains(mountItem.getSurfaceId())) { - surfaceIds.add(mountItem.getSurfaceId()); - } - } - - for (int surfaceId : surfaceIds) { + for (int surfaceId : mMountedSurfaceIds) { binding.reportMount(surfaceId); } + + mMountedSurfaceIds.clear(); } }); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListener.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListener.kt index 1db876d5aa1b47..a3acebecac68a4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListener.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListener.kt @@ -11,6 +11,7 @@ package com.facebook.react.fabric.internal.interop import com.facebook.react.bridge.UIManager import com.facebook.react.bridge.UIManagerListener +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.fabric.interop.UIBlock import com.facebook.react.fabric.interop.UIBlockViewResolver @@ -21,6 +22,7 @@ import com.facebook.react.fabric.interop.UIBlockViewResolver * class effectively re-implements this logic by using a [UIManagerListener] and exposing the two * methods that the user intend to call. */ +@OptIn(UnstableReactNativeAPI::class) internal class InteropUIBlockListener : UIManagerListener { internal val beforeUIBlocks: MutableList = mutableListOf() diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlock.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlock.kt index 702d096ea664fa..020ce08340aac1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlock.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlock.kt @@ -9,6 +9,8 @@ package com.facebook.react.fabric.interop +import com.facebook.react.common.annotations.UnstableReactNativeAPI + /** * Interop Interface added to support `addUiBlock` and `prependUIBlock` methods in Fabric. * Historically those methods were only available in `UIManagerModule` (Paper, the old renderer). @@ -17,6 +19,7 @@ package com.facebook.react.fabric.interop * @deprecated When developing new libraries for Fabric you should instead use [UIManagerListener] * or View Commands to achieve a same results. */ +@UnstableReactNativeAPI @Deprecated("Use UIManagerListener or View Commands instead of addUIBlock and prependUIBlock.") public fun interface UIBlock { /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlockViewResolver.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlockViewResolver.kt index 7fd8389b858b42..5cbcd2f2f8f5b8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlockViewResolver.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/interop/UIBlockViewResolver.kt @@ -8,6 +8,7 @@ package com.facebook.react.fabric.interop import android.view.View +import com.facebook.react.common.annotations.UnstableReactNativeAPI /** * This interface is used as receiver parameter for [UIBlock]. @@ -17,6 +18,7 @@ import android.view.View * @deprecated When developing new libraries for Fabric you should instead use [UIManagerListener] * or View Commands to achieve a same results. */ +@UnstableReactNativeAPI @Deprecated("Use UIManagerListener or View Commands instead of addUIBlock and prependUIBlock.") public interface UIBlockViewResolver { /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt index 487f43d409c9a4..a14811239d8f64 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> */ /** @@ -35,46 +35,46 @@ public object ReactNativeFeatureFlags { public fun commonTestFlag(): Boolean = accessor.commonTestFlag() /** - * Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used). + * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. */ @JvmStatic - public fun enableBackgroundExecutor(): Boolean = accessor.enableBackgroundExecutor() + public fun batchRenderingUpdatesInEventLoop(): Boolean = accessor.batchRenderingUpdatesInEventLoop() /** - * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + * Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used). */ @JvmStatic - public fun useModernRuntimeScheduler(): Boolean = accessor.useModernRuntimeScheduler() + public fun enableBackgroundExecutor(): Boolean = accessor.enableBackgroundExecutor() /** - * Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution). + * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). */ @JvmStatic - public fun enableMicrotasks(): Boolean = accessor.enableMicrotasks() + public fun enableCustomDrawOrderFabric(): Boolean = accessor.enableCustomDrawOrderFabric() /** - * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. + * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix */ @JvmStatic - public fun batchRenderingUpdatesInEventLoop(): Boolean = accessor.batchRenderingUpdatesInEventLoop() + public fun enableFixForClippedSubviewsCrash(): Boolean = accessor.enableFixForClippedSubviewsCrash() /** - * Uses new, deduplicated logic for constructing Android Spannables from text fragments + * Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution). */ @JvmStatic - public fun enableSpannableBuildingUnification(): Boolean = accessor.enableSpannableBuildingUnification() + public fun enableMicrotasks(): Boolean = accessor.enableMicrotasks() /** - * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). + * Enables the notification of mount operations to mount hooks on Android. */ @JvmStatic - public fun enableCustomDrawOrderFabric(): Boolean = accessor.enableCustomDrawOrderFabric() + public fun enableMountHooksAndroid(): Boolean = accessor.enableMountHooksAndroid() /** - * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix + * Uses new, deduplicated logic for constructing Android Spannables from text fragments */ @JvmStatic - public fun enableFixForClippedSubviewsCrash(): Boolean = accessor.enableFixForClippedSubviewsCrash() + public fun enableSpannableBuildingUnification(): Boolean = accessor.enableSpannableBuildingUnification() /** * Flag determining if the C++ implementation of InspectorPackagerConnection should be used instead of the per-platform one. This flag is global and should not be changed across React Host lifetimes. @@ -88,6 +88,12 @@ public object ReactNativeFeatureFlags { @JvmStatic public fun inspectorEnableModernCDPRegistry(): Boolean = accessor.inspectorEnableModernCDPRegistry() + /** + * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + */ + @JvmStatic + public fun useModernRuntimeScheduler(): Boolean = accessor.useModernRuntimeScheduler() + /** * Overrides the feature flags with the ones provided by the given provider * (generally one that extends `ReactNativeFeatureFlagsDefaults`). diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt index 3e38e9f251cbd8..e65fa7974529d4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<11824621ee7ca5dbdf2f09bdf1a1f983>> + * @generated SignedSource<<7ae379135157666d9646f1d8eeec9989>> */ /** @@ -21,15 +21,16 @@ package com.facebook.react.internal.featureflags public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccessor { private var commonTestFlagCache: Boolean? = null - private var enableBackgroundExecutorCache: Boolean? = null - private var useModernRuntimeSchedulerCache: Boolean? = null - private var enableMicrotasksCache: Boolean? = null private var batchRenderingUpdatesInEventLoopCache: Boolean? = null - private var enableSpannableBuildingUnificationCache: Boolean? = null + private var enableBackgroundExecutorCache: Boolean? = null private var enableCustomDrawOrderFabricCache: Boolean? = null private var enableFixForClippedSubviewsCrashCache: Boolean? = null + private var enableMicrotasksCache: Boolean? = null + private var enableMountHooksAndroidCache: Boolean? = null + private var enableSpannableBuildingUnificationCache: Boolean? = null private var inspectorEnableCxxInspectorPackagerConnectionCache: Boolean? = null private var inspectorEnableModernCDPRegistryCache: Boolean? = null + private var useModernRuntimeSchedulerCache: Boolean? = null override fun commonTestFlag(): Boolean { var cached = commonTestFlagCache @@ -40,6 +41,15 @@ public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccesso return cached } + override fun batchRenderingUpdatesInEventLoop(): Boolean { + var cached = batchRenderingUpdatesInEventLoopCache + if (cached == null) { + cached = ReactNativeFeatureFlagsCxxInterop.batchRenderingUpdatesInEventLoop() + batchRenderingUpdatesInEventLoopCache = cached + } + return cached + } + override fun enableBackgroundExecutor(): Boolean { var cached = enableBackgroundExecutorCache if (cached == null) { @@ -49,11 +59,20 @@ public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccesso return cached } - override fun useModernRuntimeScheduler(): Boolean { - var cached = useModernRuntimeSchedulerCache + override fun enableCustomDrawOrderFabric(): Boolean { + var cached = enableCustomDrawOrderFabricCache if (cached == null) { - cached = ReactNativeFeatureFlagsCxxInterop.useModernRuntimeScheduler() - useModernRuntimeSchedulerCache = cached + cached = ReactNativeFeatureFlagsCxxInterop.enableCustomDrawOrderFabric() + enableCustomDrawOrderFabricCache = cached + } + return cached + } + + override fun enableFixForClippedSubviewsCrash(): Boolean { + var cached = enableFixForClippedSubviewsCrashCache + if (cached == null) { + cached = ReactNativeFeatureFlagsCxxInterop.enableFixForClippedSubviewsCrash() + enableFixForClippedSubviewsCrashCache = cached } return cached } @@ -67,11 +86,11 @@ public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccesso return cached } - override fun batchRenderingUpdatesInEventLoop(): Boolean { - var cached = batchRenderingUpdatesInEventLoopCache + override fun enableMountHooksAndroid(): Boolean { + var cached = enableMountHooksAndroidCache if (cached == null) { - cached = ReactNativeFeatureFlagsCxxInterop.batchRenderingUpdatesInEventLoop() - batchRenderingUpdatesInEventLoopCache = cached + cached = ReactNativeFeatureFlagsCxxInterop.enableMountHooksAndroid() + enableMountHooksAndroidCache = cached } return cached } @@ -85,24 +104,6 @@ public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccesso return cached } - override fun enableCustomDrawOrderFabric(): Boolean { - var cached = enableCustomDrawOrderFabricCache - if (cached == null) { - cached = ReactNativeFeatureFlagsCxxInterop.enableCustomDrawOrderFabric() - enableCustomDrawOrderFabricCache = cached - } - return cached - } - - override fun enableFixForClippedSubviewsCrash(): Boolean { - var cached = enableFixForClippedSubviewsCrashCache - if (cached == null) { - cached = ReactNativeFeatureFlagsCxxInterop.enableFixForClippedSubviewsCrash() - enableFixForClippedSubviewsCrashCache = cached - } - return cached - } - override fun inspectorEnableCxxInspectorPackagerConnection(): Boolean { var cached = inspectorEnableCxxInspectorPackagerConnectionCache if (cached == null) { @@ -121,6 +122,15 @@ public class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAccesso return cached } + override fun useModernRuntimeScheduler(): Boolean { + var cached = useModernRuntimeSchedulerCache + if (cached == null) { + cached = ReactNativeFeatureFlagsCxxInterop.useModernRuntimeScheduler() + useModernRuntimeSchedulerCache = cached + } + return cached + } + override fun override(provider: ReactNativeFeatureFlagsProvider): Unit = ReactNativeFeatureFlagsCxxInterop.override(provider as Any) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt index d3518e6cba082d..d6093108c73d9b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<<244a0656beee8e018585bdd4bb4e5cd1>> */ /** @@ -30,24 +30,26 @@ public object ReactNativeFeatureFlagsCxxInterop { @DoNotStrip @JvmStatic public external fun commonTestFlag(): Boolean + @DoNotStrip @JvmStatic public external fun batchRenderingUpdatesInEventLoop(): Boolean + @DoNotStrip @JvmStatic public external fun enableBackgroundExecutor(): Boolean - @DoNotStrip @JvmStatic public external fun useModernRuntimeScheduler(): Boolean + @DoNotStrip @JvmStatic public external fun enableCustomDrawOrderFabric(): Boolean + + @DoNotStrip @JvmStatic public external fun enableFixForClippedSubviewsCrash(): Boolean @DoNotStrip @JvmStatic public external fun enableMicrotasks(): Boolean - @DoNotStrip @JvmStatic public external fun batchRenderingUpdatesInEventLoop(): Boolean + @DoNotStrip @JvmStatic public external fun enableMountHooksAndroid(): Boolean @DoNotStrip @JvmStatic public external fun enableSpannableBuildingUnification(): Boolean - @DoNotStrip @JvmStatic public external fun enableCustomDrawOrderFabric(): Boolean - - @DoNotStrip @JvmStatic public external fun enableFixForClippedSubviewsCrash(): Boolean - @DoNotStrip @JvmStatic public external fun inspectorEnableCxxInspectorPackagerConnection(): Boolean @DoNotStrip @JvmStatic public external fun inspectorEnableModernCDPRegistry(): Boolean + @DoNotStrip @JvmStatic public external fun useModernRuntimeScheduler(): Boolean + @DoNotStrip @JvmStatic public external fun override(provider: Any) @DoNotStrip @JvmStatic public external fun dangerouslyReset() diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt index e75ba65f44d08b..7a2ac9d1601672 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> */ /** @@ -25,21 +25,23 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi override fun commonTestFlag(): Boolean = false + override fun batchRenderingUpdatesInEventLoop(): Boolean = false + override fun enableBackgroundExecutor(): Boolean = false - override fun useModernRuntimeScheduler(): Boolean = false + override fun enableCustomDrawOrderFabric(): Boolean = false + + override fun enableFixForClippedSubviewsCrash(): Boolean = false override fun enableMicrotasks(): Boolean = false - override fun batchRenderingUpdatesInEventLoop(): Boolean = false + override fun enableMountHooksAndroid(): Boolean = false override fun enableSpannableBuildingUnification(): Boolean = false - override fun enableCustomDrawOrderFabric(): Boolean = false - - override fun enableFixForClippedSubviewsCrash(): Boolean = false - override fun inspectorEnableCxxInspectorPackagerConnection(): Boolean = false override fun inspectorEnableModernCDPRegistry(): Boolean = false + + override fun useModernRuntimeScheduler(): Boolean = false } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt index 2fcc689a55e16c..cae01383bef9fd 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<63356ad414e641eae11ca07b1a876fd3>> + * @generated SignedSource<<919eb0f27540e5dd7a1e028663c23264>> */ /** @@ -25,15 +25,16 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces private val accessedFeatureFlags = mutableSetOf() private var commonTestFlagCache: Boolean? = null - private var enableBackgroundExecutorCache: Boolean? = null - private var useModernRuntimeSchedulerCache: Boolean? = null - private var enableMicrotasksCache: Boolean? = null private var batchRenderingUpdatesInEventLoopCache: Boolean? = null - private var enableSpannableBuildingUnificationCache: Boolean? = null + private var enableBackgroundExecutorCache: Boolean? = null private var enableCustomDrawOrderFabricCache: Boolean? = null private var enableFixForClippedSubviewsCrashCache: Boolean? = null + private var enableMicrotasksCache: Boolean? = null + private var enableMountHooksAndroidCache: Boolean? = null + private var enableSpannableBuildingUnificationCache: Boolean? = null private var inspectorEnableCxxInspectorPackagerConnectionCache: Boolean? = null private var inspectorEnableModernCDPRegistryCache: Boolean? = null + private var useModernRuntimeSchedulerCache: Boolean? = null override fun commonTestFlag(): Boolean { var cached = commonTestFlagCache @@ -45,6 +46,16 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces return cached } + override fun batchRenderingUpdatesInEventLoop(): Boolean { + var cached = batchRenderingUpdatesInEventLoopCache + if (cached == null) { + cached = currentProvider.batchRenderingUpdatesInEventLoop() + accessedFeatureFlags.add("batchRenderingUpdatesInEventLoop") + batchRenderingUpdatesInEventLoopCache = cached + } + return cached + } + override fun enableBackgroundExecutor(): Boolean { var cached = enableBackgroundExecutorCache if (cached == null) { @@ -55,12 +66,22 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces return cached } - override fun useModernRuntimeScheduler(): Boolean { - var cached = useModernRuntimeSchedulerCache + override fun enableCustomDrawOrderFabric(): Boolean { + var cached = enableCustomDrawOrderFabricCache if (cached == null) { - cached = currentProvider.useModernRuntimeScheduler() - accessedFeatureFlags.add("useModernRuntimeScheduler") - useModernRuntimeSchedulerCache = cached + cached = currentProvider.enableCustomDrawOrderFabric() + accessedFeatureFlags.add("enableCustomDrawOrderFabric") + enableCustomDrawOrderFabricCache = cached + } + return cached + } + + override fun enableFixForClippedSubviewsCrash(): Boolean { + var cached = enableFixForClippedSubviewsCrashCache + if (cached == null) { + cached = currentProvider.enableFixForClippedSubviewsCrash() + accessedFeatureFlags.add("enableFixForClippedSubviewsCrash") + enableFixForClippedSubviewsCrashCache = cached } return cached } @@ -75,12 +96,12 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces return cached } - override fun batchRenderingUpdatesInEventLoop(): Boolean { - var cached = batchRenderingUpdatesInEventLoopCache + override fun enableMountHooksAndroid(): Boolean { + var cached = enableMountHooksAndroidCache if (cached == null) { - cached = currentProvider.batchRenderingUpdatesInEventLoop() - accessedFeatureFlags.add("batchRenderingUpdatesInEventLoop") - batchRenderingUpdatesInEventLoopCache = cached + cached = currentProvider.enableMountHooksAndroid() + accessedFeatureFlags.add("enableMountHooksAndroid") + enableMountHooksAndroidCache = cached } return cached } @@ -95,26 +116,6 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces return cached } - override fun enableCustomDrawOrderFabric(): Boolean { - var cached = enableCustomDrawOrderFabricCache - if (cached == null) { - cached = currentProvider.enableCustomDrawOrderFabric() - accessedFeatureFlags.add("enableCustomDrawOrderFabric") - enableCustomDrawOrderFabricCache = cached - } - return cached - } - - override fun enableFixForClippedSubviewsCrash(): Boolean { - var cached = enableFixForClippedSubviewsCrashCache - if (cached == null) { - cached = currentProvider.enableFixForClippedSubviewsCrash() - accessedFeatureFlags.add("enableFixForClippedSubviewsCrash") - enableFixForClippedSubviewsCrashCache = cached - } - return cached - } - override fun inspectorEnableCxxInspectorPackagerConnection(): Boolean { var cached = inspectorEnableCxxInspectorPackagerConnectionCache if (cached == null) { @@ -135,6 +136,16 @@ public class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcces return cached } + override fun useModernRuntimeScheduler(): Boolean { + var cached = useModernRuntimeSchedulerCache + if (cached == null) { + cached = currentProvider.useModernRuntimeScheduler() + accessedFeatureFlags.add("useModernRuntimeScheduler") + useModernRuntimeSchedulerCache = cached + } + return cached + } + override fun override(provider: ReactNativeFeatureFlagsProvider) { if (accessedFeatureFlags.isNotEmpty()) { val accessedFeatureFlagsStr = accessedFeatureFlags.joinToString(separator = ", ") { it } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt index 2d4561cc3e6420..451f64be6d98bc 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> */ /** @@ -25,21 +25,23 @@ import com.facebook.proguard.annotations.DoNotStrip public interface ReactNativeFeatureFlagsProvider { @DoNotStrip public fun commonTestFlag(): Boolean + @DoNotStrip public fun batchRenderingUpdatesInEventLoop(): Boolean + @DoNotStrip public fun enableBackgroundExecutor(): Boolean - @DoNotStrip public fun useModernRuntimeScheduler(): Boolean + @DoNotStrip public fun enableCustomDrawOrderFabric(): Boolean + + @DoNotStrip public fun enableFixForClippedSubviewsCrash(): Boolean @DoNotStrip public fun enableMicrotasks(): Boolean - @DoNotStrip public fun batchRenderingUpdatesInEventLoop(): Boolean + @DoNotStrip public fun enableMountHooksAndroid(): Boolean @DoNotStrip public fun enableSpannableBuildingUnification(): Boolean - @DoNotStrip public fun enableCustomDrawOrderFabric(): Boolean - - @DoNotStrip public fun enableFixForClippedSubviewsCrash(): Boolean - @DoNotStrip public fun inspectorEnableCxxInspectorPackagerConnection(): Boolean @DoNotStrip public fun inspectorEnableModernCDPRegistry(): Boolean + + @DoNotStrip public fun useModernRuntimeScheduler(): Boolean } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/.clang-tidy b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleInteropUtils.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleInteropUtils.java index 50ce80eb46af0b..496cf39a313ba9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleInteropUtils.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleInteropUtils.java @@ -18,7 +18,7 @@ import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManager.java index e66dbc3492830b..d627f82b7fd3f8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManager.java @@ -19,12 +19,12 @@ import com.facebook.react.bridge.ReactNoCrashSoftException; import com.facebook.react.bridge.ReactSoftExceptionLogger; import com.facebook.react.bridge.RuntimeExecutor; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.internal.turbomodule.core.interfaces.TurboModuleRegistry; import com.facebook.react.turbomodule.core.CallInvokerHolderImpl; import com.facebook.react.turbomodule.core.NativeMethodCallInvokerHolderImpl; import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder; import com.facebook.react.turbomodule.core.interfaces.NativeMethodCallInvokerHolder; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate.java index 9fe0fdb630d308..39539cdd6f34d5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate.java @@ -12,7 +12,7 @@ import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.NativeModule; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.ArrayList; import java.util.List; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/interfaces/TurboModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/interfaces/TurboModule.kt deleted file mode 100644 index 0e546d282864a3..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/turbomodule/core/interfaces/TurboModule.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -package com.facebook.react.internal.turbomodule.core.interfaces -/** All turbo modules should inherit from this interface */ -public interface TurboModule { - /** Initialize the TurboModule. */ - public fun initialize() - - /** - * Called during the turn down process of ReactHost. This method is called before React Native is - * stopped. Override this method to clean up resources used by the TurboModule. - */ - public fun invalidate() -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java index ae4a56bbc3a969..8be508edf80479 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java @@ -7,6 +7,8 @@ package com.facebook.react.module.model; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; + /** * Data holder class holding native module specifications. {@link ReactModuleSpecProcessor} creates * these so Java modules don't have to be instantiated at React Native start up. @@ -80,4 +82,12 @@ public boolean isCxxModule() { public boolean isTurboModule() { return mIsTurboModule; } + + /** + * Checks if the passed class is a TurboModule. Useful to populate the parameter [isTurboModule] + * in the constructor of ReactModuleInfo. + */ + public static boolean classIsTurboModule(Class clazz) { + return TurboModule.class.isAssignableFrom(clazz); + } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java index 969ea6ddb09939..4f85ff932503b6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java @@ -161,13 +161,13 @@ private CodeBlock getCodeBlockForReactModuleInfos(List nativeModules) builder.addStatement("$T map = new $T()", MAP_TYPE, INSTANTIATED_MAP_TYPE); String turboModuleInterfaceCanonicalName = - "com.facebook.react.internal.turbomodule.core.interfaces.TurboModule"; + "com.facebook.react.turbomodule.core.interfaces.TurboModule"; TypeMirror turboModuleInterface = mElements.getTypeElement(turboModuleInterfaceCanonicalName).asType(); if (turboModuleInterface == null) { throw new RuntimeException( - "com.facebook.react.internal.turbomodule.core.interfaces.TurboModule interface not found."); + "com.facebook.react.turbomodule.core.interfaces.TurboModule interface not found."); } for (String nativeModule : nativeModules) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/.clang-tidy b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java index 5f5e1abb8f64d3..95a74b35bfb318 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java @@ -12,12 +12,14 @@ import androidx.annotation.Nullable; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableArray; import com.facebook.react.common.SystemClock; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.jstasks.HeadlessJsTaskContext; +import com.facebook.react.jstasks.HeadlessJsTaskEventListener; import java.util.Comparator; import java.util.PriorityQueue; import java.util.concurrent.atomic.AtomicBoolean; @@ -28,7 +30,7 @@ * *

This is used by the NativeModule {@link TimingModule}. */ -public class JavaTimerManager { +public class JavaTimerManager implements LifecycleEventListener, HeadlessJsTaskEventListener { // These timing constants should be kept in sync with the ones in `JSTimers.js`. // The minimum time in milliseconds left in the frame to call idle callbacks. @@ -196,19 +198,24 @@ public int compare(Timer lhs, Timer rhs) { } }); mTimerIdsToTimers = new SparseArray<>(); + + mReactApplicationContext.addLifecycleEventListener(this); } + @Override public void onHostPause() { isPaused.set(true); clearFrameCallback(); maybeIdleCallback(); } + @Override public void onHostDestroy() { clearFrameCallback(); maybeIdleCallback(); } + @Override public void onHostResume() { isPaused.set(false); // TODO(5195192) Investigate possible problems related to restarting all tasks at the same @@ -217,6 +224,7 @@ public void onHostResume() { maybeSetChoreographerIdleCallback(); } + @Override public void onHeadlessJsTaskStart(int taskId) { if (!isRunningTasks.getAndSet(true)) { setChoreographerCallback(); @@ -224,6 +232,7 @@ public void onHeadlessJsTaskStart(int taskId) { } } + @Override public void onHeadlessJsTaskFinish(int taskId) { HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(mReactApplicationContext); @@ -235,6 +244,8 @@ public void onHeadlessJsTaskFinish(int taskId) { } public void onInstanceDestroy() { + mReactApplicationContext.removeLifecycleEventListener(this); + clearFrameCallback(); clearChoreographerIdleCallback(); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java index 73149ef7374250..af70e66e3ebe2b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java @@ -8,49 +8,16 @@ package com.facebook.react.modules.core; import com.facebook.fbreact.specs.NativeTimingSpec; -import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.WritableArray; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.jstasks.HeadlessJsTaskContext; -import com.facebook.react.jstasks.HeadlessJsTaskEventListener; import com.facebook.react.module.annotations.ReactModule; /** Native module for JS timer execution. Timers fire on frame boundaries. */ @ReactModule(name = NativeTimingSpec.NAME) -public final class TimingModule extends NativeTimingSpec - implements LifecycleEventListener, HeadlessJsTaskEventListener { - - public class BridgeTimerExecutor implements JavaScriptTimerExecutor { - @Override - public void callTimers(WritableArray timerIDs) { - ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); - - if (reactApplicationContext != null) { - reactApplicationContext.getJSModule(JSTimers.class).callTimers(timerIDs); - } - } - - @Override - public void callIdleCallbacks(double frameTime) { - ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); - - if (reactApplicationContext != null) { - reactApplicationContext.getJSModule(JSTimers.class).callIdleCallbacks(frameTime); - } - } - - @Override - public void emitTimeDriftWarning(String warningMessage) { - ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); - - if (reactApplicationContext != null) { - reactApplicationContext.getJSModule(JSTimers.class).emitTimeDriftWarning(warningMessage); - } - } - } - +public final class TimingModule extends NativeTimingSpec implements JavaScriptTimerExecutor { private final JavaTimerManager mJavaTimerManager; public TimingModule(ReactApplicationContext reactContext, DevSupportManager devSupportManager) { @@ -58,18 +25,14 @@ public TimingModule(ReactApplicationContext reactContext, DevSupportManager devS mJavaTimerManager = new JavaTimerManager( - reactContext, - new BridgeTimerExecutor(), - ReactChoreographer.getInstance(), - devSupportManager); + reactContext, this, ReactChoreographer.getInstance(), devSupportManager); } @Override public void initialize() { - getReactApplicationContext().addLifecycleEventListener(this); HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(getReactApplicationContext()); - headlessJsTaskContext.addTaskEventListener(this); + headlessJsTaskContext.addTaskEventListener(mJavaTimerManager); } @Override @@ -97,28 +60,30 @@ public void setSendIdleEvents(final boolean sendIdleEvents) { } @Override - public void onHostResume() { - mJavaTimerManager.onHostResume(); - } + public void callTimers(WritableArray timerIDs) { + ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); - @Override - public void onHostPause() { - mJavaTimerManager.onHostPause(); + if (reactApplicationContext != null) { + reactApplicationContext.getJSModule(JSTimers.class).callTimers(timerIDs); + } } @Override - public void onHostDestroy() { - mJavaTimerManager.onHostDestroy(); - } + public void callIdleCallbacks(double frameTime) { + ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); - @Override - public void onHeadlessJsTaskStart(int taskId) { - mJavaTimerManager.onHeadlessJsTaskStart(taskId); + if (reactApplicationContext != null) { + reactApplicationContext.getJSModule(JSTimers.class).callIdleCallbacks(frameTime); + } } @Override - public void onHeadlessJsTaskFinish(int taskId) { - mJavaTimerManager.onHeadlessJsTaskFinish(taskId); + public void emitTimeDriftWarning(String warningMessage) { + ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); + + if (reactApplicationContext != null) { + reactApplicationContext.getJSModule(JSTimers.class).emitTimeDriftWarning(warningMessage); + } } @Override @@ -127,9 +92,9 @@ public void invalidate() { HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(reactApplicationContext); - headlessJsTaskContext.removeTaskEventListener(this); + headlessJsTaskContext.removeTaskEventListener(mJavaTimerManager); + mJavaTimerManager.onInstanceDestroy(); - reactApplicationContext.removeLifecycleEventListener(this); } @VisibleForTesting diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java index 34f9fd7121b0c7..3ac33b5d0e58bf 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java @@ -19,12 +19,12 @@ import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.common.ReactConstants; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.common.ModuleDataCleaner; import com.facebook.react.modules.network.CookieJarContainer; import com.facebook.react.modules.network.ForwardingCookieHandler; import com.facebook.react.modules.network.OkHttpClientProvider; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.HashSet; import okhttp3.JavaNetCookieJar; import okhttp3.OkHttpClient; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java index b5b7f82b5cf6b9..3c283271487eda 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java @@ -18,8 +18,8 @@ import com.facebook.fbreact.specs.NativePlatformConstantsAndroidSpec; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.HashMap; import java.util.Map; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/.clang-tidy b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/.clang-tidy deleted file mode 100644 index 376b86838ffad1..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/.clang-tidy +++ /dev/null @@ -1,22 +0,0 @@ ---- -# NOTE there must be no spaces before the '-', so put the comma last. -InheritParentConfig: true -Checks: ' --, --cert-err60-cpp, --cppcoreguidelines-pro-bounds-pointer-arithmetic, --cppcoreguidelines-special-member-functions, --cppcoreguidelines-pro-type-const-cast, --fuchsia-default-arguments-calls, --fuchsia-multiple-inheritance, --google-readability-casting, --google-runtime-int, --google-runtime-references, --hicpp-special-member-functions, --llvm-header-guard, --misc-non-private-member-variables-in-classes, --misc-unused-parameters, --modernize-use-trailing-return-type, --performance-unnecessary-value-param, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessCatalystInstance.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessCatalystInstance.kt new file mode 100644 index 00000000000000..ea9dd2cb203892 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessCatalystInstance.kt @@ -0,0 +1,201 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.runtime + +import android.content.res.AssetManager +import com.facebook.proguard.annotations.DoNotStrip +import com.facebook.react.bridge.CatalystInstance +import com.facebook.react.bridge.JSIModule +import com.facebook.react.bridge.JSIModuleSpec +import com.facebook.react.bridge.JSIModuleType +import com.facebook.react.bridge.JavaScriptContextHolder +import com.facebook.react.bridge.JavaScriptModule +import com.facebook.react.bridge.NativeArray +import com.facebook.react.bridge.NativeArrayInterface +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.NativeModuleRegistry +import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener +import com.facebook.react.bridge.RuntimeExecutor +import com.facebook.react.bridge.RuntimeScheduler +import com.facebook.react.bridge.UIManager +import com.facebook.react.bridge.queue.ReactQueueConfiguration +import com.facebook.react.common.annotations.DeprecatedInNewArchitecture +import com.facebook.react.common.annotations.VisibleForTesting +import com.facebook.react.internal.turbomodule.core.interfaces.TurboModuleRegistry +import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder +import com.facebook.react.turbomodule.core.interfaces.NativeMethodCallInvokerHolder + +@DoNotStrip +@DeprecatedInNewArchitecture +public class BridgelessCatalystInstance(private val reactHost: ReactHostImpl) : CatalystInstance { + + override fun handleMemoryPressure(level: Int) { + throw UnsupportedOperationException("Unimplemented method 'handleMemoryPressure'") + } + + override fun loadScriptFromAssets( + assetManager: AssetManager, + assetURL: String, + loadSynchronously: Boolean + ) { + throw UnsupportedOperationException("Unimplemented method 'loadScriptFromAssets'") + } + + override fun loadScriptFromFile(fileName: String, sourceURL: String, loadSynchronously: Boolean) { + throw UnsupportedOperationException("Unimplemented method 'loadScriptFromFile'") + } + + override fun loadSplitBundleFromFile(fileName: String, sourceURL: String) { + throw UnsupportedOperationException("Unimplemented method 'loadSplitBundleFromFile'") + } + + override fun setSourceURLs(deviceURL: String, remoteURL: String) { + throw UnsupportedOperationException("Unimplemented method 'setSourceURLs'") + } + + override fun runJSBundle() { + throw UnsupportedOperationException("Unimplemented method 'runJSBundle'") + } + + override fun hasRunJSBundle(): Boolean { + throw UnsupportedOperationException("Unimplemented method 'hasRunJSBundle'") + } + + override fun getSourceURL(): String? { + throw UnsupportedOperationException("Unimplemented method 'getSourceURL'") + } + + @DoNotStrip + override fun invokeCallback(callbackID: Int, arguments: NativeArrayInterface) { + throw UnsupportedOperationException("Unimplemented method 'invokeCallback'") + } + + override fun callFunction(module: String, method: String, arguments: NativeArray) { + throw UnsupportedOperationException("Unimplemented method 'callFunction'") + } + + override fun destroy() { + throw UnsupportedOperationException("Unimplemented method 'destroy'") + } + + override fun isDestroyed(): Boolean { + throw UnsupportedOperationException("Unimplemented method 'isDestroyed'") + } + + @VisibleForTesting + override fun initialize() { + throw UnsupportedOperationException("Unimplemented method 'initialize'") + } + + override fun getReactQueueConfiguration(): ReactQueueConfiguration { + throw UnsupportedOperationException("Unimplemented method 'getReactQueueConfiguration'") + } + + override fun getJSModule(jsInterface: Class): T { + throw UnsupportedOperationException("Unimplemented method 'getJSModule'") + } + + override fun hasNativeModule(nativeModuleInterface: Class): Boolean { + throw UnsupportedOperationException("Unimplemented method 'hasNativeModule'") + } + + override fun getNativeModule(nativeModuleInterface: Class): T? { + throw UnsupportedOperationException("Unimplemented method 'getNativeModule'") + } + + override fun getNativeModule(moduleName: String): NativeModule? { + throw UnsupportedOperationException("Unimplemented method 'getNativeModule'") + } + + @Deprecated( + message = + "getJSIModule(JSIModuleType moduleType) is deprecated and will be deleted in the future. Please use ReactInstanceEventListener to subscribe for react instance events instead.") + override fun getJSIModule(moduleType: JSIModuleType): JSIModule { + throw UnsupportedOperationException("Unimplemented method 'getJSIModule'") + } + + override fun getNativeModules(): Collection { + throw UnsupportedOperationException("Unimplemented method 'getNativeModules'") + } + + override fun extendNativeModules(modules: NativeModuleRegistry) { + throw UnsupportedOperationException("Unimplemented method 'extendNativeModules'") + } + + override fun addBridgeIdleDebugListener(listener: NotThreadSafeBridgeIdleDebugListener) { + throw UnsupportedOperationException("Unimplemented method 'addBridgeIdleDebugListener'") + } + + override fun removeBridgeIdleDebugListener(listener: NotThreadSafeBridgeIdleDebugListener) { + throw UnsupportedOperationException("Unimplemented method 'removeBridgeIdleDebugListener'") + } + + override fun registerSegment(segmentId: Int, path: String) { + throw UnsupportedOperationException("Unimplemented method 'registerSegment'") + } + + @VisibleForTesting + override fun setGlobalVariable(propName: String, jsonValue: String) { + throw UnsupportedOperationException("Unimplemented method 'setGlobalVariable'") + } + + @Deprecated(message = "This API is unsupported in the New Architecture.") + override fun getJavaScriptContextHolder(): JavaScriptContextHolder { + throw UnsupportedOperationException("Unimplemented method 'getJavaScriptContextHolder'") + } + + override fun getRuntimeExecutor(): RuntimeExecutor { + throw UnsupportedOperationException("Unimplemented method 'getRuntimeExecutor'") + } + + override fun getRuntimeScheduler(): RuntimeScheduler { + throw UnsupportedOperationException("Unimplemented method 'getRuntimeScheduler'") + } + + @Deprecated(message = "This API is unsupported in the New Architecture.") + override fun addJSIModules(jsiModules: List>) { + throw UnsupportedOperationException("Unimplemented method 'addJSIModules'") + } + + override fun getJSCallInvokerHolder(): CallInvokerHolder? { + return reactHost.getJSCallInvokerHolder() + } + + override fun getNativeMethodCallInvokerHolder(): NativeMethodCallInvokerHolder { + throw UnsupportedOperationException("Unimplemented method 'getNativeMethodCallInvokerHolder'") + } + + @Deprecated( + message = + "setTurboModuleManager(JSIModule getter) is deprecated and will be deleted in the future. Please use setTurboModuleRegistry(TurboModuleRegistry turboModuleRegistry) instead.", + replaceWith = ReplaceWith("setTurboModuleRegistry(turboModuleRegistry)")) + override fun setTurboModuleManager(getter: JSIModule) { + throw UnsupportedOperationException("Unimplemented method 'setTurboModuleManager'") + } + + @DeprecatedInNewArchitecture( + message = + "This method will be deprecated later as part of Stable APIs with bridge removal and not encouraged usage.") + override fun setTurboModuleRegistry(turboModuleRegistry: TurboModuleRegistry) { + throw UnsupportedOperationException("Unimplemented method 'setTurboModuleRegistry'") + } + + @DeprecatedInNewArchitecture( + message = + "This method will be deprecated later as part of Stable APIs with bridge removal and not encouraged usage.") + override fun setFabricUIManager(fabricUIManager: UIManager) { + throw UnsupportedOperationException("Unimplemented method 'setFabricUIManager'") + } + + @DeprecatedInNewArchitecture( + message = + "This method will be deprecated later as part of Stable APIs with bridge removal and not encouraged usage.") + override fun getFabricUIManager(): UIManager { + throw UnsupportedOperationException("Unimplemented method 'getFabricUIManager'") + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessDevSupportManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessDevSupportManager.java index 0e424960ddc88e..e71937dd6d7f6f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessDevSupportManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessDevSupportManager.java @@ -119,7 +119,7 @@ public void onReloadWithJSDebugger(JavaJSExecutor.Factory proxyExecutorFactory) @Override public void onJSBundleLoadedFromServer() { - throw new IllegalStateException("Not implemented for bridgeless mode"); + // Not implemented } @Override diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.java index 5fa3947959105c..d1cdaa976fc1d5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.java @@ -8,6 +8,7 @@ package com.facebook.react.runtime; import android.content.Context; +import android.util.Log; import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; @@ -18,8 +19,6 @@ import com.facebook.react.bridge.NativeArray; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactNoCrashBridgeNotAllowedSoftException; -import com.facebook.react.bridge.ReactSoftExceptionLogger; import com.facebook.react.bridge.RuntimeExecutor; import com.facebook.react.bridge.UIManager; import com.facebook.react.bridge.WritableNativeArray; @@ -84,11 +83,10 @@ public void setSourceURL(String sourceURL) { @Override public CatalystInstance getCatalystInstance() { - ReactSoftExceptionLogger.logSoftExceptionVerbose( + Log.w( TAG, - new ReactNoCrashBridgeNotAllowedSoftException( - "getCatalystInstance() cannot be called when the bridge is disabled")); - throw new UnsupportedOperationException("There is no Catalyst instance in bridgeless mode."); + "[WARNING] Bridgeless doesn't support CatalystInstance. Accessing an API that's not part of the new architecture is not encouraged usage."); + return new BridgelessCatalystInstance(mReactHost); } @Override diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/CoreReactPackage.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/CoreReactPackage.java index cb8b9c13af09ae..deae9de23347e3 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/CoreReactPackage.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/CoreReactPackage.java @@ -14,7 +14,6 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.devsupport.LogBoxModule; import com.facebook.react.devsupport.interfaces.DevSupportManager; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; @@ -103,7 +102,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { reactModule.canOverrideExistingModule(), reactModule.needsEagerInit(), reactModule.isCxxModule(), - TurboModule.class.isAssignableFrom(moduleClass))); + ReactModuleInfo.classIsTurboModule(moduleClass))); } } return () -> reactModuleInfoMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.java index 674aeb42f9f7fd..c98603e9b50e47 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.java @@ -15,6 +15,9 @@ import android.app.Activity; import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.nfc.NfcAdapter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -45,20 +48,22 @@ import com.facebook.react.bridge.queue.ReactQueueConfiguration; import com.facebook.react.common.LifecycleState; import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.devsupport.DevSupportManagerBase; import com.facebook.react.devsupport.DisabledDevSupportManager; +import com.facebook.react.devsupport.InspectorFlags; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.fabric.ComponentFactory; import com.facebook.react.fabric.FabricUIManager; import com.facebook.react.interfaces.TaskInterface; import com.facebook.react.interfaces.exceptionmanager.ReactJsExceptionHandler; import com.facebook.react.interfaces.fabric.ReactSurface; +import com.facebook.react.modules.appearance.AppearanceModule; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.runtime.internal.bolts.Continuation; import com.facebook.react.runtime.internal.bolts.Task; import com.facebook.react.runtime.internal.bolts.TaskCompletionSource; +import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.BlackHoleEventDispatcher; import com.facebook.react.uimanager.events.EventDispatcher; @@ -129,12 +134,14 @@ public class ReactHostImpl implements ReactHost { new ReactLifecycleStateManager(mBridgelessReactStateTracker); private final int mId = mCounter.getAndIncrement(); private @Nullable JSEngineResolutionAlgorithm mJSEngineResolutionAlgorithm = null; - private MemoryPressureListener mMemoryPressureListener; + private @Nullable MemoryPressureListener mMemoryPressureListener; private @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler; private final Set> mBeforeDestroyListeners = Collections.synchronizedSet(new HashSet<>()); + private @Nullable ReactHostInspectorTarget mReactHostInspectorTarget; + public ReactHostImpl( Context context, ReactHostDelegate delegate, @@ -170,11 +177,6 @@ public ReactHostImpl( mReactJsExceptionHandler = reactJsExceptionHandler; mQueueThreadExceptionHandler = ReactHostImpl.this::handleHostException; mMemoryPressureRouter = new MemoryPressureRouter(context); - mMemoryPressureListener = - level -> - callWithExistingReactInstance( - "handleMemoryPressure(" + level + ")", - reactInstance -> reactInstance.handleMemoryPressure(level)); mAllowPackagerServerAccess = allowPackagerServerAccess; if (DEV) { mDevSupportManager = @@ -378,6 +380,7 @@ public ReactSurface createSurface( return surface; } + @Override public MemoryPressureRouter getMemoryPressureRouter() { return mMemoryPressureRouter; } @@ -600,6 +603,112 @@ RuntimeExecutor getRuntimeExecutor() { return null; } + /* package */ + @Nullable + CallInvokerHolder getJSCallInvokerHolder() { + final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult(); + if (reactInstance != null) { + return reactInstance.getJSCallInvokerHolder(); + } + ReactSoftExceptionLogger.logSoftException( + TAG, + new ReactNoCrashSoftException( + "Tried to get JSCallInvokerHolder while instance is not ready")); + return null; + } + + /** + * To be called when the host activity receives an activity result. + * + * @param activity The host activity + */ + @ThreadConfined(UI) + @Override + public void onActivityResult( + Activity activity, int requestCode, int resultCode, @Nullable Intent data) { + final String method = + "onActivityResult(activity = \"" + + activity + + "\", requestCode = \"" + + requestCode + + "\", resultCode = \"" + + resultCode + + "\", data = \"" + + data + + "\")"; + log(method); + + ReactContext currentContext = getCurrentReactContext(); + if (currentContext != null) { + currentContext.onActivityResult(activity, requestCode, resultCode, data); + } + ReactSoftExceptionLogger.logSoftException( + TAG, + new ReactNoCrashSoftException( + "Tried to access onActivityResult while context is not ready")); + } + + /* To be called when focus has changed for the hosting window. */ + @ThreadConfined(UI) + @Override + public void onWindowFocusChange(boolean hasFocus) { + final String method = "onWindowFocusChange(hasFocus = \"" + hasFocus + "\")"; + log(method); + + ReactContext currentContext = getCurrentReactContext(); + if (currentContext != null) { + currentContext.onWindowFocusChange(hasFocus); + } + ReactSoftExceptionLogger.logSoftException( + TAG, + new ReactNoCrashSoftException( + "Tried to access onWindowFocusChange while context is not ready")); + } + + /* This method will give JS the opportunity to receive intents via Linking. + * + * @param intent The incoming intent + */ + @ThreadConfined(UI) + @Override + public void onNewIntent(Intent intent) { + log("onNewIntent()"); + + ReactContext currentContext = getCurrentReactContext(); + if (currentContext != null) { + String action = intent.getAction(); + Uri uri = intent.getData(); + + if (uri != null + && (Intent.ACTION_VIEW.equals(action) + || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))) { + DeviceEventManagerModule deviceEventManagerModule = + currentContext.getNativeModule(DeviceEventManagerModule.class); + if (deviceEventManagerModule != null) { + deviceEventManagerModule.emitNewIntentReceived(uri); + } + } + currentContext.onNewIntent(getCurrentActivity(), intent); + } + ReactSoftExceptionLogger.logSoftException( + TAG, + new ReactNoCrashSoftException("Tried to access onNewIntent while context is not ready")); + } + + @ThreadConfined(UI) + @Override + public void onConfigurationChanged(Context updatedContext) { + ReactContext currentReactContext = getCurrentReactContext(); + if (currentReactContext != null) { + AppearanceModule appearanceModule = + currentReactContext.getNativeModule(AppearanceModule.class); + + if (appearanceModule != null) { + appearanceModule.onConfigurationChanged(updatedContext); + } + } + } + @Nullable JavaScriptContextHolder getJavaScriptContextHolder() { final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult(); @@ -759,6 +868,7 @@ private Task getOrCreateStartTask() { @ThreadConfined(UI) private void moveToHostDestroy(@Nullable ReactContext currentContext) { mReactLifecycleStateManager.moveToOnHostDestroy(currentContext); + destroyReactHostInspectorTarget(); setCurrentActivity(null); } @@ -768,16 +878,14 @@ private void raiseSoftException(String method, String message) { private void raiseSoftException(String method, String message, @Nullable Throwable throwable) { log(method, message); - if (ReactFeatureFlags.enableBridgelessArchitectureSoftExceptions) { - if (throwable != null) { - ReactSoftExceptionLogger.logSoftException( - TAG, new ReactNoCrashSoftException(method + ": " + message, throwable)); - return; - } - + if (throwable != null) { ReactSoftExceptionLogger.logSoftException( - TAG, new ReactNoCrashSoftException(method + ": " + message)); + TAG, new ReactNoCrashSoftException(method + ": " + message, throwable)); + return; } + + ReactSoftExceptionLogger.logSoftException( + TAG, new ReactNoCrashSoftException(method + ": " + message)); } private Task callWithExistingReactInstance( @@ -912,13 +1020,13 @@ private Task getOrCreateReactInstanceTask() { devSupportManager, mQueueThreadExceptionHandler, mReactJsExceptionHandler, - mUseDevSupport); + mUseDevSupport, + getOrCreateReactHostInspectorTarget()); - if (ReactFeatureFlags - .unstable_bridgelessArchitectureMemoryPressureHackyBoltsFix) { - mMemoryPressureListener = createMemoryPressureListener(instance); - } - mMemoryPressureRouter.addMemoryPressureListener(mMemoryPressureListener); + MemoryPressureListener memoryPressureListener = + createMemoryPressureListener(instance); + mMemoryPressureListener = memoryPressureListener; + mMemoryPressureRouter.addMemoryPressureListener(memoryPressureListener); log(method, "Loading JS Bundle"); instance.loadJSBundle(bundleLoader); @@ -1197,6 +1305,10 @@ private Task getOrCreateReloadTask(String reason) { final ReactInstance reactInstance = reactInstanceTaskUnwrapper.unwrap(task, "1: Starting reload"); + if (reactInstance != null) { + reactInstance.unregisterFromInspector(); + } + final ReactContext reactContext = mBridgelessReactContextRef.getNullable(); if (reactContext == null) { raiseSoftException(method, "ReactContext is null. Reload reason: " + reason); @@ -1246,8 +1358,10 @@ private Task getOrCreateReloadTask(String reason) { task -> { reactInstanceTaskUnwrapper.unwrap(task, "4: Destroying ReactContext"); - log(method, "Removing memory pressure listener"); - mMemoryPressureRouter.removeMemoryPressureListener(mMemoryPressureListener); + if (mMemoryPressureListener != null) { + log(method, "Removing memory pressure listener"); + mMemoryPressureRouter.removeMemoryPressureListener(mMemoryPressureListener); + } final ReactContext reactContext = mBridgelessReactContextRef.getNullable(); if (reactContext != null) { @@ -1370,6 +1484,10 @@ private Task getOrCreateDestroyTask(final String reason, @Nullable Excepti final ReactInstance reactInstance = reactInstanceTaskUnwrapper.unwrap(task, "1: Starting destroy"); + if (reactInstance != null) { + reactInstance.unregisterFromInspector(); + } + // Step 1: Destroy DevSupportManager if (mUseDevSupport) { log(method, "DevSupportManager cleanup"); @@ -1517,4 +1635,19 @@ public void setJsEngineResolutionAlgorithm( @Nullable JSEngineResolutionAlgorithm jsEngineResolutionAlgorithm) { mJSEngineResolutionAlgorithm = jsEngineResolutionAlgorithm; } + + private @Nullable ReactHostInspectorTarget getOrCreateReactHostInspectorTarget() { + if (mReactHostInspectorTarget == null && InspectorFlags.getEnableModernCDPRegistry()) { + mReactHostInspectorTarget = new ReactHostInspectorTarget(this); + } + + return mReactHostInspectorTarget; + } + + private void destroyReactHostInspectorTarget() { + if (mReactHostInspectorTarget != null) { + mReactHostInspectorTarget.close(); + mReactHostInspectorTarget = null; + } + } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostInspectorTarget.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostInspectorTarget.kt new file mode 100644 index 00000000000000..6b6820d451d44d --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostInspectorTarget.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.runtime + +import com.facebook.jni.HybridData +import com.facebook.proguard.annotations.DoNotStripAny +import com.facebook.react.runtime.internal.bolts.Task +import com.facebook.soloader.SoLoader +import java.io.Closeable +import java.util.concurrent.Executor + +@DoNotStripAny +internal class ReactHostInspectorTarget(private val reactHostImpl: ReactHostImpl) : Closeable { + // fbjni looks for the exact name "mHybridData": + // https://github.com/facebookincubator/fbjni/blob/5587a7fd2b191656be9391a3832ce04c034009a5/cxx/fbjni/detail/Hybrid.h#L310 + @Suppress("NoHungarianNotation") + private val mHybridData: HybridData = + initHybrid(reactHostImpl, Task.UI_THREAD_CONDITIONAL_SYNC_EXECUTOR) + + private external fun initHybrid(reactHostImpl: ReactHostImpl, executor: Executor): HybridData + + override fun close() { + mHybridData.resetNative() + } + + private companion object { + init { + SoLoader.loadLibrary("rninstance") + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.java index 37d8d44d830a4b..8b590833d8df66 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.java @@ -21,7 +21,6 @@ import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JSBundleLoaderDelegate; import com.facebook.react.bridge.JavaScriptContextHolder; -import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.NativeArray; import com.facebook.react.bridge.NativeMap; import com.facebook.react.bridge.NativeModule; @@ -114,7 +113,8 @@ final class ReactInstance { DevSupportManager devSupportManager, QueueThreadExceptionHandler exceptionHandler, ReactJsExceptionHandler reactExceptionManager, - boolean useDevSupport) { + boolean useDevSupport, + @Nullable ReactHostInspectorTarget reactHostInspectorTarget) { mBridgelessReactContext = bridgelessReactContext; mDelegate = delegate; @@ -142,6 +142,7 @@ final class ReactInstance { if (useDevSupport) { devSupportManager.startInspector(); } + JSTimerExecutor jsTimerExecutor = createJSTimerExecutor(); mJavaTimerManager = new JavaTimerManager( @@ -150,24 +151,6 @@ final class ReactInstance { ReactChoreographer.getInstance(), devSupportManager); - mBridgelessReactContext.addLifecycleEventListener( - new LifecycleEventListener() { - @Override - public void onHostResume() { - mJavaTimerManager.onHostResume(); - } - - @Override - public void onHostPause() { - mJavaTimerManager.onHostPause(); - } - - @Override - public void onHostDestroy() { - mJavaTimerManager.onHostDestroy(); - } - }); - JSRuntimeFactory jsRuntimeFactory = mDelegate.getJsRuntimeFactory(); BindingsInstaller bindingsInstaller = mDelegate.getBindingsInstaller(); // Notify JS if profiling is enabled @@ -182,7 +165,8 @@ public void onHostDestroy() { jsTimerExecutor, reactExceptionManager, bindingsInstaller, - isProfiling); + isProfiling, + reactHostInspectorTarget); mJavaScriptContextHolder = new JavaScriptContextHolder(getJavaScriptContext()); @@ -446,6 +430,7 @@ public Collection getNativeModules() { mQueueConfiguration.destroy(); mTurboModuleManager.invalidate(); mFabricUIManager.invalidate(); + mJavaTimerManager.onInstanceDestroy(); mHybridData.resetNative(); mComponentNameResolverManager = null; mUIConstantsProviderManager = null; @@ -463,7 +448,8 @@ private native HybridData initHybrid( JSTimerExecutor jsTimerExecutor, ReactJsExceptionHandler jReactExceptionsManager, @Nullable BindingsInstaller jBindingsInstaller, - boolean isProfiling); + boolean isProfiling, + @Nullable ReactHostInspectorTarget reactHostInspectorTarget); @DoNotStrip private static native JSTimerExecutor createJSTimerExecutor(); @@ -475,7 +461,7 @@ private native HybridData initHybrid( private native void loadJSBundleFromAssets(AssetManager assetManager, String assetURL); - private native CallInvokerHolderImpl getJSCallInvokerHolder(); + /* package */ native CallInvokerHolderImpl getJSCallInvokerHolder(); private native NativeMethodCallInvokerHolderImpl getNativeMethodCallInvokerHolder(); @@ -494,6 +480,9 @@ private native HybridData initHybrid( private native void handleMemoryPressureJs(int pressureLevel); + @ThreadConfined(ThreadConfined.UI) + /* package */ native void unregisterFromInspector(); + public void handleMemoryPressure(int level) { try { handleMemoryPressureJs(level); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/AndroidExecutors.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/AndroidExecutors.java index 49518ccc90db0b..dc4e691dc0b753 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/AndroidExecutors.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/AndroidExecutors.java @@ -39,9 +39,11 @@ final class AndroidExecutors { private static final AndroidExecutors INSTANCE = new AndroidExecutors(); @NonNull private final Executor uiThread; + @NonNull private final Executor uiThreadConditionalSync; private AndroidExecutors() { uiThread = new UIThreadExecutor(); + uiThreadConditionalSync = new UIThreadConditionalSyncExecutor(); } /** @@ -122,16 +124,52 @@ public static void allowCoreThreadTimeout(@NonNull ThreadPoolExecutor executor, } } - /** An {@link java.util.concurrent.Executor} that executes tasks on the UI thread. */ + /** + * An {@link java.util.concurrent.Executor} that schedules tasks to run asynchronously on the UI + * thread. + */ public static @NonNull Executor uiThread() { return INSTANCE.uiThread; } - /** An {@link java.util.concurrent.Executor} that runs tasks on the UI thread. */ + /** + * An {@link java.util.concurrent.Executor} that runs tasks on the UI thread (immediately if + * already on that thread). + */ + public static @NonNull Executor uiThreadConditionalSync() { + return INSTANCE.uiThreadConditionalSync; + } + + /** + * An {@link java.util.concurrent.Executor} that schedules tasks to run asynchronously on the UI + * thread. + */ private static class UIThreadExecutor implements Executor { + private final Handler mHandler = new Handler(Looper.getMainLooper()); + + @Override + public void execute(@NonNull Runnable command) { + // Otherwise, post it on the main thread handler + mHandler.post(command); + } + } + + /** + * An {@link java.util.concurrent.Executor} that runs tasks on the UI thread (immediately if + * already on that thread). + */ + private static class UIThreadConditionalSyncExecutor implements Executor { + private final Handler mHandler = new Handler(Looper.getMainLooper()); + @Override public void execute(@NonNull Runnable command) { - new Handler(Looper.getMainLooper()).post(command); + if (Looper.myLooper() == mHandler.getLooper()) { + // If we're already on the main thread, execute the command immediately + command.run(); + } else { + // Otherwise, post it on the main thread handler + mHandler.post(command); + } } } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/Task.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/Task.java index 1f4db71e3368bf..634fb318a15212 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/Task.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/internal/bolts/Task.java @@ -42,6 +42,10 @@ public class Task implements TaskInterface { /** An {@link java.util.concurrent.Executor} that executes tasks on the UI thread. */ public static final Executor UI_THREAD_EXECUTOR = AndroidExecutors.uiThread(); + /** An {@link java.util.concurrent.Executor} that executes tasks on the UI thread. */ + public static final Executor UI_THREAD_CONDITIONAL_SYNC_EXECUTOR = + AndroidExecutors.uiThreadConditionalSync(); + /** * Interface for handlers invoked when a failed {@code Task} is about to be finalized, but the * exception has not been consumed. diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index b06dcc7d745983..b95774889eb4fc 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -15,7 +15,6 @@ import com.facebook.react.bridge.ModuleSpec; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; @@ -47,7 +46,6 @@ import com.facebook.react.views.drawer.ReactDrawerLayoutManager; import com.facebook.react.views.image.ReactImageManager; import com.facebook.react.views.modal.ReactModalHostManager; -import com.facebook.react.views.popupmenu.ReactPopupMenuManager; import com.facebook.react.views.progressbar.ReactProgressBarViewManager; import com.facebook.react.views.scroll.ReactHorizontalScrollContainerViewManager; import com.facebook.react.views.scroll.ReactHorizontalScrollViewManager; @@ -171,7 +169,6 @@ public List createViewManagers(ReactApplicationContext reactContext viewManagers.add(new ReactScrollViewManager()); viewManagers.add(new ReactSwitchManager()); viewManagers.add(new SwipeRefreshLayoutManager()); - viewManagers.add(new ReactPopupMenuManager()); // Native equivalents viewManagers.add(new FrescoBasedReactTextInlineImageViewManager()); @@ -213,7 +210,6 @@ public Map getViewManagersMap() { appendMap(viewManagers, ReactSwitchManager.REACT_CLASS, ReactSwitchManager::new); appendMap( viewManagers, SwipeRefreshLayoutManager.REACT_CLASS, SwipeRefreshLayoutManager::new); - appendMap(viewManagers, ReactPopupMenuManager.REACT_CLASS, ReactPopupMenuManager::new); appendMap( viewManagers, FrescoBasedReactTextInlineImageViewManager.REACT_CLASS, @@ -300,7 +296,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { reactModule.canOverrideExistingModule(), reactModule.needsEagerInit(), reactModule.isCxxModule(), - TurboModule.class.isAssignableFrom(moduleClass))); + ReactModuleInfo.classIsTurboModule(moduleClass))); } } return () -> reactModuleInfoMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.kt index 394ffd69bfa622..6333b8125400b8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.kt @@ -6,15 +6,14 @@ */ package com.facebook.react.turbomodule.core.interfaces +/** All turbo modules should inherit from this interface */ +public interface TurboModule { + /** Initialize the TurboModule. */ + public fun initialize() -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture - -/** - * This interface was introduced for backward compatibility purposes. This interface will be - * deprecated as part of the deprecation and removal of ReactModuleInfoProvider in the near future. - * - * See description of https://github.com/facebook/react-native/pull/41412 for more context. - */ -@DeprecatedInNewArchitecture -public interface TurboModule : - com.facebook.react.internal.turbomodule.core.interfaces.TurboModule {} + /** + * Called during the turn down process of ReactHost. This method is called before React Native is + * stopped. Override this method to clean up resources used by the TurboModule. + */ + public fun invalidate() +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ComponentNameResolverManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ComponentNameResolverManager.java index 75463b8c43babd..ac97b95c3c7e6a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ComponentNameResolverManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ComponentNameResolverManager.java @@ -7,12 +7,14 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStripAny; import com.facebook.react.bridge.RuntimeExecutor; import com.facebook.soloader.SoLoader; +@Nullsafe(Nullsafe.Mode.LOCAL) @DoNotStripAny public class ComponentNameResolverManager { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FabricViewStateManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FabricViewStateManager.java index 02ea431f7f4828..6792a8cb9c7a06 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FabricViewStateManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FabricViewStateManager.java @@ -9,6 +9,7 @@ import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; @@ -24,6 +25,7 @@ * retrying the UpdateState call until it succeeds; or you call setState again; or the View layer is * updated with a newer StateWrapper. */ +@Nullsafe(Nullsafe.Mode.LOCAL) @Deprecated( since = "Deprecated class since v0.73.0, please use com.facebook.react.uimanager.StateWrapper instead.", diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FilterHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FilterHelper.java new file mode 100644 index 00000000000000..56bfa21ee676ac --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FilterHelper.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.uimanager; + +import android.annotation.TargetApi; +import android.graphics.ColorFilter; +import android.graphics.ColorMatrix; +import android.graphics.ColorMatrixColorFilter; +import android.graphics.RenderEffect; +import android.graphics.Shader; +import androidx.annotation.Nullable; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.bridge.ReadableMap; + +@TargetApi(31) +class FilterHelper { + static @Nullable RenderEffect parseFilters(@Nullable ReadableArray filters) { + if (filters == null) { + return null; + } + + RenderEffect chainedEffects = null; + for (int i = 0; i < filters.size(); i++) { + ReadableMap filter = filters.getMap(i); + @Nullable String filterName = filter.getString("name"); + if (filterName == null) { + continue; + } + + switch (filterName) { + case "brightness": + float brightnessAmount = (float) filter.getDouble("amount"); + ColorFilter brightnessFilter = + new ColorMatrixColorFilter(getBrightnessColorMatrix(brightnessAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, brightnessFilter); + break; + case "contrast": + float contrastAmount = (float) filter.getDouble("amount"); + ColorFilter contrastFilter = + new ColorMatrixColorFilter(getContrastColorMatrix(contrastAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, contrastFilter); + break; + case "grayscale": + float grayscaleAmount = (float) filter.getDouble("amount"); + ColorFilter grayscaleFilter = + new ColorMatrixColorFilter(getGrayscaleColorMatrix(grayscaleAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, grayscaleFilter); + break; + case "sepia": + float sepiaAmount = (float) filter.getDouble("amount"); + ColorFilter sepiaFilter = new ColorMatrixColorFilter(getSepiaColorMatrix(sepiaAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, sepiaFilter); + break; + case "saturate": + float saturateAmount = (float) filter.getDouble("amount"); + ColorFilter saturateFilter = + new ColorMatrixColorFilter(getSaturateColorMatrix(saturateAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, saturateFilter); + break; + case "hue-rotate": + float hueRotateAmount = (float) filter.getDouble("amount"); + ColorFilter hueRotateFilter = + new ColorMatrixColorFilter(getHueRotateColorMatrix(hueRotateAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, hueRotateFilter); + break; + case "invert": + float invertAmount = (float) filter.getDouble("amount"); + ColorFilter invertColorFilter = + new ColorMatrixColorFilter(getInvertColorMatrix(invertAmount)); + chainedEffects = chainColorFilterEffect(chainedEffects, invertColorFilter); + break; + case "blur": + float blurAmount = (float) filter.getDouble("amount"); + chainedEffects = chainBlurFilterEffect(chainedEffects, blurAmount); + break; + default: + throw new IllegalArgumentException("Invalid filter name: " + filterName); + } + } + + return chainedEffects; + } + + // https://www.w3.org/TR/filter-effects-1/#blurEquivalent + private static RenderEffect chainBlurFilterEffect( + @Nullable RenderEffect chainedEffects, float std) { + // Android takes blur amount as a radius while web takes a sigma. This value + // is used under the hood to convert between them on Android + // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/libs/hwui/utils/Blur.cpp + float sigmaToRadiusRatio = 0.57735f; + float radius = (std - 0.5f) / sigmaToRadiusRatio; + float scaledRadius = PixelUtil.toPixelFromDIP(radius); + + return chainedEffects == null + ? RenderEffect.createBlurEffect(scaledRadius, scaledRadius, Shader.TileMode.DECAL) + : RenderEffect.createBlurEffect( + scaledRadius, scaledRadius, chainedEffects, Shader.TileMode.DECAL); + } + + private static RenderEffect chainColorFilterEffect( + @Nullable RenderEffect chainedEffects, ColorFilter colorFilter) { + return chainedEffects == null + ? RenderEffect.createColorFilterEffect(colorFilter) + : RenderEffect.createColorFilterEffect(colorFilter, chainedEffects); + } + + // https://www.w3.org/TR/filter-effects-1/#brightnessEquivalent + private static ColorMatrix getBrightnessColorMatrix(float amount) { + ColorMatrix matrix = new ColorMatrix(); + matrix.setScale(amount, amount, amount, 1); + + return matrix; + } + + // https://www.w3.org/TR/filter-effects-1/#contrastEquivalent + private static ColorMatrix getContrastColorMatrix(float amount) { + // Multiply by 255 as Android operates in [0, 255] while the spec operates in [0, 1]. + // This really only matters if there is an intercept that needs to be added + float intercept = 255 * (-(amount / 2.0f) + 0.5f); + + float[] colorMatrix = { + amount, 0, 0, 0, intercept, // + 0, amount, 0, 0, intercept, // + 0, 0, amount, 0, intercept, // + 0, 0, 0, 1, 0 + }; + + return new ColorMatrix(colorMatrix); + } + + // https://www.w3.org/TR/filter-effects-1/#grayscaleEquivalent + private static float[] getGrayscaleColorMatrix(float amount) { + float inverseAmount = 1 - amount; + float[] colorMatrix = { + 0.2126f + 0.7874f * inverseAmount, + 0.7152f - 0.7152f * inverseAmount, + 0.0722f - 0.0722f * inverseAmount, + 0, + 0, + 0.2126f - 0.2126f * inverseAmount, + 0.7152f + 0.2848f * inverseAmount, + 0.0722f - 0.0722f * inverseAmount, + 0, + 0, + 0.2126f - 0.2126f * inverseAmount, + 0.7152f - 0.7152f * inverseAmount, + 0.0722f + 0.9278f * inverseAmount, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + }; + + return colorMatrix; + } + + // https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent + private static float[] getSepiaColorMatrix(float amount) { + float inverseAmount = 1 - amount; + float[] colorMatrix = { + 0.393f + 0.607f * inverseAmount, + 0.769f - 0.769f * inverseAmount, + 0.189f - 0.189f * inverseAmount, + 0, + 0, + 0.349f - 0.349f * inverseAmount, + 0.686f + 0.314f * inverseAmount, + 0.168f - 0.168f * inverseAmount, + 0, + 0, + 0.272f - 0.272f * inverseAmount, + 0.534f - 0.534f * inverseAmount, + 0.131f + 0.869f * inverseAmount, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + }; + + return colorMatrix; + } + + // https://www.w3.org/TR/filter-effects-1/#saturateEquivalent + private static ColorMatrix getSaturateColorMatrix(float amount) { + ColorMatrix matrix = new ColorMatrix(); + matrix.setSaturation(amount); + + return matrix; + } + + // https://www.w3.org/TR/filter-effects-1/#huerotateEquivalent + private static float[] getHueRotateColorMatrix(float amount) { + double amountRads = Math.toRadians(amount); + float cos = (float) Math.cos(amountRads); + float sin = (float) Math.sin(amountRads); + float[] matrix = { + 0.213f + 0.787f * cos - 0.213f * sin, + 0.715f - 0.715f * cos - 0.715f * sin, + 0.072f - 0.072f * cos + 0.928f * sin, + 0, + 0, + 0.213f - 0.213f * cos + 0.143f * sin, + 0.715f + 0.285f * cos + 0.140f * sin, + 0.072f - 0.072f * cos - 0.283f * sin, + 0, + 0, + 0.213f - 0.213f * cos - 0.787f * sin, + 0.715f - 0.715f * cos + 0.715f * sin, + 0.072f + 0.928f * cos + 0.072f * sin, + 0, + 0, + 0, + 0, + 0, + 1, + 0 + }; + + return matrix; + } + + // https://www.w3.org/TR/filter-effects-1/#invertEquivalent + private static float[] getInvertColorMatrix(float amount) { + float slope = 1 - 2 * amount; + float intercept = amount * 255; + float[] matrix = { + slope, 0, 0, 0, intercept, // + 0, slope, 0, 0, intercept, // + 0, 0, slope, 0, intercept, // + 0, 0, 0, 1, 0 + }; + + return matrix; + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java index 94add5350e3d5a..1d1a5d56a56bf6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java @@ -7,6 +7,9 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + +@Nullsafe(Nullsafe.Mode.LOCAL) public class FloatUtil { private static final float EPSILON = .00001f; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java index 5f8115c0faa4f8..9ed8000da172f2 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java @@ -8,6 +8,7 @@ package com.facebook.react.uimanager; import android.view.Choreographer; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.JSExceptionHandler; import com.facebook.react.bridge.ReactContext; @@ -15,6 +16,7 @@ * Abstract base for a Choreographer FrameCallback that should have any RuntimeExceptions it throws * handled by the {@link JSExceptionHandler} registered if the app is in dev mode. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public abstract class GuardedFrameCallback implements Choreographer.FrameCallback { private final ReactContext mReactContext; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewGroupManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewGroupManager.java index 9dd93bb58724dd..f505c24150c908 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewGroupManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewGroupManager.java @@ -8,15 +8,19 @@ package com.facebook.react.uimanager; import android.view.View; +import androidx.annotation.Nullable; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.UiThreadUtil; /** Interface providing children management API for view managers of classes extending ViewGroup. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public interface IViewGroupManager extends IViewManagerWithChildren { /** Adds a child view into the parent at the index specified as a parameter */ void addView(T parent, View child, int index); /** @return child of the parent view at the index specified as a parameter. */ + @Nullable View getChildAt(T parent, int index); /** Removes View from the parent View at the index specified as a parameter. */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java index 931f338e4bdad1..215293188ea2c7 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java @@ -9,9 +9,11 @@ import android.view.View; import androidx.annotation.Nullable; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.JSApplicationCausedNativeException; /** An exception caused by JS requesting the UI manager to perform an illegal view operation. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class IllegalViewOperationException extends JSApplicationCausedNativeException { @Nullable private View mView; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java index 8f931f4254368c..77143c90e30f93 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java @@ -11,6 +11,7 @@ import android.view.ViewGroup; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.uimanager.events.TouchEvent; @@ -22,6 +23,7 @@ * need to call handleTouchEvent from onTouchEvent and onInterceptTouchEvent. It will correctly find * the right view to handle the touch and also dispatch the appropriate event to JS */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class JSTouchDispatcher { private int mTargetTag = -1; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java index 0d698f7918965e..03f52e17cf25e3 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java @@ -8,11 +8,13 @@ package com.facebook.react.uimanager; import com.facebook.infer.annotation.Assertions; +import com.facebook.infer.annotation.Nullsafe; /** * Provides helper methods for converting transform operations into a matrix and then into a list of * translate, scale and rotate commands. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class MatrixMathHelper { private static final double EPSILON = .00001d; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java index 3f2954547d33fb..3dcdfa91e97614 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java @@ -8,8 +8,10 @@ package com.facebook.react.uimanager; import android.view.View; +import com.facebook.infer.annotation.Nullsafe; /** Shared utility for asserting on MeasureSpecs. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class MeasureSpecAssertions { public static final void assertExplicitMeasureSpec(int widthMeasureSpec, int heightMeasureSpec) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java index e45f7dd805be73..35d40c382414f5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java @@ -7,10 +7,13 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + // Common conditionals: // - `kind == PARENT` checks whether the node can host children in the native tree. // - `kind != NONE` checks whether the node appears in the native tree. +@Nullsafe(Nullsafe.Mode.LOCAL) public enum NativeKind { // Node is in the native hierarchy and the HierarchyOptimizer should assume it can host children // (e.g. because it's a ViewGroup). Note that it's okay if the node doesn't support children. When diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java index 02c6fe31efee2a..8bf0a04c8a4e8b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java @@ -7,10 +7,13 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + /** * Exception thrown when a class tries to access a native view by a tag that has no native view * associated with it. */ +@Nullsafe(Nullsafe.Mode.LOCAL) class NoSuchNativeViewException extends IllegalViewOperationException { public NoSuchNativeViewException(String detailMessage) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java index 4d771f59492bd6..37fc190500425a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java @@ -9,11 +9,13 @@ import androidx.annotation.Nullable; import androidx.core.util.Pools; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; /** Event used to notify JS component about changes of its position or dimensions */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class OnLayoutEvent extends Event { private static final Pools.SynchronizedPool EVENTS_POOL = diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java index b38c1beeeb0519..d388af8e07dadd 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java @@ -9,8 +9,10 @@ import android.util.DisplayMetrics; import android.util.TypedValue; +import com.facebook.infer.annotation.Nullsafe; /** Android dp to pixel manipulation */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class PixelUtil { /** Convert from DIP to PX */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java index bf97d45b502f07..207a650d0dbd42 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java @@ -7,12 +7,14 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import java.util.Locale; /** * Possible values for pointer events that a view and its descendants should receive. See * https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events for more info. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public enum PointerEvents { /** Neither the container nor its children receive events. */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java index 0616b16a76bcb8..ff88e2471da764 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java @@ -10,12 +10,14 @@ import android.graphics.Rect; import android.view.View; import android.view.ViewParent; +import com.facebook.infer.annotation.Nullsafe; import javax.annotation.concurrent.NotThreadSafe; /** * Provides implementation of common tasks for view and it's view manager supporting property {@code * removeClippedSubviews}. */ +@Nullsafe(Nullsafe.Mode.LOCAL) @NotThreadSafe public class ReactClippingViewGroupHelper { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java index f574371ae30bc0..63bdc3fa63779e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java @@ -7,6 +7,9 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + +@Nullsafe(Nullsafe.Mode.LOCAL) public class ReactInvalidPropertyException extends RuntimeException { public ReactInvalidPropertyException(String property, String value, String expectedValues) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java index 20a89f746bf249..49430b70d1de93 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java @@ -10,10 +10,12 @@ import android.os.Bundle; import android.view.ViewGroup; import androidx.annotation.Nullable; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.uimanager.common.UIManagerType; import java.util.concurrent.atomic.AtomicInteger; /** Interface for the root native view of a React native application */ +@Nullsafe(Nullsafe.Mode.LOCAL) public interface ReactRoot { /** This constant represents that ReactRoot hasn't started yet or it has been destroyed. */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRootViewTagGenerator.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRootViewTagGenerator.java index 90d9ac63ad7483..6c128e202ec33a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRootViewTagGenerator.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRootViewTagGenerator.java @@ -7,7 +7,10 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + /** Incremental counter for React Root View tag. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ReactRootViewTagGenerator { // Keep in sync with ReactIOSTagHandles JS module - see that file for an explanation on why the diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java index 504bedbfe220da..7f7982597e8def 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java @@ -9,6 +9,7 @@ import android.view.View; import androidx.annotation.Nullable; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; @@ -32,6 +33,7 @@ * shouldn't be updated (whereas in all other cases it should be updated to the new value or the * property should be reset). */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ReactStylesDiffMap { /* package */ final ReadableMap mBackingMap; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java index 16fbb71ae118b5..67c80d2c80f8fd 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java @@ -7,10 +7,12 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.yoga.YogaConfig; import com.facebook.yoga.YogaConfigFactory; import com.facebook.yoga.YogaErrata; +@Nullsafe(Nullsafe.Mode.LOCAL) public class ReactYogaConfigProvider { private static YogaConfig YOGA_CONFIG; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java index 4393528caac2a5..3a09de11df831d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java @@ -9,8 +9,10 @@ import android.view.ViewGroup; import android.widget.FrameLayout; +import com.facebook.infer.annotation.Nullsafe; /** View manager for ReactRootView components. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class RootViewManager extends ViewGroupManager { public static final String REACT_CLASS = "RootView"; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java index ef65aae2f83577..18be6800791658 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java @@ -8,6 +8,7 @@ package com.facebook.react.uimanager; import android.view.View; +import com.facebook.infer.annotation.Nullsafe; /** * Common base class for most of the {@link ViewManager}s. It provides support for most common @@ -17,6 +18,7 @@ * * @param the view handled by this manager */ +@Nullsafe(Nullsafe.Mode.LOCAL) public abstract class SimpleViewManager extends BaseViewManager { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java index 9ff37664d52b67..889eeade9e4c65 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java @@ -7,6 +7,7 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.yoga.YogaConstants; import java.util.Arrays; @@ -15,6 +16,7 @@ * properly implement interactions and updates for properties like margin, marginLeft, and * marginHorizontal. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class Spacing { /** Spacing type that represents the left direction. E.g. {@code marginLeft}. */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIConstantsProviderManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIConstantsProviderManager.java index 06af04472248b3..5fdf6e535e2012 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIConstantsProviderManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIConstantsProviderManager.java @@ -7,6 +7,7 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStripAny; @@ -15,6 +16,7 @@ import com.facebook.soloader.SoLoader; import javax.annotation.Nullable; +@Nullsafe(Nullsafe.Mode.LOCAL) @DoNotStripAny public class UIConstantsProviderManager { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java index 52f635eaa6aac0..c4e7b0c5cd3474 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java @@ -16,6 +16,7 @@ import android.widget.EditText; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactNoCrashSoftException; @@ -26,6 +27,7 @@ import com.facebook.react.uimanager.events.EventDispatcherProvider; /** Helper class for {@link UIManager}. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class UIManagerHelper { private static final String TAG = UIManagerHelper.class.getName(); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java index ee4f7969235a01..be8c69379f741c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java @@ -9,12 +9,14 @@ import android.view.accessibility.AccessibilityEvent; import android.widget.ImageView; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.events.TouchEventType; import java.util.Map; /** Constants exposed to JS from {@link UIManagerModule}. */ -/* package */ class UIManagerModuleConstants { +/* package */ @Nullsafe(Nullsafe.Mode.LOCAL) +class UIManagerModuleConstants { public static final String ACTION_DISMISSED = "dismissed"; public static final String ACTION_ITEM_SELECTED = "itemSelected"; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java index 098b7e15fa976e..4a246040c3152b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java @@ -10,6 +10,7 @@ import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.facebook.common.logging.FLog; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.common.MapBuilder; import com.facebook.react.common.build.ReactBuildConfig; import com.facebook.react.config.ReactFeatureFlags; @@ -24,6 +25,7 @@ * Helps generate constants map for {@link UIManagerModule} by collecting and merging constants from * registered view managers. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class UIManagerModuleConstantsHelper { private static final String TAG = "UIManagerModuleConstantsHelper"; private static final String BUBBLING_EVENTS_KEY = "bubblingEventTypes"; @@ -178,7 +180,7 @@ private static void validateDirectEventNames( } @VisibleForTesting - /* package */ static void normalizeEventTypes(Map events) { + /* package */ static void normalizeEventTypes(@Nullable Map events) { if (events == null) { return; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java index 8cab4071bda2ef..772011fb5c6077 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java @@ -7,7 +7,10 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; + /** Default property values for Views to be shared between Views and ShadowViews. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ViewDefaults { public static final float FONT_SIZE_SP = 14.0f; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java index 2bd1d754f3a398..99356c260c311f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java @@ -11,12 +11,14 @@ import android.view.ViewGroup; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.common.ReactConstants; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** Helper to handle implementing ViewGroups with custom drawing order based on z-index. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ViewGroupDrawingOrderHelper { private final ViewGroup mViewGroup; private int mNumberOfChildrenWithZIndex = 0; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java index 419747ae9b92b8..06fa73b93854b1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java @@ -10,11 +10,13 @@ import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.UiThreadUtil; import java.util.List; import java.util.WeakHashMap; /** Class providing children management API for view managers of classes extending ViewGroup. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public abstract class ViewGroupManager extends BaseViewManager implements IViewGroupManager { @@ -67,6 +69,7 @@ public int getChildCount(T parent) { } @Override + @Nullable public View getChildAt(T parent, int index) { return parent.getChildAt(index); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java index 937e0c54c55d72..205a3214a1937c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java @@ -9,11 +9,13 @@ import android.view.View; import android.view.ViewGroup; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.UiThreadUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +@Nullsafe(Nullsafe.Mode.LOCAL) class ViewHierarchyDumper { public static JSONObject toJSON(View view) throws JSONException { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java index fa6eae38a49771..ff9832dbb055b6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java @@ -8,12 +8,14 @@ package com.facebook.react.uimanager; import android.graphics.Color; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import java.util.Arrays; import java.util.HashSet; /** Keys for props that need to be shared across multiple classes. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ViewProps { public static final String VIEW_CLASS_NAME = "RCTView"; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java index 0e7f28d571f7e0..1af237ec325de6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java @@ -7,10 +7,12 @@ package com.facebook.react.uimanager; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.common.ClearableSynchronizedPool; import com.facebook.yoga.YogaNode; /** Static holder for a recycling pool of YogaNodes. */ +@Nullsafe(Nullsafe.Mode.LOCAL) class YogaNodePool { private static final Object sInitLock = new Object(); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.java deleted file mode 100644 index 052c9be79d7628..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -package com.facebook.react.util; - -import android.util.Log; -import com.facebook.common.logging.FLog; -import com.facebook.infer.annotation.Nullsafe; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.common.ReactConstants; -import javax.annotation.Nullable; - -/** Logging wrapper for FLog with LogBox support. */ -@Nullsafe(Nullsafe.Mode.LOCAL) -public class RNLog { - public static final int MINIMUM_LEVEL_FOR_UI = Log.WARN; - - public static final int LOG = Log.VERBOSE; - - public static final int TRACE = Log.DEBUG; - - public static final int ADVICE = Log.INFO; - - public static final int WARN = Log.WARN; - - public static final int ERROR = Log.ERROR; - - /** - * Log a log level message tagged as React Native to the console. - * - * @param message The message to log. - */ - public static void l(String message) { - FLog.i(ReactConstants.TAG, message); - } - - /** - * Log a trace level message tagged as React Native to the console. - * - * @param message The message to log. - */ - public static void t(String message) { - FLog.i(ReactConstants.TAG, message); - } - - /** - * Log a warning level message tagged as React Native to the console. This warning will not be - * shown in LogBox. - * - * @param message The message to log. - */ - public static void a(String message) { - FLog.w(ReactConstants.TAG, "(ADVICE)" + message); - } - - /** - * Log a warning level message tagged as React Native to the console and display in the app. - * - * @param context The React context of the application use to display the warning. - * @param message The message to log. - */ - public static void w(@Nullable ReactContext context, String message) { - logInternal(context, message, WARN); - FLog.w(ReactConstants.TAG, message); - } - - /** - * Log an error level message tagged as React Native to the console and display in the app. - * - * @param context The React context of the application use to display the error. - * @param message The message to log. - */ - public static void e(@Nullable ReactContext context, String message) { - logInternal(context, message, ERROR); - FLog.e(ReactConstants.TAG, message); - } - - /** - * Log an error level message tagged as React Native to the console. This error will not be shown - * in LogBox. - * - * @param message The message to log. - */ - public static void e(String message) { - FLog.e(ReactConstants.TAG, message); - } - - private static void logInternal( - @Nullable ReactContext context, @Nullable String message, int level) { - if (level >= MINIMUM_LEVEL_FOR_UI) { - if (context != null && context.hasActiveReactInstance() && message != null) { - context.getJSModule(RCTLog.class).logIfNoNativeHook(levelToString(level), message); - } - } - } - - private static String levelToString(int level) { - switch (level) { - case LOG: - case TRACE: - return "log"; - case ADVICE: - case WARN: - return "warn"; - case ERROR: - return "error"; - default: - return "none"; - } - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.kt new file mode 100644 index 00000000000000..481ed8969c13fe --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/util/RNLog.kt @@ -0,0 +1,108 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.util + +import android.util.Log +import com.facebook.common.logging.FLog +import com.facebook.react.bridge.ReactContext +import com.facebook.react.common.ReactConstants + +/** Logging wrapper for FLog with LogBox support. */ +public object RNLog { + + public const val MINIMUM_LEVEL_FOR_UI: Int = Log.WARN + public const val LOG: Int = Log.VERBOSE + public const val TRACE: Int = Log.DEBUG + public const val ADVICE: Int = Log.INFO + public const val WARN: Int = Log.WARN + public const val ERROR: Int = Log.ERROR + + /** + * Log a log level message tagged as React Native to the console. + * + * @param message The message to log. + */ + @JvmStatic + public fun l(message: String) { + FLog.i(ReactConstants.TAG, message) + } + + /** + * Log a trace level message tagged as React Native to the console. + * + * @param message The message to log. + */ + @JvmStatic + public fun t(message: String) { + FLog.i(ReactConstants.TAG, message) + } + + /** + * Log a warning level message tagged as React Native to the console. This warning will not be + * shown in LogBox. + * + * @param message The message to log. + */ + @JvmStatic + public fun a(message: String) { + FLog.w(ReactConstants.TAG, "(ADVICE)$message") + } + + /** + * Log a warning level message tagged as React Native to the console and display in the app. + * + * @param context The React context of the application use to display the warning. + * @param message The message to log. + */ + @JvmStatic + public fun w(context: ReactContext?, message: String) { + logInternal(context, message, WARN) + FLog.w(ReactConstants.TAG, message) + } + + /** + * Log an error level message tagged as React Native to the console and display in the app. + * + * @param context The React context of the application use to display the error. + * @param message The message to log. + */ + @JvmStatic + public fun e(context: ReactContext?, message: String) { + logInternal(context, message, ERROR) + FLog.e(ReactConstants.TAG, message) + } + + /** + * Log an error level message tagged as React Native to the console. This error will not be shown + * in LogBox. + * + * @param message The message to log. + */ + @JvmStatic + public fun e(message: String) { + FLog.e(ReactConstants.TAG, message) + } + + private fun logInternal(context: ReactContext?, message: String?, level: Int) { + if (level >= MINIMUM_LEVEL_FOR_UI) { + if (context?.hasActiveReactInstance() == true && message != null) { + context.getJSModule(RCTLog::class.java).logIfNoNativeHook(levelToString(level), message) + } + } + } + + private fun levelToString(level: Int): String = + when (level) { + LOG, + TRACE -> "log" + ADVICE, + WARN -> "warn" + ERROR -> "error" + else -> "none" + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/MaintainVisibleScrollPositionHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/MaintainVisibleScrollPositionHelper.java index 7839dcd80064a9..26c9aebc8388ad 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/MaintainVisibleScrollPositionHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/MaintainVisibleScrollPositionHelper.java @@ -34,6 +34,7 @@ @Nullsafe(Nullsafe.Mode.LOCAL) class MaintainVisibleScrollPositionHelper implements UIManagerListener { + private final ScrollViewT mScrollView; private final boolean mHorizontal; private @Nullable Config mConfig; @@ -42,6 +43,7 @@ class MaintainVisibleScrollPositionHelper currentScroll || i == contentView.getChildCount() - 1) { mFirstVisibleView = new WeakReference<>(child); Rect frame = new Rect(); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java index 7dbcb788c3ac32..8a3eedc4b2f75b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java @@ -139,6 +139,7 @@ public ReactHorizontalScrollView(Context context, @Nullable FpsListener fpsListe : ViewCompat.LAYOUT_DIRECTION_LTR); setOnHierarchyChangeListener(this); + setClipChildren(false); } public boolean getScrollEnabled() { @@ -640,13 +641,13 @@ public boolean onTouchEvent(MotionEvent ev) { } @Override - public boolean dispatchGenericPointerEvent(MotionEvent ev) { - // We do not dispatch the pointer event if its children are not supposed to receive it + public boolean dispatchGenericMotionEvent(MotionEvent ev) { + // We do not dispatch the motion event if its children are not supposed to receive it if (!PointerEvents.canChildrenBeTouchTarget(mPointerEvents)) { return false; } - return super.dispatchGenericPointerEvent(ev); + return super.dispatchGenericMotionEvent(ev); } @Override @@ -1323,6 +1324,13 @@ public void scrollTo(int x, int y) { setPendingContentOffsets(x, y); } + /** Scrolls to a new position preserving any momentum scrolling animation. */ + @Override + public void scrollToPreservingMomentum(int x, int y) { + scrollTo(x, y); + recreateFlingAnimation(x, Integer.MAX_VALUE); + } + private boolean isContentReady() { View child = getContentView(); return child != null && child.getWidth() != 0 && child.getHeight() != 0; @@ -1376,24 +1384,21 @@ public void onLayoutChange( } } - private void adjustPositionForContentChangeRTL(int left, int right, int oldLeft, int oldRight) { - // If we have any pending custon flings (e.g. from aninmated `scrollTo`, or flinging to a snap - // point), finish them, commiting the final `scrollX`. + /** + * If we are in the middle of a fling animation from the user removing their finger (OverScroller + * is in `FLING_MODE`), recreate the existing fling animation since it was calculated against + * outdated scroll offsets. + */ + private void recreateFlingAnimation(int scrollX, int maxX) { + // If we have any pending custom flings (e.g. from animated `scrollTo`, or flinging to a snap + // point), cancel them. // TODO: Can we be more graceful (like OverScroller flings)? if (getFlingAnimator().isRunning()) { - getFlingAnimator().end(); + getFlingAnimator().cancel(); } - int distanceToRightEdge = oldRight - getScrollX(); - int newWidth = right - left; - int scrollX = newWidth - distanceToRightEdge; - scrollTo(scrollX, getScrollY()); - - // If we are in the middle of a fling animation from the user removing their finger - // (OverScroller is in `FLING_MODE`), we must cancel and recreate the existing fling animation - // since it was calculated against outdated scroll offsets. if (mScroller != null && !mScroller.isFinished()) { - // Calculate the veliocity and position of the fling animation at the time of this layout + // Calculate the velocity and position of the fling animation at the time of this layout // event, which may be later than the last ScrollView tick. These values are not commited to // the underlying ScrollView, which will recalculate positions on its next tick. int scrollerXBeforeTick = mScroller.getCurrX(); @@ -1412,14 +1417,29 @@ private void adjustPositionForContentChangeRTL(int left, int right, int oldLeft, float direction = Math.signum(mScroller.getFinalX() - mScroller.getStartX()); float flingVelocityX = mScroller.getCurrVelocity() * direction; - mScroller.fling( - scrollX, getScrollY(), (int) flingVelocityX, 0, 0, newWidth - getWidth(), 0, 0); + mScroller.fling(scrollX, getScrollY(), (int) flingVelocityX, 0, 0, maxX, 0, 0); } else { scrollTo(scrollX + (mScroller.getCurrX() - scrollerXBeforeTick), getScrollY()); } } } + private void adjustPositionForContentChangeRTL(int left, int right, int oldLeft, int oldRight) { + // If we have any pending custom flings (e.g. from animated `scrollTo`, or flinging to a snap + // point), finish them, committing the final `scrollX`. + // TODO: Can we be more graceful (like OverScroller flings)? + if (getFlingAnimator().isRunning()) { + getFlingAnimator().end(); + } + + int distanceToRightEdge = oldRight - getScrollX(); + int newWidth = right - left; + int scrollX = newWidth - distanceToRightEdge; + scrollTo(scrollX, getScrollY()); + + recreateFlingAnimation(scrollX, newWidth - getWidth()); + } + @Nullable public StateWrapper getStateWrapper() { return mStateWrapper; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java index 49f7326f0a2241..a501f90f9a7434 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java @@ -131,6 +131,7 @@ public ReactScrollView(Context context, @Nullable FpsListener fpsListener) { mScroller = getOverScrollerFromParent(); setOnHierarchyChangeListener(this); setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY); + setClipChildren(false); ViewCompat.setAccessibilityDelegate(this, new ReactScrollViewAccessibilityDelegate()); } @@ -463,13 +464,13 @@ public boolean onTouchEvent(MotionEvent ev) { } @Override - public boolean dispatchGenericPointerEvent(MotionEvent ev) { - // We do not dispatch the pointer event if its children are not supposed to receive it + public boolean dispatchGenericMotionEvent(MotionEvent ev) { + // We do not dispatch the motion event if its children are not supposed to receive it if (!PointerEvents.canChildrenBeTouchTarget(mPointerEvents)) { return false; } - return super.dispatchGenericPointerEvent(ev); + return super.dispatchGenericMotionEvent(ev); } @Override @@ -1090,6 +1091,53 @@ public void scrollTo(int x, int y) { setPendingContentOffsets(x, y); } + /** + * If we are in the middle of a fling animation from the user removing their finger (OverScroller + * is in `FLING_MODE`), recreate the existing fling animation since it was calculated against + * outdated scroll offsets. + */ + private void recreateFlingAnimation(int scrollY) { + // If we have any pending custom flings (e.g. from animated `scrollTo`, or flinging to a snap + // point), cancel them. + // TODO: Can we be more graceful (like OverScroller flings)? + if (getFlingAnimator().isRunning()) { + getFlingAnimator().cancel(); + } + + if (mScroller != null && !mScroller.isFinished()) { + // Calculate the velocity and position of the fling animation at the time of this layout + // event, which may be later than the last ScrollView tick. These values are not committed to + // the underlying ScrollView, which will recalculate positions on its next tick. + int scrollerYBeforeTick = mScroller.getCurrY(); + boolean hasMoreTicks = mScroller.computeScrollOffset(); + + // Stop the existing animation at the current state of the scroller. We will then recreate + // it starting at the adjusted y offset. + mScroller.forceFinished(true); + + if (hasMoreTicks) { + // OverScroller.getCurrVelocity() returns an absolute value of the velocity a current fling + // animation (only FLING_MODE animations). We derive direction along the Y axis from the + // start and end of the, animation assuming ScrollView never fires horizontal fling + // animations. + // TODO: This does not fully handle overscroll. + float direction = Math.signum(mScroller.getFinalY() - mScroller.getStartY()); + float flingVelocityY = mScroller.getCurrVelocity() * direction; + + mScroller.fling(getScrollX(), scrollY, 0, (int) flingVelocityY, 0, 0, 0, Integer.MAX_VALUE); + } else { + scrollTo(getScrollX(), scrollY + (mScroller.getCurrX() - scrollerYBeforeTick)); + } + } + } + + /** Scrolls to a new position preserving any momentum scrolling animation. */ + @Override + public void scrollToPreservingMomentum(int x, int y) { + scrollTo(x, y); + recreateFlingAnimation(y); + } + private boolean isContentReady() { View child = getContentView(); return child != null && child.getWidth() != 0 && child.getHeight() != 0; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java index 7a9348259d473e..85ed97ec40f496 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java @@ -597,5 +597,7 @@ public interface HasScrollEventThrottle { public interface HasSmoothScroll { void reactSmoothScrollTo(int x, int y); + + void scrollToPreservingMomentum(int x, int y); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java index 25791e00679b34..202734f3795984 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java @@ -62,6 +62,8 @@ public class TextAttributeProps implements EffectiveTextAttributeProvider { public static final short TA_KEY_ROLE = 26; public static final short TA_KEY_TEXT_TRANSFORM = 27; + public static final int UNSET = -1; + private static final String PROP_SHADOW_OFFSET = "textShadowOffset"; private static final String PROP_SHADOW_OFFSET_WIDTH = "width"; private static final String PROP_SHADOW_OFFSET_HEIGHT = "height"; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/fragments/BridgeTextFragment.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/fragments/BridgeTextFragment.kt index 53d1105e6ea814..45ae17b05a8e2a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/fragments/BridgeTextFragment.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/fragments/BridgeTextFragment.kt @@ -15,8 +15,12 @@ import com.facebook.react.views.text.TextAttributeProps /** A [TextFragment] implementation backed by a a [ReadableMap] */ internal class BridgeTextFragment(private val fragment: ReadableMap) : TextFragment { override val textAttributeProps: TextAttributeProps - get() = - TextAttributeProps.fromReadableMap(ReactStylesDiffMap(fragment.getMap("textAttributes"))) + get() { + val textAttributesMap = + fragment.getMap("textAttributes") + ?: throw IllegalStateException("Missing required field `textAttributes`") + return TextAttributeProps.fromReadableMap(ReactStylesDiffMap(textAttributesMap)) + } override val string: String? get() = fragment.getString("string") diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.java index 25621c3700897a..525183053a0ef0 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.java @@ -8,6 +8,7 @@ package com.facebook.react.views.view; import android.view.View; +import androidx.annotation.Nullable; import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.uimanager.ViewGroupManager; @@ -52,6 +53,7 @@ public int getChildCount(T parent) { } @Override + @Nullable public View getChildAt(T parent, int index) { boolean removeClippedSubviews = parent.getRemoveClippedSubviews(); if (removeClippedSubviews) { @@ -68,10 +70,12 @@ public void removeViewAt(T parent, int index) { boolean removeClippedSubviews = parent.getRemoveClippedSubviews(); if (removeClippedSubviews) { View child = getChildAt(parent, index); - if (child.getParent() != null) { - parent.removeView(child); + if (child != null) { + if (child.getParent() != null) { + parent.removeView(child); + } + parent.removeViewWithSubviewClippingEnabled(child); } - parent.removeViewWithSubviewClippingEnabled(child); } else { parent.removeViewAt(index); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java index 793a0f9a584300..1af57b99847448 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java @@ -284,13 +284,13 @@ public boolean onTouchEvent(MotionEvent ev) { } @Override - public boolean dispatchGenericPointerEvent(MotionEvent ev) { - // We do not dispatch the pointer event if its children are not supposed to receive it + public boolean dispatchGenericMotionEvent(MotionEvent ev) { + // We do not dispatch the motion event if its children are not supposed to receive it if (!PointerEvents.canChildrenBeTouchTarget(mPointerEvents)) { return false; } - return super.dispatchGenericPointerEvent(ev); + return super.dispatchGenericMotionEvent(ev); } /** @@ -519,6 +519,9 @@ private void handleRemoveView(View view) { UiThreadUtil.assertOnUiThread(); if (!customDrawOrderDisabled()) { + if (indexOfChild(view) == -1) { + return; + } getDrawingOrderHelper().handleRemoveView(view); setChildrenDrawingOrderEnabled(getDrawingOrderHelper().shouldEnableCustomDrawingOrder()); } else { @@ -637,8 +640,11 @@ protected void dispatchSetPressed(boolean pressed) { return mAllChildrenCount; } - /*package*/ View getChildAtWithSubviewClippingEnabled(int index) { - return Assertions.assertNotNull(mAllChildren)[index]; + /*package*/ @Nullable + View getChildAtWithSubviewClippingEnabled(int index) { + return index >= 0 && index < mAllChildrenCount + ? Assertions.assertNotNull(mAllChildren)[index] + : null; } /*package*/ void addViewWithSubviewClippingEnabled(View child, int index) { diff --git a/packages/react-native/ReactAndroid/src/main/jni/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/CMakeLists.txt index 0fe09d67baa626..af48dbd60eee8d 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/CMakeLists.txt @@ -101,6 +101,8 @@ add_react_common_subdir(react/utils) add_react_common_subdir(react/bridging) add_react_common_subdir(react/renderer/mapbuffer) add_react_common_subdir(react/nativemodule/core) +add_react_common_subdir(react/nativemodule/featureflags) +add_react_common_subdir(react/nativemodule/microtasks) add_react_common_subdir(jserrorhandler) add_react_common_subdir(react/runtime) add_react_common_subdir(react/runtime/hermes) diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/first-party/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/.clang-tidy deleted file mode 100644 index c98fd78ff64baa..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/.clang-tidy +++ /dev/null @@ -1,5 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedGlobalRef.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedGlobalRef.h index b563d0525f9958..c0ca023e001b38 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedGlobalRef.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedGlobalRef.h @@ -62,7 +62,7 @@ class ScopedGlobalRef { * * @param globalRef the global reference to wrap. Can be NULL. */ - ScopedGlobalRef(T globalRef) : mGlobalRef(globalRef) {} + explicit ScopedGlobalRef(T globalRef) : mGlobalRef(globalRef) {} /** * Equivalent to ScopedGlobalRef(NULL) @@ -72,12 +72,12 @@ class ScopedGlobalRef { /** * Move construction is allowed. */ - ScopedGlobalRef(ScopedGlobalRef&& s) : mGlobalRef(s.release()) {} + ScopedGlobalRef(ScopedGlobalRef&& s) noexcept : mGlobalRef(s.release()) {} /** * Move assignment is allowed. */ - ScopedGlobalRef& operator=(ScopedGlobalRef&& s) { + ScopedGlobalRef& operator=(ScopedGlobalRef&& s) noexcept { reset(s.release()); return *this; } diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedLocalRef.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedLocalRef.h index 6765078bbc7948..fd49e8320337ba 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedLocalRef.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/ScopedLocalRef.h @@ -70,12 +70,13 @@ class ScopedLocalRef { /** * Move construction is allowed. */ - ScopedLocalRef(ScopedLocalRef&& s) : mEnv(s.mEnv), mLocalRef(s.release()) {} + ScopedLocalRef(ScopedLocalRef&& s) noexcept + : mEnv(s.mEnv), mLocalRef(s.release()) {} /** * Move assignment is allowed. */ - ScopedLocalRef& operator=(ScopedLocalRef&& s) { + ScopedLocalRef& operator=(ScopedLocalRef&& s) noexcept { reset(s.release()); mEnv = s.mEnv; return *this; diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNI.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNI.h index 489df201eb55d1..9b2609775a9c44 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNI.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNI.h @@ -36,7 +36,7 @@ class YGNodeEdges { BORDER = 4, }; - YGNodeEdges(YGNodeRef node) { + explicit YGNodeEdges(YGNodeRef node) { auto context = YGNodeContext{}; context.asVoidPtr = YGNodeGetContext(node); edges_ = context.edgesSet; diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp index 97fb17899c5266..82e0dc17b1350e 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp @@ -54,7 +54,9 @@ static void jni_YGConfigSetExperimentalFeatureEnabledJNI( jboolean enabled) { const YGConfigRef config = _jlong2YGConfigRef(nativePointer); YGConfigSetExperimentalFeatureEnabled( - config, static_cast(feature), enabled); + config, + static_cast(feature), + static_cast(enabled)); } static void jni_YGConfigSetUseWebDefaultsJNI( @@ -63,7 +65,7 @@ static void jni_YGConfigSetUseWebDefaultsJNI( jlong nativePointer, jboolean useWebDefaults) { const YGConfigRef config = _jlong2YGConfigRef(nativePointer); - YGConfigSetUseWebDefaults(config, useWebDefaults); + YGConfigSetUseWebDefaults(config, static_cast(useWebDefaults)); } static void jni_YGConfigSetPointScaleFactorJNI( @@ -161,7 +163,7 @@ static void jni_YGConfigSetLoggerJNI( auto context = reinterpret_cast*>(YGConfigGetContext(config)); - if (logger) { + if (logger != nullptr) { if (context == nullptr) { context = new ScopedGlobalRef(); YGConfigSetContext(config, context); @@ -225,14 +227,15 @@ static void jni_YGNodeSetIsReferenceBaselineJNI( jlong nativePointer, jboolean isReferenceBaseline) { YGNodeSetIsReferenceBaseline( - _jlong2YGNodeRef(nativePointer), isReferenceBaseline); + _jlong2YGNodeRef(nativePointer), static_cast(isReferenceBaseline)); } static jboolean jni_YGNodeIsReferenceBaselineJNI( JNIEnv* /*env*/, jobject /*obj*/, jlong nativePointer) { - return YGNodeIsReferenceBaseline(_jlong2YGNodeRef(nativePointer)); + return static_cast( + YGNodeIsReferenceBaseline(_jlong2YGNodeRef(nativePointer))); } static void jni_YGNodeRemoveAllChildrenJNI( @@ -340,7 +343,7 @@ static void jni_YGNodeCalculateLayoutJNI( try { PtrJNodeMapVanilla* layoutContext = nullptr; auto map = PtrJNodeMapVanilla{}; - if (nativePointers) { + if (nativePointers != nullptr) { map = PtrJNodeMapVanilla{nativePointers, javaNodes}; layoutContext = ↦ } @@ -356,7 +359,7 @@ static void jni_YGNodeCalculateLayoutJNI( YGTransferLayoutOutputsRecursive(env, obj, root); } catch (const YogaJniException& jniException) { ScopedLocalRef throwable = jniException.getThrowable(); - if (throwable.get()) { + if (throwable.get() != nullptr) { env->Throw(throwable.get()); } } catch (const std::logic_error& ex) { @@ -626,8 +629,8 @@ static YGSize YGJNIMeasureFunc( uint32_t wBits = 0xFFFFFFFF & (measureResult >> 32); uint32_t hBits = 0xFFFFFFFF & measureResult; - float measuredWidth = std::bit_cast(wBits); - float measuredHeight = std::bit_cast(hBits); + auto measuredWidth = std::bit_cast(wBits); + auto measuredHeight = std::bit_cast(hBits); return YGSize{measuredWidth, measuredHeight}; } else { @@ -645,7 +648,7 @@ static void jni_YGNodeSetHasMeasureFuncJNI( jboolean hasMeasureFunc) { YGNodeSetMeasureFunc( _jlong2YGNodeRef(nativePointer), - hasMeasureFunc ? YGJNIMeasureFunc : nullptr); + static_cast(hasMeasureFunc) ? YGJNIMeasureFunc : nullptr); } static float YGJNIBaselineFunc(YGNodeConstRef node, float width, float height) { @@ -669,7 +672,7 @@ static void jni_YGNodeSetHasBaselineFuncJNI( jboolean hasBaselineFunc) { YGNodeSetBaselineFunc( _jlong2YGNodeRef(nativePointer), - hasBaselineFunc ? YGJNIBaselineFunc : nullptr); + static_cast(hasBaselineFunc) ? YGJNIBaselineFunc : nullptr); } static void jni_YGNodeSetAlwaysFormsContainingBlockJNI( @@ -678,7 +681,8 @@ static void jni_YGNodeSetAlwaysFormsContainingBlockJNI( jlong nativePointer, jboolean alwaysFormsContainingBlock) { YGNodeSetAlwaysFormsContainingBlock( - _jlong2YGNodeRef(nativePointer), alwaysFormsContainingBlock); + _jlong2YGNodeRef(nativePointer), + static_cast(alwaysFormsContainingBlock)); } static jlong diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.cpp index a30b8a6a8ab610..e8c6ca923f3769 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.cpp @@ -25,7 +25,7 @@ YogaJniException::YogaJniException(jthrowable throwable) { throwable_ = newGlobalRef(getCurrentEnv(), throwable); } -YogaJniException::YogaJniException(YogaJniException&& rhs) +YogaJniException::YogaJniException(YogaJniException&& rhs) noexcept : throwable_(std::move(rhs.throwable_)) {} YogaJniException::YogaJniException(const YogaJniException& rhs) { diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.h index 1d2cc956113b51..8c53d4125af995 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YogaJniException.h @@ -22,9 +22,9 @@ class YogaJniException : public std::exception { explicit YogaJniException(jthrowable throwable); - YogaJniException(YogaJniException&& rhs); + YogaJniException(YogaJniException&& rhs) noexcept; - YogaJniException(const YogaJniException& other); + YogaJniException(const YogaJniException& rhs); ScopedLocalRef getThrowable() const noexcept; diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/common.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/common.cpp index e2dc0df22c35d6..d634b0af164a71 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/common.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/common.cpp @@ -16,7 +16,7 @@ void registerNatives( size_t numMethods) { jclass clazz = env->FindClass(className); - assertNoPendingJniExceptionIf(env, !clazz); + assertNoPendingJniExceptionIf(env, clazz == nullptr); auto result = env->RegisterNatives(clazz, methods, static_cast(numMethods)); @@ -31,7 +31,7 @@ jmethodID getStaticMethodId( const char* methodDescriptor) { jmethodID methodId = env->GetStaticMethodID(clazz, methodName, methodDescriptor); - assertNoPendingJniExceptionIf(env, !methodId); + assertNoPendingJniExceptionIf(env, methodId == nullptr); return methodId; } @@ -41,7 +41,7 @@ jmethodID getMethodId( const char* methodName, const char* methodDescriptor) { jmethodID methodId = env->GetMethodID(clazz, methodName, methodDescriptor); - assertNoPendingJniExceptionIf(env, !methodId); + assertNoPendingJniExceptionIf(env, methodId == nullptr); return methodId; } @@ -51,7 +51,7 @@ jfieldID getFieldId( const char* fieldName, const char* fieldSignature) { jfieldID fieldId = env->GetFieldID(clazz, fieldName, fieldSignature); - assertNoPendingJniExceptionIf(env, !fieldId); + assertNoPendingJniExceptionIf(env, fieldId == nullptr); return fieldId; } @@ -82,14 +82,14 @@ callStaticObjectMethod(JNIEnv* env, jclass clazz, jmethodID methodId, ...) { va_start(args, methodId); jobject result = env->CallStaticObjectMethodV(clazz, methodId, args); va_end(args); - assertNoPendingJniExceptionIf(env, !result); + assertNoPendingJniExceptionIf(env, result == nullptr); return make_local_ref(env, result); } ScopedGlobalRef newGlobalRef(JNIEnv* env, jobject obj) { jobject result = env->NewGlobalRef(obj); - if (!result) { + if (result == nullptr) { logErrorMessageAndDie("Could not obtain global reference from object"); } @@ -97,9 +97,9 @@ ScopedGlobalRef newGlobalRef(JNIEnv* env, jobject obj) { } ScopedGlobalRef newGlobalRef(JNIEnv* env, jthrowable obj) { - jthrowable result = static_cast(env->NewGlobalRef(obj)); + auto result = static_cast(env->NewGlobalRef(obj)); - if (!result) { + if (result == nullptr) { logErrorMessageAndDie("Could not obtain global reference from object"); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/corefunctions.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/corefunctions.cpp index f094357cf2bd20..6fcbf78064d1ac 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/corefunctions.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/corefunctions.cpp @@ -12,9 +12,9 @@ namespace facebook::yoga::vanillajni { namespace { -JavaVM* globalVm = NULL; +JavaVM* globalVm = nullptr; struct JavaVMInitializer { - JavaVMInitializer(JavaVM* vm) { + explicit JavaVMInitializer(JavaVM* vm) { if (!vm) { logErrorMessageAndDie( "You cannot pass a NULL JavaVM to ensureInitialized"); @@ -27,7 +27,7 @@ struct JavaVMInitializer { jint ensureInitialized(JNIEnv** env, JavaVM* vm) { static JavaVMInitializer init(vm); - if (!env) { + if (env == nullptr) { logErrorMessageAndDie( "Need to pass a valid JNIEnv pointer to vanillajni initialization " "routine"); @@ -43,7 +43,7 @@ jint ensureInitialized(JNIEnv** env, JavaVM* vm) { // TODO why we need JNIEXPORT for getCurrentEnv ? JNIEXPORT JNIEnv* getCurrentEnv() { - JNIEnv* env; + JNIEnv* env = nullptr; jint ret = globalVm->GetEnv((void**)&env, JNI_VERSION_1_6); if (ret != JNI_OK) { logErrorMessageAndDie( @@ -68,7 +68,7 @@ void assertNoPendingJniException(JNIEnv* env) { } auto throwable = env->ExceptionOccurred(); - if (!throwable) { + if (throwable == nullptr) { logErrorMessageAndDie("Unable to get pending JNI exception."); } env->ExceptionClear(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/yogajni.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/yogajni.cpp index cab45a13b5017f..5bc99431371715 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/yogajni.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/yogajni.cpp @@ -10,8 +10,8 @@ using namespace facebook::yoga; -jint JNI_OnLoad(JavaVM* vm, void*) { - JNIEnv* env; +jint JNI_OnLoad(JavaVM* vm, void* /*unused*/) { + JNIEnv* env = nullptr; jint ret = vanillajni::ensureInitialized(&env, vm); YGJNIVanilla::registerNatives(env); return ret; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp index fdb2f051621fd2..fd8e579865f73b 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp @@ -67,8 +67,6 @@ CoreComponentsRegistry::sharedProviderRegistry() { AndroidDrawerLayoutComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< DebuggingOverlayComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - AndroidPopupMenuComponentDescriptor>()); return providerRegistry; }(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.cpp index 9d37fa1f08cc1a..e3908c880dff71 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.cpp @@ -23,7 +23,6 @@ void EventEmitterWrapper::dispatchEvent( eventEmitter->dispatchEvent( eventName, payload ? payload->consume() : folly::dynamic::object(), - EventPriority::AsynchronousBatched, static_cast(category)); } } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp index 15061428a2a2df..4add6436bbd4c9 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<<393c6cf93399cfe0b0533927877531d5>> */ /** @@ -45,45 +45,45 @@ class ReactNativeFeatureFlagsProviderHolder return method(javaProvider_); } - bool enableBackgroundExecutor() override { + bool batchRenderingUpdatesInEventLoop() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableBackgroundExecutor"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("batchRenderingUpdatesInEventLoop"); return method(javaProvider_); } - bool useModernRuntimeScheduler() override { + bool enableBackgroundExecutor() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("useModernRuntimeScheduler"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableBackgroundExecutor"); return method(javaProvider_); } - bool enableMicrotasks() override { + bool enableCustomDrawOrderFabric() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableMicrotasks"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableCustomDrawOrderFabric"); return method(javaProvider_); } - bool batchRenderingUpdatesInEventLoop() override { + bool enableFixForClippedSubviewsCrash() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("batchRenderingUpdatesInEventLoop"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableFixForClippedSubviewsCrash"); return method(javaProvider_); } - bool enableSpannableBuildingUnification() override { + bool enableMicrotasks() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableSpannableBuildingUnification"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableMicrotasks"); return method(javaProvider_); } - bool enableCustomDrawOrderFabric() override { + bool enableMountHooksAndroid() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableCustomDrawOrderFabric"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableMountHooksAndroid"); return method(javaProvider_); } - bool enableFixForClippedSubviewsCrash() override { + bool enableSpannableBuildingUnification() override { static const auto method = - getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableFixForClippedSubviewsCrash"); + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enableSpannableBuildingUnification"); return method(javaProvider_); } @@ -99,6 +99,12 @@ class ReactNativeFeatureFlagsProviderHolder return method(javaProvider_); } + bool useModernRuntimeScheduler() override { + static const auto method = + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("useModernRuntimeScheduler"); + return method(javaProvider_); + } + private: jni::global_ref javaProvider_; }; @@ -108,39 +114,39 @@ bool JReactNativeFeatureFlagsCxxInterop::commonTestFlag( return ReactNativeFeatureFlags::commonTestFlag(); } -bool JReactNativeFeatureFlagsCxxInterop::enableBackgroundExecutor( +bool JReactNativeFeatureFlagsCxxInterop::batchRenderingUpdatesInEventLoop( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::enableBackgroundExecutor(); + return ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop(); } -bool JReactNativeFeatureFlagsCxxInterop::useModernRuntimeScheduler( +bool JReactNativeFeatureFlagsCxxInterop::enableBackgroundExecutor( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::useModernRuntimeScheduler(); + return ReactNativeFeatureFlags::enableBackgroundExecutor(); } -bool JReactNativeFeatureFlagsCxxInterop::enableMicrotasks( +bool JReactNativeFeatureFlagsCxxInterop::enableCustomDrawOrderFabric( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::enableMicrotasks(); + return ReactNativeFeatureFlags::enableCustomDrawOrderFabric(); } -bool JReactNativeFeatureFlagsCxxInterop::batchRenderingUpdatesInEventLoop( +bool JReactNativeFeatureFlagsCxxInterop::enableFixForClippedSubviewsCrash( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop(); + return ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash(); } -bool JReactNativeFeatureFlagsCxxInterop::enableSpannableBuildingUnification( +bool JReactNativeFeatureFlagsCxxInterop::enableMicrotasks( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::enableSpannableBuildingUnification(); + return ReactNativeFeatureFlags::enableMicrotasks(); } -bool JReactNativeFeatureFlagsCxxInterop::enableCustomDrawOrderFabric( +bool JReactNativeFeatureFlagsCxxInterop::enableMountHooksAndroid( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::enableCustomDrawOrderFabric(); + return ReactNativeFeatureFlags::enableMountHooksAndroid(); } -bool JReactNativeFeatureFlagsCxxInterop::enableFixForClippedSubviewsCrash( +bool JReactNativeFeatureFlagsCxxInterop::enableSpannableBuildingUnification( facebook::jni::alias_ref /*unused*/) { - return ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash(); + return ReactNativeFeatureFlags::enableSpannableBuildingUnification(); } bool JReactNativeFeatureFlagsCxxInterop::inspectorEnableCxxInspectorPackagerConnection( @@ -153,6 +159,11 @@ bool JReactNativeFeatureFlagsCxxInterop::inspectorEnableModernCDPRegistry( return ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry(); } +bool JReactNativeFeatureFlagsCxxInterop::useModernRuntimeScheduler( + facebook::jni::alias_ref /*unused*/) { + return ReactNativeFeatureFlags::useModernRuntimeScheduler(); +} + void JReactNativeFeatureFlagsCxxInterop::override( facebook::jni::alias_ref /*unused*/, jni::alias_ref provider) { @@ -173,33 +184,36 @@ void JReactNativeFeatureFlagsCxxInterop::registerNatives() { makeNativeMethod( "commonTestFlag", JReactNativeFeatureFlagsCxxInterop::commonTestFlag), + makeNativeMethod( + "batchRenderingUpdatesInEventLoop", + JReactNativeFeatureFlagsCxxInterop::batchRenderingUpdatesInEventLoop), makeNativeMethod( "enableBackgroundExecutor", JReactNativeFeatureFlagsCxxInterop::enableBackgroundExecutor), makeNativeMethod( - "useModernRuntimeScheduler", - JReactNativeFeatureFlagsCxxInterop::useModernRuntimeScheduler), + "enableCustomDrawOrderFabric", + JReactNativeFeatureFlagsCxxInterop::enableCustomDrawOrderFabric), + makeNativeMethod( + "enableFixForClippedSubviewsCrash", + JReactNativeFeatureFlagsCxxInterop::enableFixForClippedSubviewsCrash), makeNativeMethod( "enableMicrotasks", JReactNativeFeatureFlagsCxxInterop::enableMicrotasks), makeNativeMethod( - "batchRenderingUpdatesInEventLoop", - JReactNativeFeatureFlagsCxxInterop::batchRenderingUpdatesInEventLoop), + "enableMountHooksAndroid", + JReactNativeFeatureFlagsCxxInterop::enableMountHooksAndroid), makeNativeMethod( "enableSpannableBuildingUnification", JReactNativeFeatureFlagsCxxInterop::enableSpannableBuildingUnification), - makeNativeMethod( - "enableCustomDrawOrderFabric", - JReactNativeFeatureFlagsCxxInterop::enableCustomDrawOrderFabric), - makeNativeMethod( - "enableFixForClippedSubviewsCrash", - JReactNativeFeatureFlagsCxxInterop::enableFixForClippedSubviewsCrash), makeNativeMethod( "inspectorEnableCxxInspectorPackagerConnection", JReactNativeFeatureFlagsCxxInterop::inspectorEnableCxxInspectorPackagerConnection), makeNativeMethod( "inspectorEnableModernCDPRegistry", JReactNativeFeatureFlagsCxxInterop::inspectorEnableModernCDPRegistry), + makeNativeMethod( + "useModernRuntimeScheduler", + JReactNativeFeatureFlagsCxxInterop::useModernRuntimeScheduler), }); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h index ff7881e09e417c..d710f2c4052299 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> */ /** @@ -33,25 +33,25 @@ class JReactNativeFeatureFlagsCxxInterop static bool commonTestFlag( facebook::jni::alias_ref); - static bool enableBackgroundExecutor( + static bool batchRenderingUpdatesInEventLoop( facebook::jni::alias_ref); - static bool useModernRuntimeScheduler( + static bool enableBackgroundExecutor( facebook::jni::alias_ref); - static bool enableMicrotasks( + static bool enableCustomDrawOrderFabric( facebook::jni::alias_ref); - static bool batchRenderingUpdatesInEventLoop( + static bool enableFixForClippedSubviewsCrash( facebook::jni::alias_ref); - static bool enableSpannableBuildingUnification( + static bool enableMicrotasks( facebook::jni::alias_ref); - static bool enableCustomDrawOrderFabric( + static bool enableMountHooksAndroid( facebook::jni::alias_ref); - static bool enableFixForClippedSubviewsCrash( + static bool enableSpannableBuildingUnification( facebook::jni::alias_ref); static bool inspectorEnableCxxInspectorPackagerConnection( @@ -60,6 +60,9 @@ class JReactNativeFeatureFlagsCxxInterop static bool inspectorEnableModernCDPRegistry( facebook::jni::alias_ref); + static bool useModernRuntimeScheduler( + facebook::jni::alias_ref); + static void override( facebook::jni::alias_ref, jni::alias_ref provider); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/.clang-tidy deleted file mode 100644 index 8edbbc799e94cf..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -InheritParentConfig: true -Checks: '> -clang-diagnostic-*, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/jni/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.cpp new file mode 100644 index 00000000000000..09c55714791008 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.cpp @@ -0,0 +1,18 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "JExecutor.h" + +namespace facebook::react { + +void JExecutor::execute(jni::alias_ref runnable) { + static auto executeMethod = + javaClassStatic()->getMethod("execute"); + executeMethod(self(), runnable.get()); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventPriority.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.h similarity index 50% rename from packages/react-native/ReactCommon/react/renderer/core/EventPriority.h rename to packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.h index bc1e9aa9b49ebc..21c2a39ada9a3b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventPriority.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JExecutor.h @@ -7,18 +7,15 @@ #pragma once +#include +#include + namespace facebook::react { -enum class EventPriority { - SynchronousUnbatched, - SynchronousBatched, - AsynchronousUnbatched, - AsynchronousBatched, +struct JExecutor : public jni::JavaClass { + constexpr static auto kJavaDescriptor = "Ljava/util/concurrent/Executor;"; - Sync = SynchronousUnbatched, - Work = SynchronousBatched, - Interactive = AsynchronousUnbatched, - Deferred = AsynchronousBatched + void execute(jni::alias_ref runnable); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp index df01e447a42e5d..e945c01e267944 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h index 3926fa906deaaf..716e58b0a7b61e 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h @@ -42,10 +42,6 @@ class JMessageQueueThread : public MessageQueueThread { */ void quitSynchronous() override; - JavaMessageQueueThread::javaobject jobj() { - return m_jobj.get(); - } - private: jni::global_ref m_jobj; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/.clang-tidy deleted file mode 100644 index 796a6244e78a2c..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/.clang-tidy +++ /dev/null @@ -1,3 +0,0 @@ ---- -InheritParentConfig: true -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CMakeLists.txt index 3bbdeebb05051d..d541aa2305c868 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CMakeLists.txt @@ -21,4 +21,6 @@ target_link_libraries(react_newarchdefaults react_nativemodule_core react_codegen_rncore react_cxxreactpackage + react_nativemodule_featureflags + react_nativemodule_microtasks jsi) diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.cpp index e202896abc7bad..7a291d71821556 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.cpp @@ -9,6 +9,8 @@ #include +#include +#include #include namespace facebook::react { @@ -67,8 +69,20 @@ std::shared_ptr DefaultTurboModuleManagerDelegate::getTurboModule( auto moduleProvider = DefaultTurboModuleManagerDelegate::cxxModuleProvider; if (moduleProvider) { - return moduleProvider(name, jsInvoker); + auto module = moduleProvider(name, jsInvoker); + if (module) { + return module; + } + } + + if (name == NativeReactNativeFeatureFlags::kModuleName) { + return std::make_shared(jsInvoker); } + + if (name == NativeMicrotasks::kModuleName) { + return std::make_shared(jsInvoker); + } + return nullptr; } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/.clang-tidy deleted file mode 100644 index 8edbbc799e94cf..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -InheritParentConfig: true -Checks: '> -clang-diagnostic-*, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/.clang-tidy deleted file mode 100644 index 47a7201d28913d..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/.clang-tidy +++ /dev/null @@ -1,20 +0,0 @@ ---- -InheritParentConfig: true -Checks: ' --cert-err60-cpp, --cppcoreguidelines-pro-bounds-pointer-arithmetic, --cppcoreguidelines-special-member-functions, --cppcoreguidelines-pro-type-const-cast, --fuchsia-default-arguments-calls, --fuchsia-multiple-inheritance, --google-readability-casting, --google-runtime-int, --google-runtime-references, --hicpp-special-member-functions, --llvm-header-guard, --misc-non-private-member-variables-in-classes, --misc-unused-parameters, --modernize-use-trailing-return-type, --performance-unnecessary-value-param, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/.clang-tidy b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/.clang-tidy deleted file mode 100644 index 47a7201d28913d..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/.clang-tidy +++ /dev/null @@ -1,20 +0,0 @@ ---- -InheritParentConfig: true -Checks: ' --cert-err60-cpp, --cppcoreguidelines-pro-bounds-pointer-arithmetic, --cppcoreguidelines-special-member-functions, --cppcoreguidelines-pro-type-const-cast, --fuchsia-default-arguments-calls, --fuchsia-multiple-inheritance, --google-readability-casting, --google-runtime-int, --google-runtime-references, --hicpp-special-member-functions, --llvm-header-guard, --misc-non-private-member-variables-in-classes, --misc-unused-parameters, --modernize-use-trailing-return-type, --performance-unnecessary-value-param, -' -... diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.cpp new file mode 100644 index 00000000000000..eb47f4af4a327e --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "JReactHostInspectorTarget.h" +#include +#include + +using namespace facebook::jni; +using namespace facebook::react::jsinspector_modern; + +namespace facebook::react { +JReactHostInspectorTarget::JReactHostInspectorTarget( + alias_ref reactHostImpl, + alias_ref executor) + : javaReactHostImpl_(make_global(reactHostImpl)), + javaExecutor_(make_global(executor)) { + auto& inspectorFlags = InspectorFlags::getInstance(); + if (inspectorFlags.getEnableModernCDPRegistry()) { + inspectorTarget_ = HostTarget::create( + *this, + [javaExecutor = + javaExecutor_](std::function&& callback) mutable { + auto jrunnable = + JNativeRunnable::newObjectCxxArgs(std::move(callback)); + javaExecutor->execute(jrunnable); + }); + + inspectorPageId_ = getInspectorInstance().addPage( + "React Native Bridgeless (Experimental)", + /* vm */ "", + [inspectorTargetWeak = std::weak_ptr(inspectorTarget_)]( + std::unique_ptr remote) + -> std::unique_ptr { + if (auto inspectorTarget = inspectorTargetWeak.lock()) { + return inspectorTarget->connect( + std::move(remote), + { + .integrationName = "Android Bridgeless (ReactHostImpl)", + }); + } + // Reject the connection. + return nullptr; + }, + {.nativePageReloads = true}); + } +} + +JReactHostInspectorTarget::~JReactHostInspectorTarget() { + if (inspectorPageId_.has_value()) { + getInspectorInstance().removePage(*inspectorPageId_); + } +} + +local_ref +JReactHostInspectorTarget::initHybrid( + alias_ref self, + jni::alias_ref reactHostImpl, + jni::alias_ref executor) { + return makeCxxInstance(reactHostImpl, executor); +} + +void JReactHostInspectorTarget::registerNatives() { + registerHybrid({ + makeNativeMethod("initHybrid", JReactHostInspectorTarget::initHybrid), + }); +} + +void JReactHostInspectorTarget::onReload(const PageReloadRequest& request) { + javaReactHostImpl_->reload("CDP Page.reload"); +} + +HostTarget* JReactHostInspectorTarget::getInspectorTarget() { + return inspectorTarget_ ? inspectorTarget_.get() : nullptr; +} +} // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h new file mode 100644 index 00000000000000..d4fc38364d1243 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +namespace facebook::react { + +struct JTaskInterface : public jni::JavaClass { + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/interfaces/TaskInterface;"; +}; + +struct JReactHostImpl : public jni::JavaClass { + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/runtime/ReactHostImpl;"; + + jni::local_ref reload(const std::string& reason) { + static auto method = + javaClassStatic()->getMethod( + "reload"); + return method(self(), reason); + } +}; + +class JReactHostInspectorTarget + : public jni::HybridClass, + public jsinspector_modern::HostTargetDelegate { + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/runtime/ReactHostInspectorTarget;"; + + ~JReactHostInspectorTarget() override; + + static jni::local_ref initHybrid( + jni::alias_ref jThis, + jni::alias_ref reactHost, + jni::alias_ref); + + static void registerNatives(); + + void onReload(const PageReloadRequest& request) override; + + jsinspector_modern::HostTarget* getInspectorTarget(); + + private: + JReactHostInspectorTarget( + jni::alias_ref reactHostImpl, + jni::alias_ref executor); + jni::global_ref javaReactHostImpl_; + jni::global_ref javaExecutor_; + + std::shared_ptr inspectorTarget_; + std::optional inspectorPageId_; + + friend HybridBase; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp index ce3bc7b613e00d..a74cc54fc45668 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp @@ -36,7 +36,9 @@ JReactInstance::JReactInstance( jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, - bool isProfiling) noexcept { + bool isProfiling, + jni::alias_ref + jReactHostInspectorTarget) noexcept { // TODO(janzer): Lazily create runtime auto sharedJSMessageQueueThread = std::make_shared(jsMessageQueueThread); @@ -64,7 +66,10 @@ JReactInstance::JReactInstance( jsRuntimeFactory->cthis()->createJSRuntime(sharedJSMessageQueueThread), sharedJSMessageQueueThread, timerManager, - std::move(jsErrorHandlingFunc)); + std::move(jsErrorHandlingFunc), + jReactHostInspectorTarget + ? jReactHostInspectorTarget->cthis()->getInspectorTarget() + : nullptr); auto bufferedRuntimeExecutor = instance_->getBufferedRuntimeExecutor(); timerManager->setRuntimeExecutor(bufferedRuntimeExecutor); @@ -115,7 +120,9 @@ jni::local_ref JReactInstance::initHybrid( jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, - bool isProfiling) { + bool isProfiling, + jni::alias_ref + jReactHostInspectorTarget) { return makeCxxInstance( jsRuntimeFactory, jsMessageQueueThread, @@ -124,7 +131,8 @@ jni::local_ref JReactInstance::initHybrid( jsTimerExecutor, jReactExceptionManager, jBindingsInstaller, - isProfiling); + isProfiling, + jReactHostInspectorTarget); } void JReactInstance::loadJSBundleFromAssets( @@ -205,6 +213,10 @@ jlong JReactInstance::getJavaScriptContext() { return (jlong)(intptr_t)instance_->getJavaScriptContext(); } +void JReactInstance::unregisterFromInspector() { + instance_->unregisterFromInspector(); +} + void JReactInstance::registerNatives() { registerHybrid({ makeNativeMethod("initHybrid", JReactInstance::initHybrid), @@ -229,14 +241,14 @@ void JReactInstance::registerNatives() { JReactInstance::getBufferedRuntimeExecutor), makeNativeMethod( "getRuntimeScheduler", JReactInstance::getRuntimeScheduler), - makeNativeMethod( "registerSegmentNative", JReactInstance::registerSegment), makeNativeMethod( "handleMemoryPressureJs", JReactInstance::handleMemoryPressureJs), makeNativeMethod( "getJavaScriptContext", JReactInstance::getJavaScriptContext), + makeNativeMethod( + "unregisterFromInspector", JReactInstance::unregisterFromInspector), }); } - } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h index 6a28ea50c737e1..d6552a8a97895f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h @@ -27,6 +27,7 @@ #include "JJSTimerExecutor.h" #include "JJavaTimerManager.h" #include "JReactExceptionManager.h" +#include "JReactHostInspectorTarget.h" namespace facebook::react { @@ -45,7 +46,9 @@ class JReactInstance : public jni::HybridClass { jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, - bool isProfiling); + bool isProfiling, + jni::alias_ref + jReactHostInspectorTarget); /* * Instantiates and returns an instance of `JSTimerExecutor`. @@ -78,6 +81,8 @@ class JReactInstance : public jni::HybridClass { void handleMemoryPressureJs(jint level); + void unregisterFromInspector(); + private: friend HybridBase; @@ -90,7 +95,9 @@ class JReactInstance : public jni::HybridClass { jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, - bool isProfiling) noexcept; + bool isProfiling, + jni::alias_ref + jReactHostInspectorTarget) noexcept; jni::alias_ref getJSCallInvokerHolder(); jni::alias_ref diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/OnLoad.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/OnLoad.cpp index fa091d0f312d8a..f4dcbfa9a721ee 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/OnLoad.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/OnLoad.cpp @@ -9,6 +9,7 @@ #include #include "JJSTimerExecutor.h" +#include "JReactHostInspectorTarget.h" #include "JReactInstance.h" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* /*unused*/) { @@ -16,5 +17,6 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* /*unused*/) { facebook::react::JReactMarker::setLogPerfMarkerIfNeeded(); facebook::react::JReactInstance::registerNatives(); facebook::react::JJSTimerExecutor::registerNatives(); + facebook::react::JReactHostInspectorTarget::registerNatives(); }); } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityDelegateTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityDelegateTest.kt index f0eb097b697008..44d33df9c4545e 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityDelegateTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityDelegateTest.kt @@ -28,9 +28,7 @@ class ReactActivityDelegateTest { get() = composeLaunchOptions() } - assertNotNull(delegate.inspectLaunchOptions) - // False because oncurrentRoot is hardcoded to true for Fabric inside renderApplication - assertFalse(delegate.inspectLaunchOptions!!.containsKey("concurrentRoot")) + assertNull(delegate.inspectLaunchOptions) } @Test @@ -60,9 +58,7 @@ class ReactActivityDelegateTest { } assertNotNull(delegate.inspectLaunchOptions) - // False because oncurrentRoot is hardcoded to true for Fabric inside renderApplication - assertFalse(delegate.inspectLaunchOptions!!.containsKey("concurrentRoot")) - assertTrue(delegate.inspectLaunchOptions!!.containsKey("test-property")) - assertEquals("test-value", delegate.inspectLaunchOptions!!.getString("test-property")) + assertTrue(delegate.inspectLaunchOptions?.containsKey("test-property") ?: false) + assertEquals("test-value", delegate.inspectLaunchOptions?.getString("test-property")) } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.kt index 85ae9a6d476476..49e9709df4a1e4 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.kt @@ -7,7 +7,7 @@ package com.facebook.react.bridge -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule +import com.facebook.react.turbomodule.core.interfaces.TurboModule import com.facebook.testutils.shadows.ShadowSoLoader import org.junit.Before import org.junit.Test diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.kt index 46fbb1f67668d5..33f749862dd192 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.kt @@ -15,15 +15,23 @@ class JavaOnlyArrayTest { @Test fun testGetType() { val values = - JavaOnlyArray.of(1, 2f, 3.0, "4", false, JavaOnlyArray.of(), JavaOnlyMap.of(), null) + JavaOnlyArray.of(1, 2f, 3.0, 4L, "5", false, JavaOnlyArray.of(), JavaOnlyMap.of(), null) assertThat(values.getType(0)).isEqualTo(ReadableType.Number) assertThat(values.getType(1)).isEqualTo(ReadableType.Number) assertThat(values.getType(2)).isEqualTo(ReadableType.Number) - assertThat(values.getType(3)).isEqualTo(ReadableType.String) - assertThat(values.getType(4)).isEqualTo(ReadableType.Boolean) - assertThat(values.getType(5)).isEqualTo(ReadableType.Array) - assertThat(values.getType(6)).isEqualTo(ReadableType.Map) - assertThat(values.getType(7)).isEqualTo(ReadableType.Null) + assertThat(values.getType(3)).isEqualTo(ReadableType.Number) + assertThat(values.getType(4)).isEqualTo(ReadableType.String) + assertThat(values.getType(5)).isEqualTo(ReadableType.Boolean) + assertThat(values.getType(6)).isEqualTo(ReadableType.Array) + assertThat(values.getType(7)).isEqualTo(ReadableType.Map) + assertThat(values.getType(8)).isEqualTo(ReadableType.Null) + } + + @Test + fun testLongValueNotTruncated() { + val values = JavaOnlyArray.of(1125899906842623L) + + assertThat(values.getLong(0)).isEqualTo(1125899906842623L) } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyMapTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyMapTest.kt new file mode 100644 index 00000000000000..4596b712bbe7de --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyMapTest.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.bridge + +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test + +/** Tests for [JavaOnlyMap] */ +class JavaOnlyMapTest { + @Test + fun testGetType() { + val values = + JavaOnlyMap.of( + "int", + 1, + "float", + 2f, + "double", + 3.0, + "long", + 4L, + "string", + "5", + "boolean", + false, + "array", + JavaOnlyArray.of(), + "map", + JavaOnlyMap.of(), + "null", + null) + + assertThat(values.getType("int")).isEqualTo(ReadableType.Number) + assertThat(values.getType("float")).isEqualTo(ReadableType.Number) + assertThat(values.getType("double")).isEqualTo(ReadableType.Number) + assertThat(values.getType("long")).isEqualTo(ReadableType.Number) + assertThat(values.getType("string")).isEqualTo(ReadableType.String) + assertThat(values.getType("boolean")).isEqualTo(ReadableType.Boolean) + assertThat(values.getType("array")).isEqualTo(ReadableType.Array) + assertThat(values.getType("map")).isEqualTo(ReadableType.Map) + assertThat(values.getType("null")).isEqualTo(ReadableType.Null) + } + + @Test + fun testLongValueNotTruncated() { + val values = JavaOnlyMap.of("long", 1125899906842623L) + + assertThat(values.getLong("long")).isEqualTo(1125899906842623L) + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/FakeRCTEventEmitter.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/FakeRCTEventEmitter.kt index dd8b7ac69895d2..46f96d0b6bfc91 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/FakeRCTEventEmitter.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/FakeRCTEventEmitter.kt @@ -11,8 +11,10 @@ package com.facebook.react.bridge.interop import com.facebook.react.bridge.WritableArray import com.facebook.react.bridge.WritableMap +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.uimanager.events.RCTEventEmitter +@UnstableReactNativeAPI class FakeRCTEventEmitter : RCTEventEmitter { override fun receiveEvent(targetReactTag: Int, eventName: String, event: WritableMap?) = Unit diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/InteropModuleRegistryTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/InteropModuleRegistryTest.kt index 3d9c188b2507bc..e2fc44363dff99 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/InteropModuleRegistryTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/interop/InteropModuleRegistryTest.kt @@ -10,6 +10,7 @@ package com.facebook.react.bridge.interop +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.config.ReactFeatureFlags import com.facebook.react.modules.core.JSTimers import com.facebook.react.uimanager.events.RCTEventEmitter @@ -19,6 +20,7 @@ import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +@OptIn(UnstableReactNativeAPI::class) class InteropModuleRegistryTest { lateinit var underTest: InteropModuleRegistry diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListenerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListenerTest.kt index d875aa83ef8699..e61021c5b2c169 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListenerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/internal/interop/InteropUiBlockListenerTest.kt @@ -7,10 +7,12 @@ package com.facebook.react.fabric.internal.interop +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.testutils.fakes.FakeUIManager import org.junit.Assert.assertEquals import org.junit.Test +@OptIn(UnstableReactNativeAPI::class) class InteropUiBlockListenerTest { @Test diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/model/ReactModuleInfoTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/model/ReactModuleInfoTest.kt new file mode 100644 index 00000000000000..d3c072a6e5d10b --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/model/ReactModuleInfoTest.kt @@ -0,0 +1,51 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.modules.model + +import com.facebook.react.module.model.ReactModuleInfo +import com.facebook.react.turbomodule.core.interfaces.TurboModule +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReactModuleInfoTest { + + @Test + fun testCreateReactModuleInfo() { + val reactModuleInfo = + ReactModuleInfo( + /* name = */ "name", + /* className = */ "class", + /* canOverrideExistingModule = */ false, + /* needsEagerInit = */ false, + /* isCxxModule = */ false, + /* isTurboModule = */ false) + assertEquals("name", reactModuleInfo.name()) + assertFalse(reactModuleInfo.canOverrideExistingModule()) + assertFalse(reactModuleInfo.needsEagerInit()) + assertFalse(reactModuleInfo.isCxxModule) + assertFalse(reactModuleInfo.isTurboModule) + } + + @Test + fun classIsTurboModule_withRandomClass() { + assertFalse(ReactModuleInfo.classIsTurboModule(String::class.java)) + } + + @Test + fun classIsTurboModule_withTurboModule() { + assertTrue(ReactModuleInfo.classIsTurboModule(TestTurboModule::class.java)) + } + + inner class TestTurboModule : TurboModule { + override fun initialize() = Unit + + override fun invalidate() = Unit + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.kt index 116f1c122872eb..10cf42fde9b9ed 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.kt @@ -7,14 +7,20 @@ package com.facebook.react.modules.timing +import android.content.Context +import android.os.Looper import android.view.Choreographer.FrameCallback import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.CatalystInstance import com.facebook.react.bridge.JavaOnlyArray +import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.WritableArray import com.facebook.react.common.SystemClock import com.facebook.react.devsupport.interfaces.DevSupportManager +import com.facebook.react.jstasks.HeadlessJsTaskConfig +import com.facebook.react.jstasks.HeadlessJsTaskContext +import com.facebook.react.modules.appregistry.AppRegistry import com.facebook.react.modules.core.JSTimers import com.facebook.react.modules.core.ReactChoreographer import com.facebook.react.modules.core.ReactChoreographer.CallbackType @@ -27,15 +33,19 @@ import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.eq import org.mockito.MockedStatic +import org.mockito.Mockito.doAnswer +import org.mockito.Mockito.doReturn import org.mockito.Mockito.mock import org.mockito.Mockito.mockStatic import org.mockito.Mockito.reset +import org.mockito.Mockito.spy import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions import org.mockito.Mockito.`when` as whenever import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf @RunWith(RobolectricTestRunner::class) class TimingModuleTest { @@ -43,12 +53,14 @@ class TimingModuleTest { const val FRAME_TIME_NS = 17 * 1000 * 1000 } + private lateinit var reactContext: ReactApplicationContext + private lateinit var headlessContext: HeadlessJsTaskContext private lateinit var timingModule: TimingModule private lateinit var reactChoreographerMock: ReactChoreographer private lateinit var postFrameCallbackHandler: PostFrameCallbackHandler private lateinit var idlePostFrameCallbackHandler: PostFrameCallbackHandler private var currentTimeNs = 0L - private lateinit var jSTimersMock: JSTimers + private lateinit var jsTimersMock: JSTimers private lateinit var arguments: MockedStatic private lateinit var systemClock: MockedStatic private lateinit var reactChoreographer: MockedStatic @@ -82,9 +94,11 @@ class TimingModuleTest { .thenAnswer { reactChoreographerMock } val reactInstance = mock(CatalystInstance::class.java) - val reactContext = mock(ReactApplicationContext::class.java) - whenever(reactContext.catalystInstance).thenReturn(reactInstance) - whenever(reactContext.hasActiveReactInstance()).thenReturn(true) + reactContext = spy(ReactApplicationContext(mock(Context::class.java))) + doReturn(reactInstance).`when`(reactContext).catalystInstance + doReturn(true).`when`(reactContext).hasActiveReactInstance() + + headlessContext = HeadlessJsTaskContext.getInstance(reactContext) postFrameCallbackHandler = PostFrameCallbackHandler() idlePostFrameCallbackHandler = PostFrameCallbackHandler() @@ -95,7 +109,6 @@ class TimingModuleTest { .thenAnswer { return@thenAnswer postFrameCallbackHandler.answer(it) } - whenever( reactChoreographerMock.postFrameCallback( eq(CallbackType.IDLE_EVENT), any(FrameCallback::class.java))) @@ -104,12 +117,17 @@ class TimingModuleTest { } timingModule = TimingModule(reactContext, mock(DevSupportManager::class.java)) - jSTimersMock = mock(JSTimers::class.java) - whenever(reactContext.getJSModule(JSTimers::class.java)).thenReturn(jSTimersMock) - whenever(reactContext.runOnJSQueueThread(any(Runnable::class.java))).thenAnswer { invocation -> - (invocation.arguments[0] as Runnable).run() - return@thenAnswer true - } + jsTimersMock = mock(JSTimers::class.java) + doReturn(jsTimersMock).`when`(reactContext).getJSModule(JSTimers::class.java) + doReturn(mock(AppRegistry::class.java)) + .`when`(reactContext) + .getJSModule(AppRegistry::class.java) + doAnswer({ invocation -> + (invocation.arguments[0] as Runnable).run() + return@doAnswer true + }) + .`when`(reactContext) + .runOnJSQueueThread(any(Runnable::class.java)) timingModule.initialize() } @@ -122,6 +140,8 @@ class TimingModuleTest { } private fun stepChoreographerFrame() { + shadowOf(Looper.getMainLooper()).idle() + val callback = postFrameCallbackHandler.getAndResetFrameCallback() val idleCallback = idlePostFrameCallbackHandler.getAndResetFrameCallback() currentTimeNs += FRAME_TIME_NS @@ -134,111 +154,113 @@ class TimingModuleTest { @Test fun testSimpleTimer() { - timingModule.onHostResume() + reactContext.onHostResume(null) timingModule.createTimer(1.0, 1.0, 0.0, false) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(1.0)) - reset(jSTimersMock) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(1.0)) + reset(jsTimersMock) stepChoreographerFrame() - verifyNoMoreInteractions(jSTimersMock) + verifyNoMoreInteractions(jsTimersMock) } @Test fun testSimpleRecurringTimer() { timingModule.createTimer(100.0, 1.0, 0.0, true) - timingModule.onHostResume() + reactContext.onHostResume(null) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(100.0)) - reset(jSTimersMock) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(100.0)) + reset(jsTimersMock) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(100.0)) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(100.0)) } @Test fun testCancelRecurringTimer() { - timingModule.onHostResume() + reactContext.onHostResume(null) timingModule.createTimer(105.0, 1.0, 0.0, true) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(105.0)) - reset(jSTimersMock) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(105.0)) + reset(jsTimersMock) timingModule.deleteTimer(105.0) stepChoreographerFrame() - verifyNoMoreInteractions(jSTimersMock) + verifyNoMoreInteractions(jsTimersMock) } @Test fun testPausingAndResuming() { - timingModule.onHostResume() + reactContext.onHostResume(null) timingModule.createTimer(41.0, 1.0, 0.0, true) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHostPause() + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + reactContext.onHostPause() stepChoreographerFrame() - verifyNoMoreInteractions(jSTimersMock) - reset(jSTimersMock) - timingModule.onHostResume() + verifyNoMoreInteractions(jsTimersMock) + reset(jsTimersMock) + reactContext.onHostResume(null) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) } @Test fun testHeadlessJsTaskInBackground() { - timingModule.onHostPause() - timingModule.onHeadlessJsTaskStart(42) + reactContext.onHostPause() + val taskConfig = HeadlessJsTaskConfig("foo", JavaOnlyMap()) + val taskId = headlessContext.startTask(taskConfig) timingModule.createTimer(41.0, 1.0, 0.0, true) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHeadlessJsTaskFinish(42) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + headlessContext.finishTask(taskId) stepChoreographerFrame() - verifyNoMoreInteractions(jSTimersMock) + verifyNoMoreInteractions(jsTimersMock) } @Test fun testHeadlessJsTaskInForeground() { - timingModule.onHostResume() - timingModule.onHeadlessJsTaskStart(42) + val taskConfig = HeadlessJsTaskConfig("foo", JavaOnlyMap()) + val taskId = headlessContext.startTask(taskConfig) + reactContext.onHostResume(null) timingModule.createTimer(41.0, 1.0, 0.0, true) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHeadlessJsTaskFinish(42) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + headlessContext.finishTask(taskId) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHostPause() - verifyNoMoreInteractions(jSTimersMock) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + reactContext.onHostPause() + verifyNoMoreInteractions(jsTimersMock) } @Test fun testHeadlessJsTaskIntertwine() { - timingModule.onHostResume() - timingModule.onHeadlessJsTaskStart(42) timingModule.createTimer(41.0, 1.0, 0.0, true) - timingModule.onHostPause() + reactContext.onHostPause() + val taskConfig = HeadlessJsTaskConfig("foo", JavaOnlyMap()) + val taskId = headlessContext.startTask(taskConfig) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHostResume() - timingModule.onHeadlessJsTaskFinish(42) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + reactContext.onHostResume(null) + headlessContext.finishTask(taskId) stepChoreographerFrame() - verify(jSTimersMock).callTimers(JavaOnlyArray.of(41.0)) - reset(jSTimersMock) - timingModule.onHostPause() + verify(jsTimersMock).callTimers(JavaOnlyArray.of(41.0)) + reset(jsTimersMock) + reactContext.onHostPause() stepChoreographerFrame() - verifyNoMoreInteractions(jSTimersMock) + verifyNoMoreInteractions(jsTimersMock) } @Test fun testSetTimeoutZero() { timingModule.createTimer(100.0, 0.0, 0.0, false) - verify(jSTimersMock).callTimers(JavaOnlyArray.of(100.0)) + verify(jsTimersMock).callTimers(JavaOnlyArray.of(100.0)) } @Test fun testActiveTimersInRange() { - timingModule.onHostResume() + reactContext.onHostResume(null) assertThat(timingModule.hasActiveTimersInRange(100)).isFalse timingModule.createTimer(41.0, 1.0, 0.0, true) assertThat(timingModule.hasActiveTimersInRange(100)).isFalse // Repeating @@ -250,13 +272,12 @@ class TimingModuleTest { @Test fun testIdleCallback() { timingModule.setSendIdleEvents(true) - timingModule.onHostResume() + reactContext.onHostResume(null) stepChoreographerFrame() - verify(jSTimersMock).callIdleCallbacks(SystemClock.currentTimeMillis().toDouble()) + verify(jsTimersMock).callIdleCallbacks(SystemClock.currentTimeMillis().toDouble()) } private class PostFrameCallbackHandler : Answer { - private var frameCallback: FrameCallback? = null override fun answer(invocation: InvocationOnMock) { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/BridgelessReactContextTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/BridgelessReactContextTest.kt index d8a8c3b473091d..a3bf2053394eda 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/BridgelessReactContextTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/BridgelessReactContextTest.kt @@ -55,9 +55,9 @@ class BridgelessReactContextTest { Assertions.assertThat(bridgelessReactContext.getFabricUIManager()).isEqualTo(fabricUiManager) } - @Test(expected = UnsupportedOperationException::class) - fun getCatalystInstance_throwsException() { - // Disable this test for now due to mocking FabricUIManager fails - bridgelessReactContext.catalystInstance + @Test + fun getCatalystInstanceTest() { + Assertions.assertThat(bridgelessReactContext.getCatalystInstance()) + .isInstanceOf(BridgelessCatalystInstance::class.java) } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactHostTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactHostTest.kt index 44825dd09eae8a..e82b56d9c0ad0b 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactHostTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactHostTest.kt @@ -56,6 +56,8 @@ class ReactHostTest { private lateinit var bridgelessReactContext: BridgelessReactContext private lateinit var mockedReactInstanceCtor: MockedConstruction + private lateinit var mockedReactHostInspectorTargetCtor: + MockedConstruction private lateinit var mockedDevSupportManagerCtor: MockedConstruction private lateinit var mockedBridgelessReactContextCtor: MockedConstruction private lateinit var mockedMemoryPressureRouterCtor: MockedConstruction @@ -73,6 +75,8 @@ class ReactHostTest { bridgelessReactContext = Mockito.mock(BridgelessReactContext::class.java) mockedReactInstanceCtor = Mockito.mockConstruction(ReactInstance::class.java) + mockedReactHostInspectorTargetCtor = + Mockito.mockConstruction(ReactHostInspectorTarget::class.java) mockedDevSupportManagerCtor = Mockito.mockConstruction(BridgelessDevSupportManager::class.java) mockedBridgelessReactContextCtor = Mockito.mockConstruction(BridgelessReactContext::class.java) mockedMemoryPressureRouterCtor = Mockito.mockConstruction(MemoryPressureRouter::class.java) @@ -95,6 +99,7 @@ class ReactHostTest { @After fun tearDown() { mockedReactInstanceCtor.close() + mockedReactHostInspectorTargetCtor.close() mockedDevSupportManagerCtor.close() mockedBridgelessReactContextCtor.close() mockedMemoryPressureRouterCtor.close() diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactSurfaceTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactSurfaceTest.kt index 4d224410203489..014a45abb99827 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactSurfaceTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactSurfaceTest.kt @@ -12,7 +12,6 @@ import android.content.Context import android.view.View import com.facebook.react.bridge.NativeMap import com.facebook.react.common.annotations.UnstableReactNativeAPI -import com.facebook.react.fabric.ComponentFactory import com.facebook.react.interfaces.fabric.SurfaceHandler import com.facebook.react.runtime.internal.bolts.Task import com.facebook.react.uimanager.events.EventDispatcher @@ -34,7 +33,6 @@ import org.robolectric.shadows.ShadowInstrumentation @OptIn(UnstableReactNativeAPI::class) @Config(shadows = [ShadowSoLoader::class]) class ReactSurfaceTest { - private lateinit var reactHostDelegate: ReactHostDelegate private lateinit var eventDispatcher: EventDispatcher private lateinit var reactHost: ReactHostImpl private lateinit var context: Context @@ -43,12 +41,9 @@ class ReactSurfaceTest { @Before fun setUp() { - reactHostDelegate = mock(ReactHostDelegate::class.java) eventDispatcher = mock(EventDispatcher::class.java) context = Robolectric.buildActivity(Activity::class.java).create().get() - val componentFactory = Mockito.mock(ComponentFactory::class.java) - reactHost = - Mockito.spy(ReactHostImpl(context, reactHostDelegate, componentFactory, false, {}, false)) + reactHost = Mockito.mock(ReactHostImpl::class.java) Mockito.doAnswer(mockedStartSurface()) .`when`(reactHost) .startSurface(ArgumentMatchers.any(ReactSurfaceImpl::class.java)) diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/fakes/FakeUIManager.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/fakes/FakeUIManager.kt index 65db10c1e85eb7..520119603b66bf 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/fakes/FakeUIManager.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/fakes/FakeUIManager.kt @@ -15,8 +15,10 @@ import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.UIManager import com.facebook.react.bridge.UIManagerListener import com.facebook.react.bridge.WritableMap +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.fabric.interop.UIBlockViewResolver +@OptIn(UnstableReactNativeAPI::class) class FakeUIManager : UIManager, UIBlockViewResolver { // The number of times resolveView was called diff --git a/packages/react-native/ReactCommon/.clang-tidy b/packages/react-native/ReactCommon/.clang-tidy deleted file mode 100644 index bb56f020788994..00000000000000 --- a/packages/react-native/ReactCommon/.clang-tidy +++ /dev/null @@ -1,7 +0,0 @@ ---- -InheritParentConfig: true -CheckOptions: - # clang 15 does not support reverse_view - - key: modernize-loop-convert.UseCxx20ReverseRanges - value: false -... diff --git a/packages/react-native/ReactCommon/React-Fabric.podspec b/packages/react-native/ReactCommon/React-Fabric.podspec index 58f6f0a84383c8..6662a301291ec8 100644 --- a/packages/react-native/ReactCommon/React-Fabric.podspec +++ b/packages/react-native/ReactCommon/React-Fabric.podspec @@ -56,6 +56,7 @@ Pod::Spec.new do |s| s.dependency "fmt", "9.1.0" s.dependency "React-Core" s.dependency "React-debug" + s.dependency "React-featureflags" s.dependency "React-utils" s.dependency "React-runtimescheduler" s.dependency "React-cxxreact" @@ -197,7 +198,7 @@ Pod::Spec.new do |s| end - ss.subspec "textinput" do |sss| + ss.subspec "iostextinput" do |sss| sss.dependency folly_dep_name, folly_version sss.compiler_flags = folly_compiler_flags sss.source_files = "react/renderer/components/textinput/platform/ios/**/*.{m,mm,cpp,h}" @@ -205,6 +206,14 @@ Pod::Spec.new do |s| end + ss.subspec "textinput" do |sss| + sss.dependency folly_dep_name, folly_version + sss.compiler_flags = folly_compiler_flags + sss.source_files = "react/renderer/components/textinput/*.{m,mm,cpp,h}" + sss.header_dir = "react/renderer/components/textinput" + + end + ss.subspec "unimplementedview" do |sss| sss.dependency folly_dep_name, folly_version sss.compiler_flags = folly_compiler_flags diff --git a/packages/react-native/ReactCommon/React-FabricImage.podspec b/packages/react-native/ReactCommon/React-FabricImage.podspec index be125c11deec1d..4380d05d6dd614 100644 --- a/packages/react-native/ReactCommon/React-FabricImage.podspec +++ b/packages/react-native/ReactCommon/React-FabricImage.podspec @@ -38,7 +38,7 @@ if ENV['USE_FRAMEWORKS'] "\"$(PODS_TARGET_SRCROOT)\"", "\"$(PODS_TARGET_SRCROOT)/react/renderer/textlayoutmanager/platform/ios\"", "\"$(PODS_TARGET_SRCROOT)/react/renderer/components/textinput/platform/ios\"", - # "\"$(PODS_CONFIGURATION_BUILD_DIR)/React-Codegen/React_Codegen.framework/Headers\"", + # "\"$(PODS_CONFIGURATION_BUILD_DIR)/ReactCodegen/ReactCodegen.framework/Headers\"", ] end diff --git a/packages/react-native/ReactCommon/ReactCommon.podspec b/packages/react-native/ReactCommon/ReactCommon.podspec index 0b6f175895de6e..7fe1c6acee3e55 100644 --- a/packages/react-native/ReactCommon/ReactCommon.podspec +++ b/packages/react-native/ReactCommon/ReactCommon.podspec @@ -36,6 +36,7 @@ Pod::Spec.new do |s| s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/fmt/include\" \"$(PODS_ROOT)/Headers/Private/React-Core\"", "USE_HEADERMAP" => "YES", + "DEFINES_MODULE" => "YES", "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", "GCC_WARN_PEDANTIC" => "YES" } if ENV['USE_FRAMEWORKS'] @@ -71,8 +72,9 @@ Pod::Spec.new do |s| ss.subspec "core" do |sss| sss.source_files = "react/nativemodule/core/ReactCommon/**/*.{cpp,h}" - sss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/ReactCommon\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-debug/React_debug.framework/Headers\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-utils/React_utils.framework/Headers\"" } + sss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/ReactCommon\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-debug/React_debug.framework/Headers\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-debug/React_featureflags.framework/Headers\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-utils/React_utils.framework/Headers\"" } sss.dependency "React-debug", version + sss.dependency "React-featureflags", version sss.dependency "React-utils", version end end diff --git a/packages/react-native/ReactCommon/butter/.clang-tidy b/packages/react-native/ReactCommon/butter/.clang-tidy deleted file mode 100644 index 8edbbc799e94cf..00000000000000 --- a/packages/react-native/ReactCommon/butter/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -InheritParentConfig: true -Checks: '> -clang-diagnostic-*, -' -... diff --git a/packages/react-native/ReactCommon/butter/CMakeLists.txt b/packages/react-native/ReactCommon/butter/CMakeLists.txt deleted file mode 100644 index 1bfbc89275e996..00000000000000 --- a/packages/react-native/ReactCommon/butter/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -add_compile_options( - -DLOG_TAG=\"Butter\" - -fexceptions - -frtti - -std=c++20 - -Wall - -Wpedantic) - -add_library(butter INTERFACE) - -target_include_directories(butter INTERFACE .) - -target_link_libraries(butter INTERFACE glog) diff --git a/packages/react-native/ReactCommon/butter/butter.h b/packages/react-native/ReactCommon/butter/butter.h deleted file mode 100644 index 1b823235c48b6b..00000000000000 --- a/packages/react-native/ReactCommon/butter/butter.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -namespace facebook { -namespace butter { - -/* - * `Butter` is a minimal collection of basic tools borrowed from other low-level - * general purpose libraries (like Folly, Abseil or Boost). The main goals of - * Butter: - * - Make the codebase more portable; - * - Make the dependency list explicit (by decoupling it as a dependency list of - * Butter); - * - Make relying on modern C++ patterns and tools in code simple and easy. - * - Make executing experiments with different dependencies easier. - * - Limit reliance on third-party libraries eventually. - * - * Target C++ Version - * ------------------ - * Currently, Butter targets c++20. - * - * The Scope - * --------- - * What should be part of Butter and what should not? Should I add some piece of - * functionality in the Butter? Here is a quick checklist. - * - * As of now, Butter is relatively permissive per the guidance below: - * - * If one of the following is true, yes, go for it: - * - If some feature is already in some future C++ standard (possibly in draft - * stage) and it's already implemented in some 3rd party library. - * - If some standardized feature of C++ is implemented in the standard not in - * the most efficient way (because the standard enforces some tricky - * constraints, like always-valid iterators, which nobody uses and should use), - * but you have a library that does it right providing exact same interface. - * - * If one of the following is true, please do *NOT* do it (at least as part of - * the library): - * - You want to use some very fancy pattern that your favorite library (but - * nothing else) provides, and You want to make this pattern very command in the - * code base. Your hope is that this pattern will conquer the world and be - * a part of the C++ standard eventually. - * - You favorite library provides some general purpose container that 10x times - * faster than the standard one, so You want to use that in the code base. That - * container does not have compatible API though (because it's a clear trade-off - * with efficiency, of course). - * - * Note that eventually Butter will restrict the API collection to reduce - * reliance on non-standard C++ builtin libraries. That way, the API footprint - * stays small and is limited to just the essential APIs. This restriction is - * currently a work in progress. - */ - -/* - * Configuration - */ - -/* - * Enables using Folly containers instead of standard ones (such as map, vector, - * small_vector, optional and etc.) - * Custom containers are only enabled in release mode. Using custom stuff - * complicates debugging process because it breaks embedded into IDE - * introspections mechanisms. - */ -#ifndef DEBUG -#define BUTTER_USE_FOLLY_CONTAINERS -#endif - -} // namespace butter -} // namespace facebook diff --git a/packages/react-native/ReactCommon/butter/map.h b/packages/react-native/ReactCommon/butter/map.h deleted file mode 100644 index a5f6c665b68dd5..00000000000000 --- a/packages/react-native/ReactCommon/butter/map.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#ifdef BUTTER_USE_FOLLY_CONTAINERS - -#include - -#else - -#include - -#endif - -namespace facebook { -namespace butter { - -/* - * Note: In Butter, `map` aliases to `unordered_map` because everyone agrees - * that an *ordered* map is nonsense and was a huge mistake for standardization. - * If you need an *ordered* map, feel free to introduce that as - * `butter::ordered_map`. - */ - -#ifdef BUTTER_USE_FOLLY_CONTAINERS - -template -using map = folly::F14FastMap; - -#else - -template -using map = std::unordered_map; - -#endif - -} // namespace butter -} // namespace facebook diff --git a/packages/react-native/ReactCommon/callinvoker/.clang-tidy b/packages/react-native/ReactCommon/callinvoker/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/callinvoker/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h b/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h index 85d9aa8bc4812b..e5b4167264d7b9 100644 --- a/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h +++ b/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h @@ -12,9 +12,13 @@ #include "SchedulerPriority.h" +namespace facebook::jsi { +class Runtime; +} + namespace facebook::react { -using CallFunc = std::function; +using CallFunc = std::function; /** * An interface for a generic native-to-JS call invoker. See BridgeJSCallInvoker @@ -31,15 +35,29 @@ class CallInvoker { invokeAsync(std::move(func)); } virtual void invokeSync(CallFunc&& func) = 0; + + // Backward compatibility only, prefer the CallFunc methods instead + virtual void invokeAsync(std::function&& func) noexcept { + invokeAsync([func](jsi::Runtime&) { func(); }); + } + + virtual void invokeSync(std::function&& func) { + invokeSync([func](jsi::Runtime&) { func(); }); + } + virtual ~CallInvoker() {} }; +using NativeMethodCallFunc = std::function; + class NativeMethodCallInvoker { public: virtual void invokeAsync( const std::string& methodName, - CallFunc&& func) noexcept = 0; - virtual void invokeSync(const std::string& methodName, CallFunc&& func) = 0; + NativeMethodCallFunc&& func) noexcept = 0; + virtual void invokeSync( + const std::string& methodName, + NativeMethodCallFunc&& func) = 0; virtual ~NativeMethodCallInvoker() {} }; diff --git a/packages/react-native/ReactCommon/cxxreact/.clang-tidy b/packages/react-native/ReactCommon/cxxreact/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/cxxreact/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h b/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h index 89603e628a7b1d..bb08c4894a0bbb 100644 --- a/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h +++ b/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include namespace facebook::react { diff --git a/packages/react-native/ReactCommon/cxxreact/Instance.cpp b/packages/react-native/ReactCommon/cxxreact/Instance.cpp index 01c03ee9785442..ed0a2443efcf5d 100644 --- a/packages/react-native/ReactCommon/cxxreact/Instance.cpp +++ b/packages/react-native/ReactCommon/cxxreact/Instance.cpp @@ -54,7 +54,7 @@ void Instance::initializeBridge( std::shared_ptr jsef, std::shared_ptr jsQueue, std::shared_ptr moduleRegistry, - jsinspector_modern::PageTarget* parentInspectorTarget) { + jsinspector_modern::HostTarget* parentInspectorTarget) { callback_ = std::move(callback); moduleRegistry_ = std::move(moduleRegistry); parentInspectorTarget_ = parentInspectorTarget; @@ -279,14 +279,13 @@ void Instance::JSCallInvoker::setNativeToJsBridgeAndFlushCalls( } } -void Instance::JSCallInvoker::invokeSync(std::function&& work) { +void Instance::JSCallInvoker::invokeSync(CallFunc&& /*work*/) { // TODO: Replace JS Callinvoker with RuntimeExecutor. throw std::runtime_error( "Synchronous native -> JS calls are currently not supported."); } -void Instance::JSCallInvoker::invokeAsync( - std::function&& work) noexcept { +void Instance::JSCallInvoker::invokeAsync(CallFunc&& work) noexcept { std::scoped_lock guard(m_mutex); /** @@ -311,12 +310,12 @@ void Instance::JSCallInvoker::invokeAsync( scheduleAsync(std::move(work)); } -void Instance::JSCallInvoker::scheduleAsync( - std::function&& work) noexcept { +void Instance::JSCallInvoker::scheduleAsync(CallFunc&& work) noexcept { if (auto strongNativeToJsBridge = m_nativeToJsBridge.lock()) { strongNativeToJsBridge->runOnExecutorQueue( [work = std::move(work)](JSExecutor* executor) { - work(); + auto* runtime = (jsi::Runtime*)executor->getJavaScriptContext(); + work(*runtime); executor->flush(); }); } diff --git a/packages/react-native/ReactCommon/cxxreact/Instance.h b/packages/react-native/ReactCommon/cxxreact/Instance.h index bc4e58ebb1d43c..547c971dfe98c6 100644 --- a/packages/react-native/ReactCommon/cxxreact/Instance.h +++ b/packages/react-native/ReactCommon/cxxreact/Instance.h @@ -47,7 +47,7 @@ class RN_EXPORT Instance : private jsinspector_modern::InstanceTargetDelegate { std::shared_ptr jsef, std::shared_ptr jsQueue, std::shared_ptr moduleRegistry, - jsinspector_modern::PageTarget* inspectorTarget = nullptr); + jsinspector_modern::HostTarget* inspectorTarget = nullptr); void initializeRuntime(); @@ -164,21 +164,21 @@ class RN_EXPORT Instance : private jsinspector_modern::InstanceTargetDelegate { std::weak_ptr m_nativeToJsBridge; std::mutex m_mutex; bool m_shouldBuffer = true; - std::list> m_workBuffer; + std::list m_workBuffer; - void scheduleAsync(std::function&& work) noexcept; + void scheduleAsync(CallFunc&& work) noexcept; public: void setNativeToJsBridgeAndFlushCalls( std::weak_ptr nativeToJsBridge); - void invokeAsync(std::function&& work) noexcept override; - void invokeSync(std::function&& work) override; + void invokeAsync(CallFunc&& work) noexcept override; + void invokeSync(CallFunc&& work) override; }; std::shared_ptr jsCallInvoker_ = std::make_shared(); - jsinspector_modern::PageTarget* parentInspectorTarget_{nullptr}; + jsinspector_modern::HostTarget* parentInspectorTarget_{nullptr}; jsinspector_modern::InstanceTarget* inspectorTarget_{nullptr}; jsinspector_modern::RuntimeTarget* runtimeInspectorTarget_{nullptr}; }; diff --git a/packages/react-native/ReactCommon/cxxreact/JSExecutor.cpp b/packages/react-native/ReactCommon/cxxreact/JSExecutor.cpp index e68a716d772592..263ab90bb5cb31 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSExecutor.cpp +++ b/packages/react-native/ReactCommon/cxxreact/JSExecutor.cpp @@ -35,16 +35,12 @@ double JSExecutor::performanceNow() { return duration / NANOSECONDS_IN_MILLISECOND; } -std::unique_ptr -JSExecutor::createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) { - (void)executionContextDescription; - return std::make_unique( - std::move(frontendChannel), sessionState, getDescription()); +jsinspector_modern::RuntimeTargetDelegate& +JSExecutor::getRuntimeTargetDelegate() { + if (!runtimeTargetDelegate_) { + runtimeTargetDelegate_.emplace(getDescription()); + } + return *runtimeTargetDelegate_; } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JSExecutor.h b/packages/react-native/ReactCommon/cxxreact/JSExecutor.h index e89f924545249a..469f4ca6fd73d5 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSExecutor.h +++ b/packages/react-native/ReactCommon/cxxreact/JSExecutor.h @@ -55,7 +55,7 @@ class JSExecutorFactory { virtual ~JSExecutorFactory() {} }; -class RN_EXPORT JSExecutor : public jsinspector_modern::RuntimeTargetDelegate { +class RN_EXPORT JSExecutor { public: /** * Prepares the JS runtime for React Native by installing global variables. @@ -130,7 +130,7 @@ class RN_EXPORT JSExecutor : public jsinspector_modern::RuntimeTargetDelegate { virtual void handleMemoryPressure([[maybe_unused]] int pressureLevel) {} virtual void destroy() {} - virtual ~JSExecutor() override {} + virtual ~JSExecutor() = default; virtual void flush() {} @@ -141,16 +141,19 @@ class RN_EXPORT JSExecutor : public jsinspector_modern::RuntimeTargetDelegate { static double performanceNow(); /** - * Create a RuntimeAgentDelegate that can be used to debug the JS VM instance. + * Get a reference to the \c RuntimeTargetDelegate owned (or implemented) by + * this executor. This reference must remain valid for the duration of the + * executor's lifetime. */ - virtual std::unique_ptr - createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) override; + virtual jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate(); + + private: + /** + * Initialized by \c getRuntimeTargetDelegate if not overridden, and then + * never changes. + */ + std::optional + runtimeTargetDelegate_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp index f23ce412fae178..aeec3b7a144520 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp +++ b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp @@ -326,14 +326,14 @@ NativeToJsBridge::getDecoratedNativeMethodCallInvoker( void invokeAsync( const std::string& methodName, - std::function&& func) noexcept override { + NativeMethodCallFunc&& func) noexcept override { if (auto strongJsToNativeBridge = m_jsToNativeBridge.lock()) { strongJsToNativeBridge->recordTurboModuleAsyncMethodCall(); } m_nativeInvoker->invokeAsync(methodName, std::move(func)); } - void invokeSync(const std::string& methodName, std::function&& func) + void invokeSync(const std::string& methodName, NativeMethodCallFunc&& func) override { m_nativeInvoker->invokeSync(methodName, std::move(func)); } @@ -345,7 +345,7 @@ NativeToJsBridge::getDecoratedNativeMethodCallInvoker( jsinspector_modern::RuntimeTargetDelegate& NativeToJsBridge::getInspectorTargetDelegate() { - return *m_executor; + return m_executor->getRuntimeTargetDelegate(); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/SharedProxyCxxModule.h b/packages/react-native/ReactCommon/cxxreact/SharedProxyCxxModule.h index cb607d3ca5b976..858f9b7f325e8e 100644 --- a/packages/react-native/ReactCommon/cxxreact/SharedProxyCxxModule.h +++ b/packages/react-native/ReactCommon/cxxreact/SharedProxyCxxModule.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include diff --git a/packages/react-native/ReactCommon/hermes/.clang-tidy b/packages/react-native/ReactCommon/hermes/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/hermes/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.cpp b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.cpp index 4b1414253d38c3..8ee40df6785a6e 100644 --- a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.cpp +++ b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.cpp @@ -7,15 +7,12 @@ #include "HermesExecutorFactory.h" -#include - #include #include #include #include #include -#include #include #include @@ -155,6 +152,8 @@ class DecoratedRuntime : public jsi::WithRuntimeDecorator { debugToken_ = facebook::hermes::inspector_modern::chrome::enableDebugging( std::move(adapter), debuggerName); } +#else + (void)jsQueue; #endif // HERMES_ENABLE_DEBUGGER } @@ -253,40 +252,15 @@ HermesExecutor::HermesExecutor( RuntimeInstaller runtimeInstaller, HermesRuntime& hermesRuntime) : JSIExecutor(runtime, delegate, timeoutInvoker, runtimeInstaller), - jsQueue_(jsQueue), runtime_(runtime), - hermesRuntime_(hermesRuntime) {} - -std::unique_ptr -HermesExecutor::createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) { - std::shared_ptr hermesRuntimeShared(runtime_, &hermesRuntime_); - return std::unique_ptr( - new jsinspector_modern::HermesRuntimeAgentDelegate( - frontendChannel, - sessionState, - std::move(previouslyExportedState), - executionContextDescription, - hermesRuntimeShared, - [jsQueueWeak = std::weak_ptr(jsQueue_), - runtimeWeak = std::weak_ptr(runtime_)](auto fn) { - auto jsQueue = jsQueueWeak.lock(); - if (!jsQueue) { - return; - } - jsQueue->runOnQueue([runtimeWeak, fn]() { - auto runtime = runtimeWeak.lock(); - if (!runtime) { - return; - } - fn(*runtime); - }); - })); + hermesRuntime_(runtime_, &hermesRuntime) {} + +jsinspector_modern::RuntimeTargetDelegate& +HermesExecutor::getRuntimeTargetDelegate() { + if (!targetDelegate_) { + targetDelegate_.emplace(hermesRuntime_); + } + return *targetDelegate_; } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h index 689a58f7f0592e..ea370876d7af42 100644 --- a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h +++ b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include @@ -54,20 +55,15 @@ class HermesExecutor : public JSIExecutor { RuntimeInstaller runtimeInstaller, hermes::HermesRuntime& hermesRuntime); - virtual std::unique_ptr - createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) override; + jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate() + override; private: JSIScopedTimeoutInvoker timeoutInvoker_; - std::shared_ptr jsQueue_; std::shared_ptr runtime_; - hermes::HermesRuntime& hermesRuntime_; + std::shared_ptr hermesRuntime_; + std::optional + targetDelegate_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp index bfea30fc827a88..d3e0a6fef84670 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp @@ -5,214 +5,111 @@ * LICENSE file in the root directory of this source tree. */ -#include "HermesRuntimeAgentDelegate.h" - -// If HERMES_ENABLE_DEBUGGER isn't defined, we can't access any Hermes -// CDPHandler headers or types. - #ifdef HERMES_ENABLE_DEBUGGER -#include -#include -#else // HERMES_ENABLE_DEBUGGER -#include -#endif // HERMES_ENABLE_DEBUGGER +#include "HermesRuntimeAgentDelegate.h" + +#include +#include #include +#include #include using namespace facebook::hermes; namespace facebook::react::jsinspector_modern { -#ifdef HERMES_ENABLE_DEBUGGER - -namespace { - -/** - * An implementation of the Hermes RuntimeAdapter interface (part of - * Hermes's CDPHandler API) for use within a React Native RuntimeAgentDelegate. - */ -class HermesRuntimeAgentDelegateAdapter - : public hermes::inspector_modern::RuntimeAdapter { - public: - HermesRuntimeAgentDelegateAdapter( - std::shared_ptr runtime, - RuntimeExecutor runtimeExecutor) - : runtime_(runtime), runtimeExecutor_(runtimeExecutor) {} - - HermesRuntime& getRuntime() override { - return *runtime_; - } - - void tickleJs() override { - runtimeExecutor_([](jsi::Runtime& runtime) { - jsi::Function func = - runtime.global().getPropertyAsFunction(runtime, "__tickleJs"); - func.call(runtime); - }); - } - - private: - std::shared_ptr runtime_; - RuntimeExecutor runtimeExecutor_; -}; - -} // namespace - -/** - * A RuntimeAgentDelegate that handles requests from the Chrome DevTools - * Protocol for an instance of Hermes. - */ class HermesRuntimeAgentDelegate::Impl final : public RuntimeAgentDelegate { - using HermesCDPHandler = hermes::inspector_modern::chrome::CDPHandler; - using HermesExecutionContextDescription = - hermes::inspector_modern::chrome::CDPHandlerExecutionContextDescription; - using HermesState = hermes::inspector_modern::chrome::State; + using HermesState = hermes::cdp::State; struct HermesStateWrapper : public ExportedState { - explicit HermesStateWrapper(std::unique_ptr state) - : state_(std::move(state)) {} + explicit HermesStateWrapper(HermesState state) : state_(std::move(state)) {} - static std::unique_ptr unwrapDestructively( - ExportedState* wrapper) { + static HermesState unwrapDestructively(ExportedState* wrapper) { if (!wrapper) { - return nullptr; + return {}; } if (auto* typedWrapper = dynamic_cast(wrapper)) { return std::move(typedWrapper->state_); } - return nullptr; + return {}; } private: - std::unique_ptr state_; + HermesState state_; }; public: - /** - * \param frontendChannel A channel used to send responses and events to the - * frontend. - * \param sessionState The state of the current CDP session. This will only - * be accessed on the main thread (during the constructor, in handleRequest, - * etc). - * \param previouslyExportedState The exported state from a previous instance - * of RuntimeAgentDelegate (NOT necessarily HermesRuntimeAgentDelegate). This - * may be nullptr, and if not nullptr it may be of any concrete type that - * implements RuntimeAgentDelegate::ExportedState. - * \param executionContextDescription A description of the execution context - * represented by this runtime. This is used for disambiguating the - * source/destination of CDP messages when there are multiple runtimes - * (concurrently or over the life of a Page). - * \param runtime The HermesRuntime that this agent is attached to. - * \param runtimeExecutor A callback for scheduling work on the JS thread. - * \c runtimeExecutor may drop scheduled work if the runtime is destroyed - * first. - */ Impl( FrontendChannel frontendChannel, SessionState& sessionState, std::unique_ptr previouslyExportedState, const ExecutionContextDescription& executionContextDescription, - std::shared_ptr runtime, - RuntimeExecutor runtimeExecutor) - : hermes_(HermesCDPHandler::create( - std::make_unique( - runtime, - runtimeExecutor), - /* waitForDebugger */ false, - /* enableConsoleAPICapturing */ false, - /* state */ + HermesRuntime& runtime, + HermesRuntimeTargetDelegate& runtimeTargetDelegate, + const RuntimeExecutor& runtimeExecutor) + : hermes_(hermes::cdp::CDPAgent::create( + executionContextDescription.id, + runtimeTargetDelegate.getCDPDebugAPI(), + // RuntimeTask takes a HermesRuntime whereas our RuntimeExecutor + // takes a jsi::Runtime. + [runtimeExecutor, + &runtime](facebook::hermes::debugger::RuntimeTask fn) { + runtimeExecutor( + [&runtime, fn = std::move(fn)](auto&) { fn(runtime); }); + }, + frontendChannel, HermesStateWrapper::unwrapDestructively( - previouslyExportedState.get()), - {.isRuntimeDomainEnabled = sessionState.isRuntimeDomainEnabled}, - HermesExecutionContextDescription{ - .id = executionContextDescription.id, - .origin = executionContextDescription.origin, - .name = executionContextDescription.name, - .auxData = std::nullopt, - .shouldSendNotifications = false})) { - hermes_->registerCallbacks( - /* msgCallback */ - [frontendChannel = - std::move(frontendChannel)](const std::string& messageFromHermes) { - frontendChannel(messageFromHermes); - ; - }, - /* onUnregister */ - []() {}); + previouslyExportedState.get()))) { + if (sessionState.isRuntimeDomainEnabled) { + hermes_->enableRuntimeDomain(); + } + if (sessionState.isDebuggerDomainEnabled) { + hermes_->enableDebuggerDomain(); + } } - /** - * Handle a CDP request. The response will be sent over the provided - * \c FrontendChannel synchronously or asynchronously. - * \param req The parsed request. - * \returns true if this agent has responded, or will respond asynchronously, - * to the request (with either a success or error message). False if the - * agent expects another agent to respond to the request instead. - */ bool handleRequest(const cdp::PreparsedRequest& req) override { // TODO: Change to string::starts_with when we're on C++20. if (req.method.rfind("Log.", 0) == 0) { - // Since we know Hermes doesn't do anything useful with Log messages, but - // our containing PageAgent will, just bail out early. + // Since we know Hermes doesn't do anything useful with Log messages, + // but our containing HostAgent will, bail out early. // TODO: We need a way to negotiate this more dynamically with Hermes // through the API. return false; } - // Forward everything else to Hermes's CDPHandler. - hermes_->handle(req.toJson()); + // Forward everything else to Hermes's CDPAgent. + hermes_->handleCommand(req.toJson()); // Let the call know that this request is handled (i.e. it is Hermes's // responsibility to respond with either success or an error). return true; } - virtual std::unique_ptr getExportedState() override { + std::unique_ptr getExportedState() override { return std::make_unique(hermes_->getState()); } private: - std::shared_ptr hermes_; -}; - -#else // !HERMES_ENABLE_DEBUGGER - -/** - * A stub for HermesRuntimeAgentDelegate when Hermes is compiled without - * debugging support. - */ -class HermesRuntimeAgentDelegate::Impl final - : public FallbackRuntimeAgentDelegate { - public: - Impl( - FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr, - const ExecutionContextDescription&, - std::shared_ptr runtime, - RuntimeExecutor) - : FallbackRuntimeAgentDelegate( - std::move(frontendChannel), - sessionState, - runtime->description()) {} + std::unique_ptr hermes_; }; -#endif // HERMES_ENABLE_DEBUGGER - HermesRuntimeAgentDelegate::HermesRuntimeAgentDelegate( FrontendChannel frontendChannel, SessionState& sessionState, std::unique_ptr previouslyExportedState, const ExecutionContextDescription& executionContextDescription, - std::shared_ptr runtime, + HermesRuntime& runtime, + HermesRuntimeTargetDelegate& runtimeTargetDelegate, RuntimeExecutor runtimeExecutor) : impl_(std::make_unique( std::move(frontendChannel), sessionState, std::move(previouslyExportedState), executionContextDescription, - std::move(runtime), + runtime, + runtimeTargetDelegate, std::move(runtimeExecutor))) {} bool HermesRuntimeAgentDelegate::handleRequest( @@ -220,9 +117,11 @@ bool HermesRuntimeAgentDelegate::handleRequest( return impl_->handleRequest(req); } -std::unique_ptr +std::unique_ptr HermesRuntimeAgentDelegate::getExportedState() { return impl_->getExportedState(); } } // namespace facebook::react::jsinspector_modern + +#endif // HERMES_ENABLE_DEBUGGER diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h index e6be5dc7246de1..d38e86358ca226 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h @@ -7,8 +7,11 @@ #pragma once -#include +#ifdef HERMES_ENABLE_DEBUGGER + +#include "HermesRuntimeTargetDelegate.h" +#include #include #include @@ -16,7 +19,7 @@ namespace facebook::react::jsinspector_modern { /** * A RuntimeAgentDelegate that handles requests from the Chrome DevTools - * Protocol for an instance of Hermes. + * Protocol for an instance of Hermes, using the modern CDPAgent API. */ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { public: @@ -27,14 +30,18 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { * be accessed on the main thread (during the constructor, in handleRequest, * etc). * \param previouslyExportedState The exported state from a previous instance - * of RuntimeAgentDelegate (NOT necessarily HermesRuntimeAgentDelegate). This - * may be nullptr, and if not nullptr it may be of any concrete type that + * of RuntimeAgentDelegate (NOT necessarily HermesRuntimeAgentDelegate). + * This may be nullptr, and if not nullptr it may be of any concrete type that * implements RuntimeAgentDelegate::ExportedState. * \param executionContextDescription A description of the execution context * represented by this runtime. This is used for disambiguating the * source/destination of CDP messages when there are multiple runtimes - * (concurrently or over the life of a Page). - * \param runtime The HermesRuntime that this agent is attached to. + * (concurrently or over the life of a Host). + * \param runtime The HermesRuntime that this agent is attached to. The caller + * is responsible for keeping this object alive for the duration of the + * \c HermesRuntimeAgentDelegate lifetime. + * \param runtimeTargetDelegate The \c HermesRuntimeTargetDelegate object + * object for the passed runtime. * \param runtimeExecutor A callback for scheduling work on the JS thread. * \c runtimeExecutor may drop scheduled work if the runtime is destroyed * first. @@ -45,11 +52,12 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { std::unique_ptr previouslyExportedState, const ExecutionContextDescription& executionContextDescription, - std::shared_ptr runtime, + hermes::HermesRuntime& runtime, + HermesRuntimeTargetDelegate& runtimeTargetDelegate, RuntimeExecutor runtimeExecutor); /** - * Handle a CDP request. The response will be sent over the provided + * Handle a CDP request. The response will be sent over the provided * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. * \returns true if this agent has responded, or will respond asynchronously, @@ -58,14 +66,18 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { */ bool handleRequest(const cdp::PreparsedRequest& req) override; - virtual std::unique_ptr getExportedState() override; + std::unique_ptr getExportedState() + override; private: - // We use the private implementation idiom to keep HERMES_ENABLE_DEBUGGER - // checks out of the header. class Impl; const std::unique_ptr impl_; }; } // namespace facebook::react::jsinspector_modern + +#else +#error \ + "HERMES_ENABLE_DEBUGGER must be enabled to use HermesRuntimeAgentDelegate." +#endif // HERMES_ENABLE_DEBUGGER diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.cpp b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.cpp new file mode 100644 index 00000000000000..f83da054d6050e --- /dev/null +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include "HermesRuntimeTargetDelegate.h" + +// If HERMES_ENABLE_DEBUGGER isn't defined, we can't access any Hermes +// CDPHandler headers or types. +#ifdef HERMES_ENABLE_DEBUGGER +#include "HermesRuntimeAgentDelegate.h" + +#include + +using namespace facebook::hermes::cdp; +#else +#include +#endif // HERMES_ENABLE_DEBUGGER + +#include + +using namespace facebook::hermes; + +namespace facebook::react::jsinspector_modern { + +#ifdef HERMES_ENABLE_DEBUGGER +class HermesRuntimeTargetDelegate::Impl final : public RuntimeTargetDelegate { + public: + explicit Impl( + HermesRuntimeTargetDelegate& delegate, + std::shared_ptr hermesRuntime) + : delegate_(delegate), + runtime_(std::move(hermesRuntime)), + cdpDebugAPI_(CDPDebugAPI::create(*runtime_)) {} + + CDPDebugAPI& getCDPDebugAPI() { + return *cdpDebugAPI_; + } + + // RuntimeTargetDelegate methods + + std::unique_ptr createAgentDelegate( + FrontendChannel frontendChannel, + SessionState& sessionState, + std::unique_ptr + previouslyExportedState, + const ExecutionContextDescription& executionContextDescription, + RuntimeExecutor runtimeExecutor) override { + return std::unique_ptr(new HermesRuntimeAgentDelegate( + frontendChannel, + sessionState, + std::move(previouslyExportedState), + executionContextDescription, + *runtime_, + delegate_, + std::move(runtimeExecutor))); + } + + void addConsoleMessage(jsi::Runtime& /*unused*/, ConsoleMessage message) + override { + using HermesConsoleMessage = facebook::hermes::cdp::ConsoleMessage; + using HermesConsoleAPIType = facebook::hermes::cdp::ConsoleAPIType; + + HermesConsoleAPIType type{}; + switch (message.type) { + case ConsoleAPIType::kLog: + type = HermesConsoleAPIType::kLog; + break; + case ConsoleAPIType::kDebug: + type = HermesConsoleAPIType::kDebug; + break; + case ConsoleAPIType::kInfo: + type = HermesConsoleAPIType::kInfo; + break; + case ConsoleAPIType::kError: + type = HermesConsoleAPIType::kError; + break; + case ConsoleAPIType::kWarning: + type = HermesConsoleAPIType::kWarning; + break; + case ConsoleAPIType::kDir: + type = HermesConsoleAPIType::kDir; + break; + case ConsoleAPIType::kDirXML: + type = HermesConsoleAPIType::kDirXML; + break; + case ConsoleAPIType::kTable: + type = HermesConsoleAPIType::kTable; + break; + case ConsoleAPIType::kTrace: + type = HermesConsoleAPIType::kTrace; + break; + case ConsoleAPIType::kStartGroup: + type = HermesConsoleAPIType::kStartGroup; + break; + case ConsoleAPIType::kStartGroupCollapsed: + type = HermesConsoleAPIType::kStartGroupCollapsed; + break; + case ConsoleAPIType::kEndGroup: + type = HermesConsoleAPIType::kEndGroup; + break; + case ConsoleAPIType::kClear: + type = HermesConsoleAPIType::kClear; + break; + case ConsoleAPIType::kAssert: + type = HermesConsoleAPIType::kAssert; + break; + case ConsoleAPIType::kTimeEnd: + type = HermesConsoleAPIType::kTimeEnd; + break; + case ConsoleAPIType::kCount: + type = HermesConsoleAPIType::kCount; + break; + default: + throw std::logic_error{"Unknown console message type"}; + } + cdpDebugAPI_->addConsoleMessage( + HermesConsoleMessage{message.timestamp, type, std::move(message.args)}); + } + + private: + HermesRuntimeTargetDelegate& delegate_; + std::shared_ptr runtime_; + const std::unique_ptr cdpDebugAPI_; +}; + +#else + +/** + * A stub for HermesRuntimeTargetDelegate when Hermes is compiled without + * debugging support. + */ +class HermesRuntimeTargetDelegate::Impl final + : public FallbackRuntimeTargetDelegate { + public: + explicit Impl( + HermesRuntimeTargetDelegate&, + std::shared_ptr hermesRuntime) + : FallbackRuntimeTargetDelegate{hermesRuntime->description()} {} +}; + +#endif // HERMES_ENABLE_DEBUGGER + +HermesRuntimeTargetDelegate::HermesRuntimeTargetDelegate( + std::shared_ptr hermesRuntime) + : impl_(std::make_unique(*this, std::move(hermesRuntime))) {} + +HermesRuntimeTargetDelegate::~HermesRuntimeTargetDelegate() = default; + +std::unique_ptr +HermesRuntimeTargetDelegate::createAgentDelegate( + FrontendChannel frontendChannel, + SessionState& sessionState, + std::unique_ptr + previouslyExportedState, + const ExecutionContextDescription& executionContextDescription, + RuntimeExecutor runtimeExecutor) { + return impl_->createAgentDelegate( + frontendChannel, + sessionState, + std::move(previouslyExportedState), + executionContextDescription, + std::move(runtimeExecutor)); +} + +void HermesRuntimeTargetDelegate::addConsoleMessage( + jsi::Runtime& runtime, + ConsoleMessage message) { + impl_->addConsoleMessage(runtime, std::move(message)); +} + +#ifdef HERMES_ENABLE_DEBUGGER +CDPDebugAPI& HermesRuntimeTargetDelegate::getCDPDebugAPI() { + return impl_->getCDPDebugAPI(); +} +#endif + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h new file mode 100644 index 00000000000000..d442505dbf6f48 --- /dev/null +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include +#include + +#ifdef HERMES_ENABLE_DEBUGGER +#include +#endif + +#include + +namespace facebook::react::jsinspector_modern { + +/** + * A RuntimeTargetDelegate that enables debugging a Hermes runtime over CDP. + */ +class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { + public: + /** + * Creates a HermesRuntimeTargetDelegate for the given runtime. + */ + explicit HermesRuntimeTargetDelegate( + std::shared_ptr hermesRuntime); + + ~HermesRuntimeTargetDelegate() override; + + // RuntimeTargetDelegate methods + + std::unique_ptr createAgentDelegate( + jsinspector_modern::FrontendChannel frontendChannel, + jsinspector_modern::SessionState& sessionState, + std::unique_ptr + previouslyExportedState, + const jsinspector_modern::ExecutionContextDescription& + executionContextDescription, + RuntimeExecutor runtimeExecutor) override; + + void addConsoleMessage(jsi::Runtime& runtime, ConsoleMessage message) + override; + + private: + // We use the private implementation idiom to ensure this class has the same + // layout regardless of whether HERMES_ENABLE_DEBUGGER is defined. The net + // effect is that callers can include HermesRuntimeTargetDelegate.h without + // setting HERMES_ENABLE_DEBUGGER one way or the other. + class Impl; + +// Callers within this library may set HERMES_ENABLE_DEBUGGER to see this extra +// API. +#ifdef HERMES_ENABLE_DEBUGGER + friend class HermesRuntimeAgentDelegate; + + hermes::cdp::CDPDebugAPI& getCDPDebugAPI(); +#endif + + std::unique_ptr impl_; +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsc/.clang-tidy b/packages/react-native/ReactCommon/jsc/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/jsc/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/jsc/JSCRuntime.cpp b/packages/react-native/ReactCommon/jsc/JSCRuntime.cpp index c42d4f3008e4a6..33f7db44d3a76c 100644 --- a/packages/react-native/ReactCommon/jsc/JSCRuntime.cpp +++ b/packages/react-native/ReactCommon/jsc/JSCRuntime.cpp @@ -13,8 +13,8 @@ #include #include #include +#include #include -#include #include #include @@ -51,6 +51,12 @@ class JSCRuntime : public jsi::Runtime { const std::shared_ptr& buffer, const std::string& sourceURL) override; + // If we use this interface to implement microtasks in the host we need to + // polyfill `Promise` to use these methods, because JSC doesn't currently + // support providing a custom queue for its built-in implementation. + // Not doing this would result in a non-compliant behavior, as microtasks + // wouldn't execute in the order in which they were queued. + void queueMicrotask(const jsi::Function& callback) override; bool drainMicrotasks(int maxMicrotasksHint = -1) override; jsi::Object global() override; @@ -265,6 +271,7 @@ class JSCRuntime : public jsi::Runtime { std::atomic ctxInvalid_; std::string desc_; JSValueRef nativeStateSymbol_ = nullptr; + std::deque microtaskQueue_; #ifndef NDEBUG mutable std::atomic objectCounter_; mutable std::atomic symbolCounter_; @@ -378,6 +385,10 @@ JSCRuntime::JSCRuntime(JSGlobalContextRef ctx) } JSCRuntime::~JSCRuntime() { + // We need to clear the microtask queue to remove all references to the + // callbacks, so objectCounter_ would be 0 below. + microtaskQueue_.clear(); + // On shutting down and cleaning up: when JSC is actually torn down, // it calls JSC::Heap::lastChanceToFinalize internally which // finalizes anything left over. But at this point, @@ -434,7 +445,23 @@ jsi::Value JSCRuntime::evaluateJavaScript( return createValue(res); } -bool JSCRuntime::drainMicrotasks(int maxMicrotasksHint) { +void JSCRuntime::queueMicrotask(const jsi::Function& callback) { + microtaskQueue_.emplace_back(callback.getFunction(*this)); +} + +bool JSCRuntime::drainMicrotasks(int /*maxMicrotasksHint*/) { + // Note that new jobs can be enqueued during the draining. + while (!microtaskQueue_.empty()) { + jsi::Function callback = std::move(microtaskQueue_.front()); + + // We need to pop before calling the callback because that might throw. + // When that happens, the host will call `drainMicrotasks` again to execute + // the remaining microtasks, and this one shouldn't run again. + microtaskQueue_.pop_front(); + + callback.call(*this); + } + return true; } diff --git a/packages/react-native/ReactCommon/jsengineinstance/.clang-tidy b/packages/react-native/ReactCommon/jsengineinstance/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/jsengineinstance/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/jsi/.clang-tidy b/packages/react-native/ReactCommon/jsi/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/jsi/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/jsi/jsi/decorator.h b/packages/react-native/ReactCommon/jsi/jsi/decorator.h index 7bddd1fad80a52..6f4351a420da69 100644 --- a/packages/react-native/ReactCommon/jsi/jsi/decorator.h +++ b/packages/react-native/ReactCommon/jsi/jsi/decorator.h @@ -126,6 +126,9 @@ class RuntimeDecorator : public Base, private jsi::Instrumentation { const std::shared_ptr& js) override { return plain().evaluatePreparedJavaScript(js); } + void queueMicrotask(const jsi::Function& callback) override { + return plain().queueMicrotask(callback); + } bool drainMicrotasks(int maxMicrotasksHint) override { return plain().drainMicrotasks(maxMicrotasksHint); } @@ -544,6 +547,10 @@ class WithRuntimeDecorator : public RuntimeDecorator { Around around{with_}; return RD::evaluatePreparedJavaScript(js); } + void queueMicrotask(const Function& callback) override { + Around around{with_}; + RD::queueMicrotask(callback); + } bool drainMicrotasks(int maxMicrotasksHint) override { Around around{with_}; return RD::drainMicrotasks(maxMicrotasksHint); diff --git a/packages/react-native/ReactCommon/jsi/jsi/jsi.h b/packages/react-native/ReactCommon/jsi/jsi/jsi.h index 962dae93609423..d77255f61a86c7 100644 --- a/packages/react-native/ReactCommon/jsi/jsi/jsi.h +++ b/packages/react-native/ReactCommon/jsi/jsi/jsi.h @@ -209,6 +209,13 @@ class JSI_EXPORT Runtime { virtual Value evaluatePreparedJavaScript( const std::shared_ptr& js) = 0; + /// Queues a microtask in the JavaScript VM internal Microtask (a.k.a. Job in + /// ECMA262) queue, to be executed when the host drains microtasks in + /// its event loop implementation. + /// + /// \param callback a function to be executed as a microtask. + virtual void queueMicrotask(const jsi::Function& callback) = 0; + /// Drain the JavaScript VM internal Microtask (a.k.a. Job in ECMA262) queue. /// /// \param maxMicrotasksHint a hint to tell an implementation that it should diff --git a/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp b/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp index 8291d428b357a8..d9090bdb2aac65 100644 --- a/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp +++ b/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp @@ -1358,6 +1358,38 @@ TEST_P(JSITest, JSErrorTest) { JSIException); } +TEST_P(JSITest, MicrotasksTest) { + try { + rt.global().setProperty(rt, "globalValue", String::createFromAscii(rt, "")); + + auto microtask1 = + function("function microtask1() { globalValue += 'hello'; }"); + auto microtask2 = + function("function microtask2() { globalValue += ' world' }"); + + rt.queueMicrotask(microtask1); + rt.queueMicrotask(microtask2); + + EXPECT_EQ( + rt.global().getProperty(rt, "globalValue").asString(rt).utf8(rt), ""); + + rt.drainMicrotasks(); + + EXPECT_EQ( + rt.global().getProperty(rt, "globalValue").asString(rt).utf8(rt), + "hello world"); + + // Microtasks shouldn't run again + rt.drainMicrotasks(); + + EXPECT_EQ( + rt.global().getProperty(rt, "globalValue").asString(rt).utf8(rt), + "hello world"); + } catch (const JSINativeException& ex) { + // queueMicrotask() is unimplemented by some runtimes, ignore such failures. + } +} + //---------------------------------------------------------------------- // Test that multiple levels of delegation in DecoratedHostObjects works. diff --git a/packages/react-native/ReactCommon/jsiexecutor/.clang-tidy b/packages/react-native/ReactCommon/jsiexecutor/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/jsiexecutor/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/jsinspector-modern/.clang-tidy b/packages/react-native/ReactCommon/jsinspector-modern/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/jsinspector-modern/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/jsinspector-modern/CONCEPTS.md b/packages/react-native/ReactCommon/jsinspector-modern/CONCEPTS.md index e07d2eeda971fc..f62ddb431cf896 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/CONCEPTS.md +++ b/packages/react-native/ReactCommon/jsinspector-modern/CONCEPTS.md @@ -8,11 +8,11 @@ A debuggable entity that a debugger frontend can connect to. ### Target Delegate -An interface between a Target class and the underlying debuggable entity. For example, PageTargetDelegate is used by PageTarget to send page-related events to the native platform implementation. +An interface between a Target class and the underlying debuggable entity. For example, HostTargetDelegate is used by HostTarget to send host-related events to the native platform implementation. ### Target Controller -A private interface exposed by a Target class to its Sessions/Agents. For example, PageTargetController is used by PageAgent to safely access the page's PageTargetDelegate, without exposing PageTarget's other private state. +A private interface exposed by a Target class to its Sessions/Agents. For example, HostTargetController is used by HostAgent to safely access the host's HostTargetDelegate, without exposing HostTarget's other private state. ### Session diff --git a/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.cpp b/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.cpp new file mode 100644 index 00000000000000..d91d3f3678a38c --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "CdpJson.h" + +#include +#include + +namespace facebook::react::jsinspector_modern::cdp { + +PreparsedRequest preparse(std::string_view message) { + folly::dynamic parsed = folly::parseJson(message); + return PreparsedRequest{ + .id = parsed["id"].getInt(), + .method = parsed["method"].getString(), + .params = parsed.count("params") != 0u ? parsed["params"] : nullptr}; +} + +std::string PreparsedRequest::toJson() const { + folly::dynamic obj = folly::dynamic::object; + obj["id"] = id; + obj["method"] = method; + if (params != nullptr) { + obj["params"] = params; + } + return folly::toJson(obj); +} + +std::string jsonError( + std::optional id, + ErrorCode code, + std::optional message) { + auto dynamicError = folly::dynamic::object("code", static_cast(code)); + if (message) { + dynamicError("message", *message); + } + return folly::toJson( + (id ? folly::dynamic::object("id", *id) + : folly::dynamic::object( + "id", nullptr))("error", std::move(dynamicError))); +} + +std::string jsonResult(RequestId id, const folly::dynamic& result) { + return folly::toJson(folly::dynamic::object("id", id)("result", result)); +} + +std::string jsonNotification( + std::string_view method, + std::optional params) { + auto dynamicNotification = folly::dynamic::object("method", method); + if (params) { + dynamicNotification("params", *params); + } + return folly::toJson(std::move(dynamicNotification)); +} + +} // namespace facebook::react::jsinspector_modern::cdp diff --git a/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.h b/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.h new file mode 100644 index 00000000000000..b77e40f7ef7cfb --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/CdpJson.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +namespace facebook::react::jsinspector_modern::cdp { + +using RequestId = long long; + +/** + * Error codes to be used in CDP responses. + * https://www.jsonrpc.org/specification#error_object + */ +enum class ErrorCode { + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603 + /* -32000 to -32099: Implementation-defined server errors. */ +}; + +/** + * An incoming CDP request that has been parsed into a more usable form. + */ +struct PreparsedRequest { + public: + /** + * The ID of the request. + */ + RequestId id{}; + + /** + * The name of the method being invoked. + */ + std::string method; + + /** + * The parameters passed to the method, if any. + */ + folly::dynamic params; + + /** + * Equality operator, useful for unit tests + */ + inline bool operator==(const PreparsedRequest& rhs) const { + return id == rhs.id && method == rhs.method && params == rhs.params; + } + + std::string toJson() const; +}; + +/** + * Parse a JSON-encoded CDP request into its constituent parts. + * \throws ParseError If the input cannot be parsed. + * \throws TypeError If the input does not conform to the expected format. + */ +PreparsedRequest preparse(std::string_view message); + +/** + * A type error that may be thrown while preparsing a request, or while + * accessing dynamic params on a request. + */ +using TypeError = folly::TypeError; + +/** + * A parse error that may be thrown while preparsing a request. + */ +using ParseError = folly::json::parse_error; + +/** + * Helper functions for creating CDP (loosely JSON-RPC) messages of various + * types, returning a JSON string ready for sending over the wire. + */ + +/** + * Returns a JSON-formatted string representing an error. + * + * {"id": , "error": { "code": , "message": }} + * + * \param id Request ID. Mandatory, null only if the request omitted it or + * could not be parsed. + * \param code Integer code from cdp::ErrorCode. + * \param message Optional, brief human-readable error message. + */ +std::string jsonError( + std::optional id, + ErrorCode code, + std::optional message = std::nullopt); + +/** + * Returns a JSON-formatted string representing a successful response. + * + * {"id": , "result": } + * + * \param id The id of the request that this response corresponds to. + * \param result Result payload, defaulting to {}. + */ +std::string jsonResult( + RequestId id, + const folly::dynamic& result = folly::dynamic::object()); + +/** + * Returns a JSON-formatted string representing a unilateral notifcation. + * + * {"method": , "params": } + * + * \param method Notification (aka "event") method. + * \param params Optional payload pbject. + */ +std::string jsonNotification( + std::string_view method, + std::optional params = std::nullopt); + +} // namespace facebook::react::jsinspector_modern::cdp diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h new file mode 100644 index 00000000000000..4ca5b1c665820d --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace facebook::react::jsinspector_modern { + +enum class ConsoleAPIType { + kLog, + kDebug, + kInfo, + kError, + kWarning, + kDir, + kDirXML, + kTable, + kTrace, + kStartGroup, + kStartGroupCollapsed, + kEndGroup, + kClear, + kAssert, + kTimeEnd, + kCount +}; + +struct ConsoleMessage { + double timestamp; + ConsoleAPIType type; + std::vector args; + + ConsoleMessage( + double timestamp, + ConsoleAPIType type, + std::vector args) + : timestamp(timestamp), type(type), args(std::move(args)) {} + + ConsoleMessage(const ConsoleMessage& other) = delete; + ConsoleMessage(ConsoleMessage&& other) noexcept = default; + ConsoleMessage& operator=(const ConsoleMessage& other) = delete; + ConsoleMessage& operator=(ConsoleMessage&& other) noexcept = default; + ~ConsoleMessage() = default; +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp index 75f74e5f285302..5cab36048b67ff 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp @@ -54,17 +54,16 @@ void FallbackRuntimeAgentDelegate::sendFallbackRuntimeWarning() { } void FallbackRuntimeAgentDelegate::sendWarningLogEntry(std::string_view text) { - frontendChannel_( - folly::toJson(folly::dynamic::object("method", "Log.entryAdded")( - "params", + frontendChannel_(cdp::jsonNotification( + "Log.entryAdded", + folly::dynamic::object( + "entry", folly::dynamic::object( - "entry", - folly::dynamic::object( - "timestamp", - duration_cast( - system_clock::now().time_since_epoch()) - .count())("source", "other")( - "level", "warning")("text", text))))); + "timestamp", + duration_cast( + system_clock::now().time_since_epoch()) + .count())("source", "other")( + "level", "warning")("text", text)))); } } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.cpp b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.cpp new file mode 100644 index 00000000000000..f7d36d415f9349 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "FallbackRuntimeTargetDelegate.h" +#include "FallbackRuntimeAgentDelegate.h" + +namespace facebook::react::jsinspector_modern { + +FallbackRuntimeTargetDelegate::FallbackRuntimeTargetDelegate( + std::string engineDescription) + : engineDescription_{std::move(engineDescription)} {} + +std::unique_ptr +FallbackRuntimeTargetDelegate::createAgentDelegate( + FrontendChannel channel, + SessionState& sessionState, + std::unique_ptr + /*previouslyExportedState*/, + const ExecutionContextDescription& /*executionContextDescription*/, + RuntimeExecutor /*runtimeExecutor*/) { + return std::make_unique( + std::move(channel), sessionState, engineDescription_); +} + +void FallbackRuntimeTargetDelegate::addConsoleMessage( + jsi::Runtime& /*unused*/, + ConsoleMessage /*unused*/) { + // TODO: Best-effort printing (without RemoteObjects) +} + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h new file mode 100644 index 00000000000000..fa859f0fceda64 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include "InspectorInterfaces.h" +#include "RuntimeTarget.h" +#include "SessionState.h" + +#include + +namespace facebook::react::jsinspector_modern { + +/** + * A RuntimeTargetDelegate that stubs out debugging functionality for a + * JavaScript runtime that does not natively support debugging. + */ +class FallbackRuntimeTargetDelegate : public RuntimeTargetDelegate { + public: + explicit FallbackRuntimeTargetDelegate(std::string engineDescription); + + std::unique_ptr createAgentDelegate( + FrontendChannel channel, + SessionState& sessionState, + std::unique_ptr + previouslyExportedState, + const ExecutionContextDescription& executionContextDescription, + RuntimeExecutor runtimeExecutor) override; + + void addConsoleMessage(jsi::Runtime& runtime, ConsoleMessage message) + override; + + private: + std::string engineDescription_; +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/PageAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp similarity index 72% rename from packages/react-native/ReactCommon/jsinspector-modern/PageAgent.cpp rename to packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp index 92eea3a21246ed..e8171ec625e52a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/PageAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp @@ -5,11 +5,13 @@ * LICENSE file in the root directory of this source tree. */ +#include "CdpJson.h" + #include #include +#include +#include #include -#include -#include #include @@ -27,19 +29,19 @@ namespace facebook::react::jsinspector_modern { static constexpr auto kModernCDPBackendNotice = ANSI_COLOR_BG_YELLOW ANSI_WEIGHT_BOLD "NOTE:" ANSI_WEIGHT_RESET " You are using the " ANSI_STYLE_ITALIC - "modern" ANSI_STYLE_RESET " CDP backend for React Native (PageTarget)."sv; + "modern" ANSI_STYLE_RESET " CDP backend for React Native (HostTarget)."sv; -PageAgent::PageAgent( +HostAgent::HostAgent( FrontendChannel frontendChannel, - PageTargetController& targetController, - PageTarget::SessionMetadata sessionMetadata, + HostTargetController& targetController, + HostTarget::SessionMetadata sessionMetadata, SessionState& sessionState) : frontendChannel_(frontendChannel), targetController_(targetController), sessionMetadata_(std::move(sessionMetadata)), sessionState_(sessionState) {} -void PageAgent::handleRequest(const cdp::PreparsedRequest& req) { +void HostAgent::handleRequest(const cdp::PreparsedRequest& req) { bool shouldSendOKResponse = false; bool isFinishedHandlingRequest = false; @@ -72,6 +74,16 @@ void PageAgent::handleRequest(const cdp::PreparsedRequest& req) { } else if (req.method == "Runtime.disable") { sessionState_.isRuntimeDomainEnabled = false; + shouldSendOKResponse = true; + isFinishedHandlingRequest = false; + } else if (req.method == "Debugger.enable") { + sessionState_.isDebuggerDomainEnabled = true; + + shouldSendOKResponse = true; + isFinishedHandlingRequest = false; + } else if (req.method == "Debugger.disable") { + sessionState_.isDebuggerDomainEnabled = false; + shouldSendOKResponse = true; isFinishedHandlingRequest = false; } @@ -98,36 +110,30 @@ void PageAgent::handleRequest(const cdp::PreparsedRequest& req) { } if (shouldSendOKResponse) { - folly::dynamic res = folly::dynamic::object("id", req.id)( - "result", folly::dynamic::object()); - std::string json = folly::toJson(res); - frontendChannel_(json); + frontendChannel_(cdp::jsonResult(req.id)); return; } - folly::dynamic res = folly::dynamic::object("id", req.id)( - "error", - folly::dynamic::object("code", -32601)( - "message", req.method + " not implemented yet")); - std::string json = folly::toJson(res); - frontendChannel_(json); + frontendChannel_(cdp::jsonError( + req.id, + cdp::ErrorCode::MethodNotFound, + req.method + " not implemented yet")); } -void PageAgent::sendInfoLogEntry(std::string_view text) { - frontendChannel_( - folly::toJson(folly::dynamic::object("method", "Log.entryAdded")( - "params", +void HostAgent::sendInfoLogEntry(std::string_view text) { + frontendChannel_(cdp::jsonNotification( + "Log.entryAdded", + folly::dynamic::object( + "entry", folly::dynamic::object( - "entry", - folly::dynamic::object( - "timestamp", - duration_cast( - system_clock::now().time_since_epoch()) - .count())("source", "other")( - "level", "info")("text", text))))); + "timestamp", + duration_cast( + system_clock::now().time_since_epoch()) + .count())("source", "other")( + "level", "info")("text", text)))); } -void PageAgent::setCurrentInstanceAgent( +void HostAgent::setCurrentInstanceAgent( std::shared_ptr instanceAgent) { auto previousInstanceAgent = std::move(instanceAgent_); instanceAgent_ = std::move(instanceAgent); @@ -140,9 +146,7 @@ void PageAgent::setCurrentInstanceAgent( // Because we can only have a single instance, we can report all contexts // as cleared. - folly::dynamic contextsCleared = - folly::dynamic::object("method", "Runtime.executionContextsCleared"); - frontendChannel_(folly::toJson(contextsCleared)); + frontendChannel_(cdp::jsonNotification("Runtime.executionContextsCleared")); } if (instanceAgent_) { // TODO: Send Runtime.executionContextCreated here - at the moment we expect diff --git a/packages/react-native/ReactCommon/jsinspector-modern/PageAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h similarity index 80% rename from packages/react-native/ReactCommon/jsinspector-modern/PageAgent.h rename to packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h index 30f540abfcfffb..aec355bc3ce284 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/PageAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h @@ -7,44 +7,43 @@ #pragma once -#include "PageTarget.h" +#include "HostTarget.h" #include "SessionState.h" #include #include -#include #include #include namespace facebook::react::jsinspector_modern { -class PageTarget; +class HostTarget; class InstanceAgent; class InstanceTarget; /** * An Agent that handles requests from the Chrome DevTools Protocol for the - * given page. + * given Host. * The constructor, destructor and all public methods must be called on the - * same thread, which is also the thread where the associated PageTarget is + * same thread, which is also the thread where the associated HostTarget is * constructed and managed. */ -class PageAgent final { +class HostAgent final { public: /** * \param frontendChannel A channel used to send responses and events to the * frontend. - * \param targetController An interface to the PageTarget that this agent is + * \param targetController An interface to the HostTarget that this agent is * attached to. The caller is responsible for ensuring that the - * PageTargetDelegate and underlying PageTarget both outlive the agent. + * HostTargetDelegate and underlying HostTarget both outlive the agent. * \param sessionMetadata Metadata about the session that created this agent. * \param sessionState The state of the session that created this agent. */ - PageAgent( + HostAgent( FrontendChannel frontendChannel, - PageTargetController& targetController, - PageTarget::SessionMetadata sessionMetadata, + HostTargetController& targetController, + HostTarget::SessionMetadata sessionMetadata, SessionState& sessionState); /** @@ -70,13 +69,13 @@ class PageAgent final { * DevTools, the message will appear in the Console tab along with regular * console messages. The difference between Log.entryAdded and * Runtime.consoleAPICalled is that the latter requires an execution context - * ID, which does not exist at the Page level. + * ID, which does not exist at the Host level. */ void sendInfoLogEntry(std::string_view text); FrontendChannel frontendChannel_; - PageTargetController& targetController_; - const PageTarget::SessionMetadata sessionMetadata_; + HostTargetController& targetController_; + const HostTarget::SessionMetadata sessionMetadata_; std::shared_ptr instanceAgent_; /** diff --git a/packages/react-native/ReactCommon/jsinspector-modern/PageTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp similarity index 59% rename from packages/react-native/ReactCommon/jsinspector-modern/PageTarget.cpp rename to packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp index 86db8b8f400506..2bbb8d78e74b00 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/PageTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp @@ -5,12 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -#include "PageTarget.h" +#include "HostTarget.h" +#include "CdpJson.h" +#include "HostAgent.h" #include "InspectorInterfaces.h" #include "InspectorUtilities.h" #include "InstanceTarget.h" -#include "PageAgent.h" -#include "Parsing.h" #include "SessionState.h" #include @@ -21,15 +21,15 @@ namespace facebook::react::jsinspector_modern { /** - * A Session connected to a PageTarget, passing CDP messages to and from a - * PageAgent which it owns. + * A Session connected to a HostTarget, passing CDP messages to and from a + * HostAgent which it owns. */ -class PageTargetSession { +class HostTargetSession { public: - explicit PageTargetSession( + explicit HostTargetSession( std::unique_ptr remote, - PageTargetController& targetController, - PageTarget::SessionMetadata sessionMetadata) + HostTargetController& targetController, + HostTarget::SessionMetadata sessionMetadata) : remote_(std::make_shared(std::move(remote))), frontendChannel_( [remoteWeak = std::weak_ptr(remote_)](std::string_view message) { @@ -37,7 +37,7 @@ class PageTargetSession { remote->onMessage(std::string(message)); } }), - pageAgent_( + hostAgent_( frontendChannel_, targetController, std::move(sessionMetadata), @@ -53,41 +53,38 @@ class PageTargetSession { try { request = cdp::preparse(message); } catch (const cdp::ParseError& e) { - frontendChannel_(folly::toJson(folly::dynamic::object("id", nullptr)( - "error", - folly::dynamic::object("code", -32700)("message", e.what())))); + frontendChannel_( + cdp::jsonError(std::nullopt, cdp::ErrorCode::ParseError, e.what())); return; } catch (const cdp::TypeError& e) { - frontendChannel_(folly::toJson(folly::dynamic::object("id", nullptr)( - "error", - folly::dynamic::object("code", -32600)("message", e.what())))); + frontendChannel_(cdp::jsonError( + std::nullopt, cdp::ErrorCode::InvalidRequest, e.what())); return; } // Catch exceptions that may arise from accessing dynamic params during // request handling. try { - pageAgent_.handleRequest(request); + hostAgent_.handleRequest(request); } catch (const cdp::TypeError& e) { - frontendChannel_(folly::toJson(folly::dynamic::object("id", request.id)( - "error", - folly::dynamic::object("code", -32600)("message", e.what())))); + frontendChannel_( + cdp::jsonError(request.id, cdp::ErrorCode::InvalidRequest, e.what())); return; } } /** - * Replace the current instance agent inside pageAgent_ with a new one + * Replace the current instance agent inside hostAgent_ with a new one * connected to the new InstanceTarget. * \param instance The new instance target. May be nullptr to indicate * there's no current instance. */ void setCurrentInstance(InstanceTarget* instance) { if (instance) { - pageAgent_.setCurrentInstanceAgent( + hostAgent_.setCurrentInstanceAgent( instance->createAgent(frontendChannel_, state_)); } else { - pageAgent_.setCurrentInstanceAgent(nullptr); + hostAgent_.setCurrentInstanceAgent(nullptr); } } @@ -95,26 +92,28 @@ class PageTargetSession { // Owned by this instance, but shared (weakly) with the frontend channel std::shared_ptr remote_; FrontendChannel frontendChannel_; - PageAgent pageAgent_; SessionState state_; + + // NOTE: hostAgent_ has a raw reference to state_ so must be destroyed first. + HostAgent hostAgent_; }; -std::shared_ptr PageTarget::create( - PageTargetDelegate& delegate, +std::shared_ptr HostTarget::create( + HostTargetDelegate& delegate, VoidExecutor executor) { - std::shared_ptr pageTarget{new PageTarget(delegate)}; - pageTarget->setExecutor(executor); - return pageTarget; + std::shared_ptr hostTarget{new HostTarget(delegate)}; + hostTarget->setExecutor(executor); + return hostTarget; } -PageTarget::PageTarget(PageTargetDelegate& delegate) +HostTarget::HostTarget(HostTargetDelegate& delegate) : delegate_(delegate), executionContextManager_{std::make_shared()} {} -std::unique_ptr PageTarget::connect( +std::unique_ptr HostTarget::connect( std::unique_ptr connectionToFrontend, SessionMetadata sessionMetadata) { - auto session = std::make_shared( + auto session = std::make_shared( std::move(connectionToFrontend), controller_, std::move(sessionMetadata)); session->setCurrentInstance(currentInstance_.get()); sessions_.insert(std::weak_ptr(session)); @@ -122,44 +121,44 @@ std::unique_ptr PageTarget::connect( [session](std::string message) { (*session)(message); }); } -PageTarget::~PageTarget() { - // Sessions are owned by InspectorPackagerConnection, not by PageTarget, but - // they hold a PageTarget& that we must guarantee is valid. +HostTarget::~HostTarget() { + // Sessions are owned by InspectorPackagerConnection, not by HostTarget, but + // they hold a HostTarget& that we must guarantee is valid. assert( sessions_.empty() && - "PageTargetSession objects must be destroyed before their PageTarget. Did you call getInspectorInstance().removePage()?"); + "HostTargetSession objects must be destroyed before their HostTarget. Did you call getInspectorInstance().removePage()?"); } -PageTargetDelegate::~PageTargetDelegate() {} +HostTargetDelegate::~HostTargetDelegate() {} -InstanceTarget& PageTarget::registerInstance(InstanceTargetDelegate& delegate) { +InstanceTarget& HostTarget::registerInstance(InstanceTargetDelegate& delegate) { assert(!currentInstance_ && "Only one instance allowed"); currentInstance_ = InstanceTarget::create( executionContextManager_, delegate, makeVoidExecutor(executorFromThis())); sessions_.forEach( - [currentInstance = &*currentInstance_](PageTargetSession& session) { + [currentInstance = &*currentInstance_](HostTargetSession& session) { session.setCurrentInstance(currentInstance); }); return *currentInstance_; } -void PageTarget::unregisterInstance(InstanceTarget& instance) { +void HostTarget::unregisterInstance(InstanceTarget& instance) { assert( currentInstance_ && currentInstance_.get() == &instance && "Invalid unregistration"); sessions_.forEach( - [](PageTargetSession& session) { session.setCurrentInstance(nullptr); }); + [](HostTargetSession& session) { session.setCurrentInstance(nullptr); }); currentInstance_.reset(); } -PageTargetController::PageTargetController(PageTarget& target) +HostTargetController::HostTargetController(HostTarget& target) : target_(target) {} -PageTargetDelegate& PageTargetController::getDelegate() { +HostTargetDelegate& HostTargetController::getDelegate() { return target_.getDelegate(); } -bool PageTargetController::hasInstance() const { +bool HostTargetController::hasInstance() const { return target_.hasInstance(); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/PageTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h similarity index 62% rename from packages/react-native/ReactCommon/jsinspector-modern/PageTarget.h rename to packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h index d48a6a7d39eff3..cb04ee5f3bb248 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/PageTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h @@ -31,22 +31,22 @@ namespace facebook::react::jsinspector_modern { -class PageTargetSession; -class PageAgent; -class PageTarget; +class HostTargetSession; +class HostAgent; +class HostTarget; /** - * Receives events from a PageTarget. This is a shared interface that each + * Receives events from a HostTarget. This is a shared interface that each * React Native platform needs to implement in order to integrate with the * debugging stack. */ -class PageTargetDelegate { +class HostTargetDelegate { public: - PageTargetDelegate() = default; - PageTargetDelegate(const PageTargetDelegate&) = delete; - PageTargetDelegate(PageTargetDelegate&&) = default; - PageTargetDelegate& operator=(const PageTargetDelegate&) = delete; - PageTargetDelegate& operator=(PageTargetDelegate&&) = default; + HostTargetDelegate() = default; + HostTargetDelegate(const HostTargetDelegate&) = delete; + HostTargetDelegate(HostTargetDelegate&&) = default; + HostTargetDelegate& operator=(const HostTargetDelegate&) = delete; + HostTargetDelegate& operator=(HostTargetDelegate&&) = default; // TODO(moti): This is 1:1 the shape of the corresponding CDP message - // consider reusing typed/generated CDP interfaces when we have those. @@ -67,7 +67,7 @@ class PageTargetDelegate { } }; - virtual ~PageTargetDelegate(); + virtual ~HostTargetDelegate(); /** * Called when the debugger requests a reload of the page. This is called on @@ -78,19 +78,19 @@ class PageTargetDelegate { }; /** - * The limited interface that PageTarget exposes to its associated + * The limited interface that HostTarget exposes to its associated * sessions/agents. */ -class PageTargetController final { +class HostTargetController final { public: - explicit PageTargetController(PageTarget& target); + explicit HostTargetController(HostTarget& target); - PageTargetDelegate& getDelegate(); + HostTargetDelegate& getDelegate(); bool hasInstance() const; private: - PageTarget& target_; + HostTarget& target_; }; /** @@ -98,37 +98,37 @@ class PageTargetController final { * "Host" in React Native's architecture - the entity that manages the * lifecycle of a React Instance. */ -class JSINSPECTOR_EXPORT PageTarget - : public EnableExecutorFromThis { +class JSINSPECTOR_EXPORT HostTarget + : public EnableExecutorFromThis { public: struct SessionMetadata { std::optional integrationName; }; /** - * Constructs a new PageTarget. - * \param delegate The PageTargetDelegate that will - * receive events from this PageTarget. The caller is responsible for ensuring - * that the PageTargetDelegate outlives this object. + * Constructs a new HostTarget. + * \param delegate The HostTargetDelegate that will + * receive events from this HostTarget. The caller is responsible for ensuring + * that the HostTargetDelegate outlives this object. * \param executor An executor that may be used to call methods on this - * PageTarget while it exists. \c create additionally guarantees that the - * executor will not be called after the PageTarget is destroyed. + * HostTarget while it exists. \c create additionally guarantees that the + * executor will not be called after the HostTarget is destroyed. */ - static std::shared_ptr create( - PageTargetDelegate& delegate, + static std::shared_ptr create( + HostTargetDelegate& delegate, VoidExecutor executor); - PageTarget(const PageTarget&) = delete; - PageTarget(PageTarget&&) = delete; - PageTarget& operator=(const PageTarget&) = delete; - PageTarget& operator=(PageTarget&&) = delete; - ~PageTarget(); + HostTarget(const HostTarget&) = delete; + HostTarget(HostTarget&&) = delete; + HostTarget& operator=(const HostTarget&) = delete; + HostTarget& operator=(HostTarget&&) = delete; + ~HostTarget(); /** - * Creates a new Session connected to this PageTarget, wrapped in an + * Creates a new Session connected to this HostTarget, wrapped in an * interface which is compatible with \c IInspector::addPage. - * The caller is responsible for destroying the connection before PageTarget - * is destroyed, on the same thread where PageTarget's constructor and + * The caller is responsible for destroying the connection before HostTarget + * is destroyed, on the same thread where HostTarget's constructor and * destructor execute. */ std::unique_ptr connect( @@ -136,19 +136,19 @@ class JSINSPECTOR_EXPORT PageTarget SessionMetadata sessionMetadata = {}); /** - * Registers an instance with this PageTarget. + * Registers an instance with this HostTarget. * \param delegate The InstanceTargetDelegate that will receive events from * this InstanceTarget. The caller is responsible for ensuring that the * InstanceTargetDelegate outlives this object. * \return An InstanceTarget reference representing the newly created * instance. This reference is only valid until unregisterInstance is called - * (or the PageTarget is destroyed). \pre There isn't currently an instance - * registered with this PageTarget. + * (or the HostTarget is destroyed). \pre There isn't currently an instance + * registered with this HostTarget. */ InstanceTarget& registerInstance(InstanceTargetDelegate& delegate); /** - * Unregisters an instance from this PageTarget. + * Unregisters an instance from this HostTarget. * \param instance The InstanceTarget reference previously returned by * registerInstance. */ @@ -156,24 +156,24 @@ class JSINSPECTOR_EXPORT PageTarget private: /** - * Constructs a new PageTarget. + * Constructs a new HostTarget. * The caller must call setExecutor immediately afterwards. - * \param delegate The PageTargetDelegate that will - * receive events from this PageTarget. The caller is responsible for ensuring - * that the PageTargetDelegate outlives this object. + * \param delegate The HostTargetDelegate that will + * receive events from this HostTarget. The caller is responsible for ensuring + * that the HostTargetDelegate outlives this object. */ - PageTarget(PageTargetDelegate& delegate); + HostTarget(HostTargetDelegate& delegate); - PageTargetDelegate& delegate_; - WeakList sessions_; - PageTargetController controller_{*this}; + HostTargetDelegate& delegate_; + WeakList sessions_; + HostTargetController controller_{*this}; // executionContextManager_ is a shared_ptr to guarantee its validity while // the InstanceTarget is alive (just in case the InstanceTarget ends up - // briefly outliving the PageTarget, which it generally shouldn't). + // briefly outliving the HostTarget, which it generally shouldn't). std::shared_ptr executionContextManager_; std::shared_ptr currentInstance_{nullptr}; - inline PageTargetDelegate& getDelegate() { + inline HostTargetDelegate& getDelegate() { return delegate_; } @@ -181,10 +181,10 @@ class JSINSPECTOR_EXPORT PageTarget return currentInstance_ != nullptr; } - // Necessary to allow PageAgent to access PageTarget's internals in a - // controlled way (i.e. only PageTargetController gets friend access, while - // PageAgent itself doesn't). - friend class PageTargetController; + // Necessary to allow HostAgent to access HostTarget's internals in a + // controlled way (i.e. only HostTargetController gets friend access, while + // HostAgent itself doesn't). + friend class HostTargetController; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.cpp index b0e3b4fb17b549..caf66b8fded272 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.cpp @@ -17,42 +17,45 @@ InspectorFlags& InspectorFlags::getInstance() { return instance; } -InspectorFlags::InspectorFlags() - : enableModernCDPRegistry_( - ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry()), - enableCxxInspectorPackagerConnection_( - ReactNativeFeatureFlags:: - inspectorEnableCxxInspectorPackagerConnection()) {} - bool InspectorFlags::getEnableModernCDPRegistry() const { - assertFlagsMatchUpstream(); - return enableModernCDPRegistry_; + return loadFlagsAndAssertUnchanged().enableModernCDPRegistry; } bool InspectorFlags::getEnableCxxInspectorPackagerConnection() const { - assertFlagsMatchUpstream(); - return enableCxxInspectorPackagerConnection_ || + auto& values = loadFlagsAndAssertUnchanged(); + + return values.enableCxxInspectorPackagerConnection || // If we are using the modern CDP registry, then we must also use the C++ // InspectorPackagerConnection implementation. - enableModernCDPRegistry_; + values.enableModernCDPRegistry; } -void InspectorFlags::assertFlagsMatchUpstream() const { - if (inconsistentFlagsStateLogged_) { - return; - } +void InspectorFlags::dangerouslyResetFlags() { + *this = InspectorFlags{}; +} - if (enableModernCDPRegistry_ != - ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry() || - enableCxxInspectorPackagerConnection_ != - ReactNativeFeatureFlags:: - inspectorEnableCxxInspectorPackagerConnection()) { - LOG(ERROR) - << "[InspectorFlags] Error: One or more ReactNativeFeatureFlags values " - << "have changed during the global app lifetime. This may lead to " - << "inconsistent inspector behaviour. Please quit and restart the app."; - inconsistentFlagsStateLogged_ = true; +const InspectorFlags::Values& InspectorFlags::loadFlagsAndAssertUnchanged() + const { + InspectorFlags::Values newValues = { + .enableCxxInspectorPackagerConnection = ReactNativeFeatureFlags:: + inspectorEnableCxxInspectorPackagerConnection(), + .enableModernCDPRegistry = + ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry(), + }; + + if (cachedValues_.has_value() && !inconsistentFlagsStateLogged_) { + if (cachedValues_ != newValues) { + LOG(ERROR) + << "[InspectorFlags] Error: One or more ReactNativeFeatureFlags values " + << "have changed during the global app lifetime. This may lead to " + << "inconsistent inspector behaviour. Please quit and restart the app."; + inconsistentFlagsStateLogged_ = true; + } } + + cachedValues_ = newValues; + + return cachedValues_.value(); } } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h index 605fad31723ad8..5ed464525d35a9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h @@ -30,17 +30,28 @@ class InspectorFlags { */ bool getEnableCxxInspectorPackagerConnection() const; + /** + * Reset flags to their upstream values. The caller must ensure any resources + * that have read previous flag values have been cleaned up. + */ + void dangerouslyResetFlags(); + private: - InspectorFlags(); + struct Values { + bool enableCxxInspectorPackagerConnection; + bool enableModernCDPRegistry; + bool operator==(const Values&) const = default; + }; + + InspectorFlags() = default; InspectorFlags(const InspectorFlags&) = delete; - InspectorFlags& operator=(const InspectorFlags&) = delete; + InspectorFlags& operator=(const InspectorFlags&) = default; ~InspectorFlags() = default; - const bool enableModernCDPRegistry_; - const bool enableCxxInspectorPackagerConnection_; + mutable std::optional cachedValues_; + mutable bool inconsistentFlagsStateLogged_{false}; - mutable bool inconsistentFlagsStateLogged_; - void assertFlagsMatchUpstream() const; + const Values& loadFlagsAndAssertUnchanged() const; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp index fdb57b0b4c7dcc..a68d82a479b222 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp @@ -6,6 +6,7 @@ */ #include +#include "CdpJson.h" #include "RuntimeTarget.h" namespace facebook::react::jsinspector_modern { @@ -49,9 +50,8 @@ void InstanceAgent::setCurrentRuntime(RuntimeTarget* runtimeTarget) { if (previousContext.uniqueId.has_value()) { params["executionContextUniqueId"] = *previousContext.uniqueId; } - folly::dynamic contextDestroyed = folly::dynamic::object( - "method", "Runtime.executionContextDestroyed")("params", params); - frontendChannel_(folly::toJson(contextDestroyed)); + frontendChannel_( + cdp::jsonNotification("Runtime.executionContextDestroyed", params)); } maybeSendExecutionContextCreatedNotification(); } @@ -66,9 +66,8 @@ void InstanceAgent::maybeSendExecutionContextCreatedNotification() { if (newContext.uniqueId.has_value()) { params["uniqueId"] = *newContext.uniqueId; } - folly::dynamic contextCreated = folly::dynamic::object( - "method", "Runtime.executionContextCreated")("params", params); - frontendChannel_(folly::toJson(contextCreated)); + frontendChannel_( + cdp::jsonNotification("Runtime.executionContextCreated", params)); } } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h index d33670275663de..167c4c2205bea9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h @@ -7,11 +7,11 @@ #pragma once +#include "CdpJson.h" #include "RuntimeTarget.h" #include "SessionState.h" #include -#include #include #include @@ -47,7 +47,7 @@ class InstanceAgent final { bool handleRequest(const cdp::PreparsedRequest& req); /** - * Replace the current RuntimeAgent pageAgent_ with a new one + * Replace the current RuntimeAgent hostAgent_ with a new one * connected to the new RuntimeTarget. * \param runtime The new runtime target. May be nullptr to indicate * there's no current debuggable runtime. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp index e128c689ed6d26..c8df28bce10b60 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp @@ -47,7 +47,7 @@ InstanceTarget::~InstanceTarget() { // they hold an InstanceTarget& that we must guarantee is valid. assert( agents_.empty() && - "InstanceAgent objects must be destroyed before their InstanceTarget. Did you call PageTarget::unregisterInstance()?"); + "InstanceAgent objects must be destroyed before their InstanceTarget. Did you call HostTarget::unregisterInstance()?"); } RuntimeTarget& InstanceTarget::registerRuntime( diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h index 101433c8b2779f..e9ec51b12db339 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h @@ -70,9 +70,22 @@ class InstanceTarget : public EnableExecutorFromThis { FrontendChannel channel, SessionState& sessionState); + /** + * Registers a JS runtime with this InstanceTarget. \returns a reference to + * the created RuntimeTarget, which is owned by the \c InstanceTarget. All the + * requirements of \c RuntimeTarget::create must be met. + */ RuntimeTarget& registerRuntime( RuntimeTargetDelegate& delegate, RuntimeExecutor executor); + + /** + * Unregisters a JS runtime from this InstanceTarget. This destroys the \c + * RuntimeTarget, and it is no longer valid to use. Note that the \c + * RuntimeTargetDelegate& initially provided to \c registerRuntime may + * continue to be used as long as JavaScript execution continues in the + * runtime. + */ void unregisterRuntime(RuntimeTarget& runtime); private: diff --git a/packages/react-native/ReactCommon/jsinspector-modern/Parsing.cpp b/packages/react-native/ReactCommon/jsinspector-modern/Parsing.cpp deleted file mode 100644 index 99b233aa9ca728..00000000000000 --- a/packages/react-native/ReactCommon/jsinspector-modern/Parsing.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include -#include - -namespace facebook::react::jsinspector_modern::cdp { - -PreparsedRequest preparse(std::string_view message) { - folly::dynamic parsed = folly::parseJson(message); - return PreparsedRequest{ - .id = parsed["id"].getInt(), - .method = parsed["method"].getString(), - .params = parsed.count("params") ? parsed["params"] : nullptr}; -} - -std::string PreparsedRequest::toJson() const { - folly::dynamic obj = folly::dynamic::object; - obj["id"] = id; - obj["method"] = method; - if (params != nullptr) { - obj["params"] = params; - } - return folly::toJson(obj); -} - -} // namespace facebook::react::jsinspector_modern::cdp diff --git a/packages/react-native/ReactCommon/jsinspector-modern/Parsing.h b/packages/react-native/ReactCommon/jsinspector-modern/Parsing.h deleted file mode 100644 index bd446fb1971448..00000000000000 --- a/packages/react-native/ReactCommon/jsinspector-modern/Parsing.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react::jsinspector_modern { - -namespace cdp { -using RequestId = long long; - -/** - * An incoming CDP request that has been parsed into a more usable form. - */ -struct PreparsedRequest { - public: - /** - * The ID of the request. - */ - RequestId id; - - /** - * The name of the method being invoked. - */ - std::string method; - - /** - * The parameters passed to the method, if any. - */ - folly::dynamic params; - - /** - * Equality operator, useful for unit tests - */ - inline bool operator==(const PreparsedRequest& rhs) const { - return id == rhs.id && method == rhs.method && params == rhs.params; - } - - std::string toJson() const; -}; - -/** - * Parse a JSON-encoded CDP request into its constituent parts. - * \throws ParseError If the input cannot be parsed. - * \throws TypeError If the input does not conform to the expected format. - */ -PreparsedRequest preparse(std::string_view message); - -/** - * A type error that may be thrown while preparsing a request, or while - * accessing dynamic params on a request. - */ -using TypeError = folly::TypeError; - -/** - * A parse error that may be thrown while preparsing a request. - */ -using ParseError = folly::json::parse_error; -} // namespace cdp - -} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ReactCdp.h b/packages/react-native/ReactCommon/jsinspector-modern/ReactCdp.h index c23e6a73db32d0..23c9d3eaeeea52 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ReactCdp.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ReactCdp.h @@ -8,9 +8,9 @@ #pragma once #include -#include +#include +#include #include -#include #include #include #include diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp index 05071cfe4b88af..0172ff47d13355 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp @@ -35,28 +35,27 @@ bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { ExecutionContextSelector contextSelector = ExecutionContextSelector::all(); // TODO: Eventually, move execution context targeting out of RuntimeAgent. - // Right now, there's only ever one context (Runtime) in a Page, so we can + // Right now, there's only ever one context (Runtime) in a Host, so we can // handle it here for simplicity, and use session state to propagate // bindings to the next RuntimeAgent. if (req.params.count("executionContextId")) { auto executionContextId = req.params["executionContextId"].getInt(); if (executionContextId < (int64_t)std::numeric_limits::min() || executionContextId > (int64_t)std::numeric_limits::max()) { - frontendChannel_(folly::toJson(folly::dynamic::object("id", req.id)( - "error", - folly::dynamic::object("code", -32602)( - "message", "Invalid execution context id")))); + frontendChannel_(cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidParams, + "Invalid execution context id")); return true; } contextSelector = ExecutionContextSelector::byId((int32_t)executionContextId); if (req.params.count("executionContextName")) { - frontendChannel_(folly::toJson(folly::dynamic::object("id", req.id)( - "error", - folly::dynamic::object("code", -32602)( - "message", - "executionContextName is mutually exclusive with executionContextId")))); + frontendChannel_(cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidParams, + "executionContextName is mutually exclusive with executionContextId")); return true; } } else if (req.params.count("executionContextName")) { @@ -68,10 +67,7 @@ bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { } sessionState_.subscribedBindings[bindingName].insert(contextSelector); - folly::dynamic res = folly::dynamic::object("id", req.id)( - "result", folly::dynamic::object()); - std::string json = folly::toJson(res); - frontendChannel_(json); + frontendChannel_(cdp::jsonResult(req.id)); return true; } @@ -83,10 +79,7 @@ bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { // if the subscription is targeted by context name. sessionState_.subscribedBindings.erase(req.params["name"].getString()); - folly::dynamic res = folly::dynamic::object("id", req.id)( - "result", folly::dynamic::object()); - std::string json = folly::toJson(res); - frontendChannel_(json); + frontendChannel_(cdp::jsonResult(req.id)); return true; } @@ -113,12 +106,11 @@ void RuntimeAgent::notifyBindingCalled( return; } - frontendChannel_( - folly::toJson(folly::dynamic::object("method", "Runtime.bindingCalled")( - "params", - folly::dynamic::object( - "executionContextId", executionContextDescription_.id)( - "name", bindingName)("payload", payload)))); + frontendChannel_(cdp::jsonNotification( + "Runtime.bindingCalled", + folly::dynamic::object( + "executionContextId", executionContextDescription_.id)( + "name", bindingName)("payload", payload))); } RuntimeAgent::ExportedState RuntimeAgent::getExportedState() { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h index 0310f2a9165e25..4cc01bc1bd0d9a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h @@ -7,12 +7,11 @@ #pragma once +#include "CdpJson.h" #include "InspectorInterfaces.h" #include "RuntimeAgentDelegate.h" #include "RuntimeTarget.h" -#include - namespace facebook::react::jsinspector_modern { class RuntimeTargetController; @@ -36,7 +35,7 @@ class RuntimeAgent final { * \param executionContextDescription A description of the execution context * represented by this runtime. This is used for disambiguating the * source/destination of CDP messages when there are multiple runtimes - * (concurrently or over the life of a Page). + * (concurrently or over the life of a Host). * \param sessionState The state of the session that created this agent. * \param delegate The RuntimeAgentDelegate providing engine-specific * CDP functionality. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h index d7042d60d48c24..d5e62d1b576c2c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h @@ -7,7 +7,7 @@ #pragma once -#include +#include "CdpJson.h" namespace facebook::react::jsinspector_modern { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.cpp index c9a8be6f597480..ecee63a5d5f571 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.cpp @@ -21,6 +21,7 @@ std::shared_ptr RuntimeTarget::create( std::shared_ptr runtimeTarget{ new RuntimeTarget(executionContextDescription, delegate, jsExecutor)}; runtimeTarget->setExecutor(selfExecutor); + runtimeTarget->installGlobals(); return runtimeTarget; } @@ -32,6 +33,11 @@ RuntimeTarget::RuntimeTarget( delegate_(delegate), jsExecutor_(jsExecutor) {} +void RuntimeTarget::installGlobals() { + // NOTE: RuntimeTarget::installConsoleHandler is in RuntimeTargetConsole.cpp + installConsoleHandler(); +} + std::shared_ptr RuntimeTarget::createAgent( FrontendChannel channel, SessionState& sessionState) { @@ -46,7 +52,8 @@ std::shared_ptr RuntimeTarget::createAgent( channel, sessionState, std::move(runtimeAgentState.delegateState), - executionContextDescription_)); + executionContextDescription_, + jsExecutor_)); agents_.insert(runtimeAgent); return runtimeAgent; } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h index 20c42cb2644663..a5f42b8fa1f921 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h @@ -9,6 +9,7 @@ #include +#include "ConsoleMessage.h" #include "ExecutionContext.h" #include "InspectorInterfaces.h" #include "RuntimeAgent.h" @@ -49,7 +50,23 @@ class RuntimeTargetDelegate { SessionState& sessionState, std::unique_ptr previouslyExportedState, - const ExecutionContextDescription& executionContextDescription) = 0; + const ExecutionContextDescription& executionContextDescription, + RuntimeExecutor runtimeExecutor) = 0; + + /** + * Called when the runtime intercepts a console API call. The target delegate + * should notify the frontend (via its agent delegates) of the message, and + * perform any buffering required for logging the message later (in the + * existing and/or new sessions). + * + * \note The method is called on the JS thread, and receives a valid reference + * to the current \c jsi::Runtime. The callee MAY use its own intrinsic + * Runtime reference, if it has one, without checking it for equivalence with + * the one provided here. + */ + virtual void addConsoleMessage( + jsi::Runtime& runtime, + ConsoleMessage message) = 0; }; /** @@ -77,15 +94,15 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis { public: /** - * Constructs a new RuntimeTarget. The caller must call setExecutor - * immediately afterwards. * \param executionContextDescription A description of the execution context * represented by this runtime. This is used for disambiguating the * source/destination of CDP messages when there are multiple runtimes - * (concurrently or over the life of a Page). + * (concurrently or over the life of a Host). * \param delegate The object that will receive events from this target. The - * caller is responsible for - * ensuring that the delegate outlives this object. + * caller is responsible for ensuring that the delegate outlives this object + * AND that it remains valid for as long as the JS runtime is executing any + * code, even if the \c RuntimeTarget itself is destroyed. The delegate SHOULD + * be the object that owns the underlying jsi::Runtime, if any. * \param jsExecutor A RuntimeExecutor that can be used to schedule work on * the JS runtime's thread. The executor's queue should be empty when * RuntimeTarget is constructed (i.e. anything scheduled during the @@ -109,9 +126,9 @@ class JSINSPECTOR_EXPORT RuntimeTarget /** * Create a new RuntimeAgent that can be used to debug the underlying JS VM. * The agent will be destroyed when the session ends, the containing - * InstanceTarget is unregistered from its PageTarget, or the RuntimeAgent is + * InstanceTarget is unregistered from its HostTarget, or the RuntimeAgent is * unregistered from its InstanceTarget (whichever happens first). - * \param channel A thread-safe channel for sending CDP messages to the + * \param channel A thread-safe channel forHostTargetDP messages to the * frontend. * \returns The new agent, or nullptr if the runtime is not debuggable. */ @@ -126,10 +143,12 @@ class JSINSPECTOR_EXPORT RuntimeTarget * \param executionContextDescription A description of the execution context * represented by this runtime. This is used for disambiguating the * source/destination of CDP messages when there are multiple runtimes - * (concurrently or over the life of a Page). - * \param delegate The object that will receive events from this target. - * The caller is responsible for ensuring that the delegate outlives this - * object. + * (concurrently or over the life of a Host). + * \param delegate The object that will receive events from this target. The + * caller is responsible for ensuring that the delegate outlives this object + * AND that it remains valid for as long as the JS runtime is executing any + * code, even if the \c RuntimeTarget itself is destroyed. The delegate SHOULD + * be the object that owns the underlying jsi::Runtime, if any. * \param jsExecutor A RuntimeExecutor that can be used to schedule work on * the JS runtime's thread. The executor's queue should be empty when * RuntimeTarget is constructed (i.e. anything scheduled during the @@ -153,6 +172,17 @@ class JSINSPECTOR_EXPORT RuntimeTarget */ void installBindingHandler(const std::string& bindingName); + /** + * Installs any global values we want to expose to framework/user JavaScript + * code. + */ + void installGlobals(); + + /** + * Install the console API handler. + */ + void installConsoleHandler(); + // Necessary to allow RuntimeAgent to access RuntimeTarget's internals in a // controlled way (i.e. only RuntimeTargetController gets friend access, while // RuntimeAgent itself doesn't). diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp new file mode 100644 index 00000000000000..6ac0b02fad9fc4 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp @@ -0,0 +1,447 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +using namespace facebook::jsi; +using namespace std::string_literals; + +namespace facebook::react::jsinspector_modern { + +namespace { + +struct ConsoleState { + /** + * https://console.spec.whatwg.org/#counting + */ + std::unordered_map countMap; + + /** + * https://console.spec.whatwg.org/#timing + */ + std::unordered_map timerTable; + + ConsoleState() = default; + ConsoleState(const ConsoleState&) = delete; + ConsoleState& operator=(const ConsoleState&) = delete; + ConsoleState(ConsoleState&&) = delete; + ConsoleState& operator=(ConsoleState&&) = delete; + ~ConsoleState() = default; +}; + +/** + * `console` methods that have no behaviour other than emitting a + * Runtime.consoleAPICalled message. + */ +constexpr const std::pair + kForwardingConsoleMethods[] = { + {"clear", ConsoleAPIType::kClear}, + {"debug", ConsoleAPIType::kDebug}, + {"dir", ConsoleAPIType::kDir}, + {"dirxml", ConsoleAPIType::kDirXML}, + {"error", ConsoleAPIType::kError}, + {"group", ConsoleAPIType::kStartGroup}, + {"groupCollapsed", ConsoleAPIType::kStartGroupCollapsed}, + {"groupEnd", ConsoleAPIType::kEndGroup}, + {"info", ConsoleAPIType::kInfo}, + {"log", ConsoleAPIType::kLog}, + {"table", ConsoleAPIType::kTable}, + {"trace", ConsoleAPIType::kTrace}, + {"warn", ConsoleAPIType::kWarning}, +}; + +/** + * JS `Object.create()` + */ +jsi::Object objectCreate(jsi::Runtime& runtime, jsi::Value prototype) { + auto objectGlobal = runtime.global().getPropertyAsObject(runtime, "Object"); + auto createFn = objectGlobal.getPropertyAsFunction(runtime, "create"); + return createFn.callWithThis(runtime, objectGlobal, prototype) + .getObject(runtime); +} + +bool toBoolean(jsi::Runtime& runtime, const jsi::Value& val) { + // Based on Operations.cpp:toBoolean in the Hermes VM. + if (val.isUndefined() || val.isNull()) { + return false; + } + if (val.isBool()) { + return val.getBool(); + } + if (val.isNumber()) { + double m = val.getNumber(); + return m != 0 && !std::isnan(m); + } + if (val.isSymbol() || val.isObject()) { + return true; + } + if (val.isString()) { + std::string s = val.getString(runtime).utf8(runtime); + return !s.empty(); + } + assert(false && "All cases should be covered"); + return false; +} + +/** + * Get the current time in milliseconds as a double. + */ +double getTimestampMs() { + return std::chrono::duration_cast>( + std::chrono::system_clock::now().time_since_epoch()) + .count(); +} + +} // namespace + +void RuntimeTarget::installConsoleHandler() { + jsExecutor_([selfWeak = weak_from_this(), + selfExecutor = executorFromThis()](jsi::Runtime& runtime) { + jsi::Value consolePrototype = jsi::Value::null(); + auto originalConsoleVal = runtime.global().getProperty(runtime, "console"); + std::shared_ptr originalConsole; + if (originalConsoleVal.isObject()) { + originalConsole = + std::make_shared(originalConsoleVal.getObject(runtime)); + consolePrototype = std::move(originalConsoleVal); + } else { + consolePrototype = jsi::Object(runtime); + } + auto console = objectCreate(runtime, std::move(consolePrototype)); + auto state = std::make_shared(); + + /** + * An executor that runs synchronously and provides a safe reference to our + * RuntimeTargetDelegate for use on the JS thread. + * \see RuntimeTargetDelegate for information on which methods are safe to + * call on the JS thread. + * \warning The callback will not run if the RuntimeTarget has been + * destroyed. + */ + auto delegateExecutorSync = [selfWeak, selfExecutor](auto&& func) { + if (auto self = selfWeak.lock()) { + // Q: Why is it safe to use self->delegate_ here? + // A: Because the caller of InspectorTarget::registerRuntime + // is explicitly required to guarantee that the delegate not + // only outlives the target, but also outlives all JS code + // execution that occurs on the JS thread. + func(self->delegate_); + // To ensure we never destroy `self` on the JS thread, send + // our shared_ptr back to the inspector thread. + selfExecutor([self = std::move(self)](auto&) { (void)self; }); + } + }; + + /** + * Call \param innerFn and forward any arguments to the original console + * method named \param methodName, if possible. + */ + auto forwardToOriginalConsole = [originalConsole, delegateExecutorSync]( + const char* methodName, + auto&& innerFn) { + return [originalConsole, + delegateExecutorSync, + innerFn = std::forward(innerFn), + methodName]( + jsi::Runtime& runtime, + const jsi::Value& thisVal, + const jsi::Value* args, + size_t count) mutable { + jsi::Value retVal = innerFn(runtime, thisVal, args, count); + if (originalConsole) { + auto val = originalConsole->getProperty(runtime, methodName); + if (val.isObject()) { + auto obj = val.getObject(runtime); + if (obj.isFunction(runtime)) { + auto func = obj.getFunction(runtime); + func.callWithThis(runtime, *originalConsole, args, count); + } + } + } + return retVal; + }; + }; + + /** + * Install a console method with the given name and body. The body receives + * the usual JSI host function parameters plus a ConsoleState reference, a + * reference to the RuntimeTargetDelegate for sending messages to the + * client, and the timestamp of the call. After the body runs (or is skipped + * due to RuntimeTarget having been destroyed), the method of the same name + * is also called on originalConsole (if it exists). + */ + auto installConsoleMethod = + [&](const char* methodName, + std::function&& body) { + console.setProperty( + runtime, + methodName, + jsi::Function::createFromHostFunction( + runtime, + jsi::PropNameID::forAscii(runtime, methodName), + 0, + forwardToOriginalConsole( + methodName, + [body = std::move(body), state, delegateExecutorSync]( + jsi::Runtime& runtime, + const jsi::Value& /*thisVal*/, + const jsi::Value* args, + size_t count) mutable { + auto timestampMs = getTimestampMs(); + delegateExecutorSync( + [&runtime, + args, + count, + body = std::move(body), + state, + timestampMs](auto& runtimeTargetDelegate) { + body( + runtime, + args, + count, + runtimeTargetDelegate, + *state, + timestampMs); + }); + return jsi::Value::undefined(); + }))); + }; + + /** + * console.count + */ + installConsoleMethod( + "count", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& state, + auto timestampMs) { + std::string label = "default"; + if (count > 0 && !args[0].isUndefined()) { + label = args[0].toString(runtime).utf8(runtime); + } + auto it = state.countMap.find(label); + if (it == state.countMap.end()) { + it = state.countMap.insert({label, 1}).first; + } else { + it->second++; + } + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, label + ": "s + std::to_string(it->second))); + runtimeTargetDelegate.addConsoleMessage( + runtime, {timestampMs, ConsoleAPIType::kCount, std::move(vec)}); + }); + + /** + * console.countReset + */ + installConsoleMethod( + "countReset", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& state, + auto timestampMs) { + std::string label = "default"; + if (count > 0 && !args[0].isUndefined()) { + label = args[0].toString(runtime).utf8(runtime); + } + auto it = state.countMap.find(label); + if (it == state.countMap.end()) { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, "Count for '"s + label + "' does not exist")); + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, ConsoleAPIType::kWarning, std::move(vec)}); + } else { + it->second = 0; + } + }); + + /** + * console.time + */ + installConsoleMethod( + "time", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& state, + auto timestampMs) { + std::string label = "default"; + if (count > 0 && !args[0].isUndefined()) { + label = args[0].toString(runtime).utf8(runtime); + } + auto it = state.timerTable.find(label); + if (it == state.timerTable.end()) { + state.timerTable.insert({label, timestampMs}); + } else { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' already exists")); + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, ConsoleAPIType::kWarning, std::move(vec)}); + } + }); + + /** + * console.timeEnd + */ + installConsoleMethod( + "timeEnd", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& state, + auto timestampMs) { + std::string label = "default"; + if (count > 0 && !args[0].isUndefined()) { + label = args[0].toString(runtime).utf8(runtime); + } + auto it = state.timerTable.find(label); + if (it == state.timerTable.end()) { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' does not exist")); + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, ConsoleAPIType::kWarning, std::move(vec)}); + } else { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, + label + ": "s + std::to_string(timestampMs - it->second) + + " ms")); + state.timerTable.erase(it); + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, ConsoleAPIType::kTimeEnd, std::move(vec)}); + } + }); + + /** + * console.timeLog + */ + installConsoleMethod( + "timeLog", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& state, + auto timestampMs) { + std::string label = "default"; + if (count > 0 && !args[0].isUndefined()) { + label = args[0].toString(runtime).utf8(runtime); + } + auto it = state.timerTable.find(label); + if (it == state.timerTable.end()) { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' does not exist")); + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, ConsoleAPIType::kWarning, std::move(vec)}); + } else { + std::vector vec; + vec.emplace_back(jsi::String::createFromUtf8( + runtime, + label + ": "s + std::to_string(timestampMs - it->second) + + " ms")); + if (count > 1) { + for (size_t i = 1; i != count; ++i) { + vec.emplace_back(runtime, args[i]); + } + } + runtimeTargetDelegate.addConsoleMessage( + runtime, {timestampMs, ConsoleAPIType::kLog, std::move(vec)}); + } + }); + + /** + * console.assert + */ + installConsoleMethod( + "assert", + [](jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& /*state*/, + auto timestampMs) { + if (count >= 1 && toBoolean(runtime, args[0])) { + return; + } + std::deque data; + + if (count > 1) { + for (size_t i = 1; i != count; ++i) { + data.emplace_back(runtime, args[i]); + } + } + if (data.empty()) { + data.emplace_back( + jsi::String::createFromUtf8(runtime, "Assertion failed")); + } else if (data.front().isString()) { + data.front() = jsi::String::createFromUtf8( + runtime, + "Assertion failed: "s + + data.front().asString(runtime).utf8(runtime)); + } else { + data.emplace_front( + jsi::String::createFromUtf8(runtime, "Assertion failed")); + } + runtimeTargetDelegate.addConsoleMessage( + runtime, + {timestampMs, + ConsoleAPIType::kAssert, + std::vector( + make_move_iterator(data.begin()), + make_move_iterator(data.end()))}); + }); + + for (auto& [name, type] : kForwardingConsoleMethods) { + installConsoleMethod( + name, + [type = type]( + jsi::Runtime& runtime, + const jsi::Value* args, + size_t count, + RuntimeTargetDelegate& runtimeTargetDelegate, + ConsoleState& /*state*/, + auto timestampMs) { + std::vector argsVec; + for (size_t i = 0; i != count; ++i) { + argsVec.emplace_back(runtime, args[i]); + } + runtimeTargetDelegate.addConsoleMessage( + runtime, {timestampMs, type, std::move(argsVec)}); + }); + } + + runtime.global().setProperty(runtime, "console", console); + }); +} + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h index a0329cc2db7b41..6a61ff5468524e 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h @@ -20,6 +20,7 @@ namespace facebook::react::jsinspector_modern { struct SessionState { public: // TODO: Generalise this to arbitrary domains + bool isDebuggerDomainEnabled{false}; bool isLogDomainEnabled{false}; bool isRuntimeDomainEnabled{false}; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ConsoleApiTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/ConsoleApiTest.cpp new file mode 100644 index 00000000000000..326dd3a6dd635a --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ConsoleApiTest.cpp @@ -0,0 +1,571 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "JsiIntegrationTest.h" + +#include "engines/JsiIntegrationTestHermesEngineAdapter.h" +#include "prelude.js.h" + +#include + +using namespace ::testing; + +namespace facebook::react::jsinspector_modern { + +namespace { + +struct Params { + /** + * Whether to evaluate the prelude.js script (containing RN's console + * polyfill) after setting up the Runtime. + */ + bool withConsolePolyfill{false}; + + /** + * Whether to install the global nativeLoggingHook function after setting up + * the Runtime (before the prelude if any). + */ + bool withNativeLoggingHook{false}; + + /** + * Whether to enable the Runtime domain at the start of the test (and expect + * live consoleAPICalled notifications), or enable it at the *end* of the test + * (and expect buffered notifications at that point). + */ + bool runtimeEnabledAtStart{false}; +}; + +} // namespace + +/** + * A test fixture for the Console API. + */ +class ConsoleApiTest + : public JsiIntegrationPortableTest, + public WithParamInterface { + struct ExpectedConsoleApiCall { + std::string type; + std::string argsJson; + }; + + protected: + void SetUp() override { + JsiIntegrationPortableTest::SetUp(); + connect(); + if (GetParam().runtimeEnabledAtStart) { + enableRuntimeDomain(); + } + } + + void TearDown() override { + if (!GetParam().runtimeEnabledAtStart) { + enableRuntimeDomain(); + } + JsiIntegrationPortableTest::TearDown(); + } + + void expectConsoleApiCall(std::string type, std::string argsJson) { + ExpectedConsoleApiCall call{ + .type = std::move(type), .argsJson = std::move(argsJson)}; + if (runtimeEnabled_) { + expectConsoleApiCallImpl(std::move(call)); + } else { + expectedConsoleApiCalls_.emplace_back(call); + } + } + + bool isRuntimeDomainEnabled() const { + return runtimeEnabled_; + } + + void clearExpectedConsoleApiCalls() { + expectedConsoleApiCalls_.clear(); + } + + private: + void expectConsoleApiCallImpl(ExpectedConsoleApiCall call) { + this->expectMessageFromPage(JsonParsed(AllOf( + AtJsonPtr("/method", "Runtime.consoleAPICalled"), + AtJsonPtr("/params/type", call.type), + AtJsonPtr("/params/args", Eq(folly::parseJson(call.argsJson)))))); + } + + void enableRuntimeDomain() { + InSequence s; + auto executionContextInfo = this->expectMessageFromPage(JsonParsed( + AllOf(AtJsonPtr("/method", "Runtime.executionContextCreated")))); + if (!runtimeEnabled_) { + for (auto& call : expectedConsoleApiCalls_) { + expectConsoleApiCallImpl(call); + } + expectedConsoleApiCalls_.clear(); + } + this->expectMessageFromPage(JsonEq(R"({ + "id": 1, + "result": {} + })")); + this->toPage_->sendMessage(R"({ + "id": 1, + "method": "Runtime.enable" + })"); + + ASSERT_TRUE(executionContextInfo->has_value()); + + runtimeEnabled_ = true; + } + + void loadMainBundle() override { + auto params = GetParam(); + if (params.withNativeLoggingHook) { + // The presence or absence of nativeLoggingHook affects the console + // polyfill's behaviour. + eval( + R"( + if (!globalThis.nativeLoggingHook) { + globalThis.nativeLoggingHook = function(level, message) { + print(level + ': ' + message); + }; + } + )"); + } else { + // Ensure that we run without nativeLoggingHook even if it was installed + // elsewhere. + eval(R"( + delete globalThis.nativeLoggingHook; + )"); + } + if (params.withConsolePolyfill) { + eval(preludeJsCode); + } + } + + std::vector expectedConsoleApiCalls_; + bool runtimeEnabled_{false}; +}; + +class ConsoleApiTestWithPreExistingConsole : public ConsoleApiTest { + void setupRuntimeBeforeRegistration(jsi::Runtime& /*unused*/) override { + eval(R"( + globalThis.__console_messages__ = []; + globalThis.console = { + log: function(...args) { + globalThis.__console_messages__.push({ + type: 'log', + args, + }); + }, + warn: function(...args) { + globalThis.__console_messages__.push({ + type: 'warn', + args, + }); + }, + }; + )"); + } +}; + +TEST_P(ConsoleApiTest, testConsoleLog) { + InSequence s; + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "hello" + }, { + "type": "string", + "value": "world" + }])"); + eval("console.log('hello', 'world');"); +} + +TEST_P(ConsoleApiTest, testConsoleDebug) { + InSequence s; + expectConsoleApiCall("debug", R"([{ + "type": "string", + "value": "hello fusebox" + }])"); + eval("console.debug('hello fusebox');"); +} + +TEST_P(ConsoleApiTest, testConsoleInfo) { + InSequence s; + expectConsoleApiCall("info", R"([{ + "type": "string", + "value": "you should know this" + }])"); + eval("console.info('you should know this');"); +} + +TEST_P(ConsoleApiTest, testConsoleError) { + InSequence s; + expectConsoleApiCall("error", R"([{ + "type": "string", + "value": "uh oh" + }])"); + eval("console.error('uh oh');"); +} + +TEST_P(ConsoleApiTest, testConsoleWarn) { + InSequence s; + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "careful" + }])"); + eval("console.warn('careful');"); +} + +TEST_P(ConsoleApiTest, testConsoleDir) { + InSequence s; + expectConsoleApiCall("dir", R"([{ + "type": "string", + "value": "something" + }])"); + eval("console.dir('something');"); +} + +TEST_P(ConsoleApiTest, testConsoleDirxml) { + InSequence s; + expectConsoleApiCall("dirxml", R"([{ + "type": "string", + "value": "pretend this is a DOM element" + }])"); + eval("console.dirxml('pretend this is a DOM element');"); +} + +TEST_P(ConsoleApiTest, testConsoleTable) { + InSequence s; + expectConsoleApiCall("table", R"([{ + "type": "string", + "value": "pretend this is a complex object" + }])"); + eval("console.table('pretend this is a complex object');"); +} + +TEST_P(ConsoleApiTest, testConsoleTrace) { + InSequence s; + expectConsoleApiCall("trace", R"([{ + "type": "string", + "value": "trace trace" + }])"); + eval("console.trace('trace trace');"); +} + +TEST_P(ConsoleApiTest, testConsoleClear) { + InSequence s; + expectConsoleApiCall("clear", "[]"); + eval("console.clear();"); +} + +TEST_P(ConsoleApiTest, testConsoleClearAfterOtherCall) { + InSequence s; + if (isRuntimeDomainEnabled()) { + // This should only be delivered if console notifications are enabled, not + // when they're being cached for later. + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "hello" + }])"); + } + expectConsoleApiCall("clear", "[]"); + eval("console.log('hello');"); + eval("console.clear();"); +} + +TEST_P(ConsoleApiTest, testConsoleGroup) { + InSequence s; + expectConsoleApiCall("startGroup", R"([{ + "type": "string", + "value": "group title" + }])"); + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "in group" + }])"); + expectConsoleApiCall("endGroup", "[]"); + eval("console.group('group title');"); + eval("console.log('in group');"); + eval("console.groupEnd();"); +} + +TEST_P(ConsoleApiTest, testConsoleGroupCollapsed) { + InSequence s; + expectConsoleApiCall("startGroupCollapsed", R"([{ + "type": "string", + "value": "group collapsed title" + }])"); + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "in group collapsed" + }])"); + expectConsoleApiCall("endGroup", "[]"); + eval("console.groupCollapsed('group collapsed title');"); + eval("console.log('in group collapsed');"); + eval("console.groupEnd();"); +} + +TEST_P(ConsoleApiTest, testConsoleAssert) { + InSequence s; + expectConsoleApiCall("assert", R"([{ + "type": "string", + "value": "Assertion failed: something is bad" + }])"); + eval("console.assert(true, 'everything is good');"); + eval("console.assert(false, 'something is bad');"); + + expectConsoleApiCall("assert", R"([{ + "type": "string", + "value": "Assertion failed" + }])"); + eval("console.assert();"); +} + +TEST_P(ConsoleApiTest, testConsoleCount) { + InSequence s; + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "default: 1" + }])"); + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "default: 2" + }])"); + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "default: 3" + }])"); + eval("console.count();"); + eval("console.count('default');"); + eval("console.count();"); + eval("console.countReset();"); + + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "default: 1" + }])"); + eval("console.count();"); + eval("console.countReset('default');"); + + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "default: 1" + }])"); + eval("console.count();"); +} + +TEST_P(ConsoleApiTest, testConsoleCountLabel) { + InSequence s; + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "foo: 1" + }])"); + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "foo: 2" + }])"); + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "foo: 3" + }])"); + eval("console.count('foo');"); + eval("console.count('foo');"); + eval("console.count('foo');"); + eval("console.countReset('foo');"); + + expectConsoleApiCall("count", R"([{ + "type": "string", + "value": "foo: 1" + }])"); + eval("console.count('foo');"); +} + +TEST_P(ConsoleApiTest, testConsoleCountResetInvalidLabel) { + InSequence s; + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Count for 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Count for 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Count for 'foo' does not exist" + }])"); + eval("console.countReset();"); + eval("console.countReset('default');"); + eval("console.countReset('foo');"); +} + +// TODO(moti): Tests for console.timeEnd() and timeLog() that actually check the +// output (with mocked system clock?) + +TEST_P(ConsoleApiTest, testConsoleTimeExistingLabel) { + eval("console.time();"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'default' already exists" + }])"); + eval("console.time('default');"); + + eval("console.time('foo');"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'foo' already exists" + }])"); + eval("console.time('foo');"); +} + +TEST_P(ConsoleApiTest, testConsoleTimeInvalidLabel) { + InSequence s; + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'foo' does not exist" + }])"); + eval("console.timeEnd();"); + eval("console.timeEnd('default');"); + eval("console.timeEnd('foo');"); + + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'default' does not exist" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "Timer 'foo' does not exist" + }])"); + eval("console.timeLog();"); + eval("console.timeLog('default');"); + eval("console.timeLog('foo');"); +} + +TEST_P(ConsoleApiTest, testConsoleSilentlyClearedOnReload) { + InSequence s; + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "hello" + }])"); + eval("console.log('hello');"); + + // If there are any expectations we haven't checked yet, clear them + clearExpectedConsoleApiCalls(); + // Reloading generates some Runtime events + if (isRuntimeDomainEnabled()) { + expectMessageFromPage(JsonParsed( + AllOf(AtJsonPtr("/method", "Runtime.executionContextDestroyed")))); + expectMessageFromPage(JsonParsed( + AllOf(AtJsonPtr("/method", "Runtime.executionContextsCleared")))); + expectMessageFromPage(JsonParsed( + AllOf(AtJsonPtr("/method", "Runtime.executionContextCreated")))); + } + reload(); + + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "world" + }])"); + eval("console.log('world');"); +} + +TEST_P(ConsoleApiTestWithPreExistingConsole, testPreExistingConsoleObject) { + InSequence s; + expectConsoleApiCall("log", R"([{ + "type": "string", + "value": "hello" + }])"); + expectConsoleApiCall("warning", R"([{ + "type": "string", + "value": "world" + }])"); + expectConsoleApiCall("table", R"([{ + "type": "number", + "value": 42 + }])"); + eval("console.log('hello');"); + eval("console.warn('world');"); + // NOTE: not present in the pre-existing console object + eval("console.table(42);"); + auto& runtime = engineAdapter_->getRuntime(); + EXPECT_THAT( + eval("JSON.stringify(globalThis.__console_messages__)") + .asString(runtime) + .utf8(runtime), + JsonEq( + R"([{ + "type": "log", + "args": [ + "hello" + ] + }, { + "type": "warn", + "args": [ + "world" + ] + }])")); +} + +static const auto paramValues = testing::Values( + Params{ + .withConsolePolyfill = true, + .withNativeLoggingHook = false, + .runtimeEnabledAtStart = false, + }, + Params{ + .withConsolePolyfill = false, + .withNativeLoggingHook = false, + .runtimeEnabledAtStart = false, + }, + Params{ + .withConsolePolyfill = true, + .withNativeLoggingHook = false, + .runtimeEnabledAtStart = true, + }, + Params{ + .withConsolePolyfill = false, + .withNativeLoggingHook = false, + .runtimeEnabledAtStart = true, + }, + Params{ + .withConsolePolyfill = true, + .withNativeLoggingHook = true, + .runtimeEnabledAtStart = false, + }, + Params{ + .withConsolePolyfill = false, + .withNativeLoggingHook = true, + .runtimeEnabledAtStart = false, + }, + Params{ + .withConsolePolyfill = true, + .withNativeLoggingHook = true, + .runtimeEnabledAtStart = true, + }, + Params{ + .withConsolePolyfill = false, + .withNativeLoggingHook = true, + .runtimeEnabledAtStart = true, + }); + +INSTANTIATE_TEST_SUITE_P(ConsoleApiTest, ConsoleApiTest, paramValues); + +INSTANTIATE_TEST_SUITE_P( + ConsoleApiTestWithPreExistingConsole, + ConsoleApiTestWithPreExistingConsole, + paramValues); + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/PageTargetTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp similarity index 89% rename from packages/react-native/ReactCommon/jsinspector-modern/tests/PageTargetTest.cpp rename to packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp index 31b01eb1571af9..f27baef9567379 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/PageTargetTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp @@ -11,8 +11,8 @@ #include #include +#include #include -#include #include @@ -26,31 +26,32 @@ namespace facebook::react::jsinspector_modern { namespace { -class PageTargetTest : public Test { +class HostTargetTest : public Test { folly::QueuedImmediateExecutor immediateExecutor_; protected: - PageTargetTest() { - EXPECT_CALL(runtimeTargetDelegate_, createAgentDelegate(_, _, _, _)) + HostTargetTest() { + EXPECT_CALL(runtimeTargetDelegate_, createAgentDelegate(_, _, _, _, _)) .WillRepeatedly(runtimeAgentDelegates_.lazily_make_unique< FrontendChannel, SessionState&, std::unique_ptr, - const ExecutionContextDescription&>()); + const ExecutionContextDescription&, + RuntimeExecutor>()); } void connect() { - ASSERT_FALSE(toPage_) << "Can only connect once in a PageTargetTest."; + ASSERT_FALSE(toPage_) << "Can only connect once in a HostTargetTest."; toPage_ = page_->connect( remoteConnections_.make_unique(), - {.integrationName = "PageTargetTest"}); + {.integrationName = "HostTargetTest"}); // We'll always get an onDisconnect call when we tear // down the test. Expect it in order to satisfy the strict mock. EXPECT_CALL(*remoteConnections_[0], onDisconnect()); } - MockPageTargetDelegate pageTargetDelegate_; + MockHostTargetDelegate hostTargetDelegate_; MockRemoteConnection& fromPage() { assert(toPage_); @@ -61,8 +62,8 @@ class PageTargetTest : public Test { immediateExecutor_.add(callback); }; - std::shared_ptr page_ = - PageTarget::create(pageTargetDelegate_, inspectorExecutor_); + std::shared_ptr page_ = + HostTarget::create(hostTargetDelegate_, inspectorExecutor_); MockInstanceTargetDelegate instanceTargetDelegate_; MockRuntimeTargetDelegate runtimeTargetDelegate_; @@ -81,22 +82,22 @@ class PageTargetTest : public Test { }; /** - * Simplified test harness focused on sending messages to and from a PageTarget. + * Simplified test harness focused on sending messages to and from a HostTarget. */ -class PageTargetProtocolTest : public PageTargetTest { +class HostTargetProtocolTest : public HostTargetTest { public: - PageTargetProtocolTest() { + HostTargetProtocolTest() { connect(); } private: // Protocol tests shouldn't manually call connect() - using PageTargetTest::connect; + using HostTargetTest::connect; }; } // namespace -TEST_F(PageTargetProtocolTest, UnrecognizedMethod) { +TEST_F(HostTargetProtocolTest, UnrecognizedMethod) { EXPECT_CALL( fromPage(), onMessage(JsonParsed(AllOf( @@ -109,7 +110,7 @@ TEST_F(PageTargetProtocolTest, UnrecognizedMethod) { })"); } -TEST_F(PageTargetProtocolTest, TypeErrorInMethodName) { +TEST_F(HostTargetProtocolTest, TypeErrorInMethodName) { EXPECT_CALL( fromPage(), onMessage(JsonParsed(AllOf( @@ -123,7 +124,7 @@ TEST_F(PageTargetProtocolTest, TypeErrorInMethodName) { })"); } -TEST_F(PageTargetProtocolTest, MissingId) { +TEST_F(HostTargetProtocolTest, MissingId) { EXPECT_CALL( fromPage(), onMessage(JsonParsed(AllOf( @@ -136,7 +137,7 @@ TEST_F(PageTargetProtocolTest, MissingId) { })"); } -TEST_F(PageTargetProtocolTest, MalformedJson) { +TEST_F(HostTargetProtocolTest, MalformedJson) { EXPECT_CALL( fromPage(), onMessage(JsonParsed(AllOf( @@ -146,7 +147,7 @@ TEST_F(PageTargetProtocolTest, MalformedJson) { toPage_->sendMessage("{"); } -TEST_F(PageTargetProtocolTest, InjectLogsToIdentifyBackend) { +TEST_F(HostTargetProtocolTest, InjectLogsToIdentifyBackend) { InSequence s; EXPECT_CALL( @@ -167,12 +168,12 @@ TEST_F(PageTargetProtocolTest, InjectLogsToIdentifyBackend) { })"); } -TEST_F(PageTargetProtocolTest, PageReloadMethod) { +TEST_F(HostTargetProtocolTest, PageReloadMethod) { InSequence s; EXPECT_CALL( - pageTargetDelegate_, - onReload(Eq(PageTargetDelegate::PageReloadRequest{ + hostTargetDelegate_, + onReload(Eq(HostTargetDelegate::PageReloadRequest{ .ignoreCache = std::nullopt, .scriptToEvaluateOnLoad = std::nullopt}))) .RetiresOnSaturation(); @@ -187,8 +188,8 @@ TEST_F(PageTargetProtocolTest, PageReloadMethod) { })"); EXPECT_CALL( - pageTargetDelegate_, - onReload(Eq(PageTargetDelegate::PageReloadRequest{ + hostTargetDelegate_, + onReload(Eq(HostTargetDelegate::PageReloadRequest{ .ignoreCache = true, .scriptToEvaluateOnLoad = "alert('hello');"}))) .RetiresOnSaturation(); EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({ @@ -206,13 +207,13 @@ TEST_F(PageTargetProtocolTest, PageReloadMethod) { })"); } -TEST_F(PageTargetProtocolTest, RegisterUnregisterInstanceWithoutEvents) { +TEST_F(HostTargetProtocolTest, RegisterUnregisterInstanceWithoutEvents) { auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetTest, ConnectToAlreadyRegisteredInstanceWithoutEvents) { +TEST_F(HostTargetTest, ConnectToAlreadyRegisteredInstanceWithoutEvents) { auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); connect(); @@ -220,7 +221,7 @@ TEST_F(PageTargetTest, ConnectToAlreadyRegisteredInstanceWithoutEvents) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetProtocolTest, RegisterUnregisterInstanceWithEvents) { +TEST_F(HostTargetProtocolTest, RegisterUnregisterInstanceWithEvents) { InSequence s; EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({ @@ -240,7 +241,7 @@ TEST_F(PageTargetProtocolTest, RegisterUnregisterInstanceWithEvents) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetTest, ConnectToAlreadyRegisteredInstanceWithEvents) { +TEST_F(HostTargetTest, ConnectToAlreadyRegisteredInstanceWithEvents) { auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); connect(); @@ -263,7 +264,7 @@ TEST_F(PageTargetTest, ConnectToAlreadyRegisteredInstanceWithEvents) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetTest, ConnectToAlreadyRegisteredRuntimeWithEvents) { +TEST_F(HostTargetTest, ConnectToAlreadyRegisteredRuntimeWithEvents) { auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); auto& runtimeTarget = instanceTarget.registerRuntime(runtimeTargetDelegate_, runtimeExecutor_); @@ -298,7 +299,7 @@ TEST_F(PageTargetTest, ConnectToAlreadyRegisteredRuntimeWithEvents) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetProtocolTest, RuntimeAgentDelegateLifecycle) { +TEST_F(HostTargetProtocolTest, RuntimeAgentDelegateLifecycle) { { auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); auto& runtimeTarget = instanceTarget.registerRuntime( @@ -326,7 +327,7 @@ TEST_F(PageTargetProtocolTest, RuntimeAgentDelegateLifecycle) { EXPECT_FALSE(runtimeAgentDelegates_[1]); } -TEST_F(PageTargetProtocolTest, MethodNotHandledByRuntimeAgentDelegate) { +TEST_F(HostTargetProtocolTest, MethodNotHandledByRuntimeAgentDelegate) { InSequence s; auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); @@ -352,7 +353,7 @@ TEST_F(PageTargetProtocolTest, MethodNotHandledByRuntimeAgentDelegate) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetProtocolTest, MethodHandledByRuntimeAgentDelegate) { +TEST_F(HostTargetProtocolTest, MethodHandledByRuntimeAgentDelegate) { InSequence s; auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); @@ -385,7 +386,7 @@ TEST_F(PageTargetProtocolTest, MethodHandledByRuntimeAgentDelegate) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetProtocolTest, MessageRoutingWhileNoRuntimeAgentDelegate) { +TEST_F(HostTargetProtocolTest, MessageRoutingWhileNoRuntimeAgentDelegate) { InSequence s; EXPECT_CALL( @@ -442,10 +443,10 @@ TEST_F(PageTargetProtocolTest, MessageRoutingWhileNoRuntimeAgentDelegate) { })"); } -TEST_F(PageTargetProtocolTest, InstanceWithNullRuntimeAgentDelegate) { +TEST_F(HostTargetProtocolTest, InstanceWithNullRuntimeAgentDelegate) { InSequence s; - EXPECT_CALL(runtimeTargetDelegate_, createAgentDelegate(_, _, _, _)) + EXPECT_CALL(runtimeTargetDelegate_, createAgentDelegate(_, _, _, _, _)) .WillRepeatedly(ReturnNull()); auto& instanceTarget = page_->registerInstance(instanceTargetDelegate_); @@ -469,7 +470,7 @@ TEST_F(PageTargetProtocolTest, InstanceWithNullRuntimeAgentDelegate) { page_->unregisterInstance(instanceTarget); } -TEST_F(PageTargetProtocolTest, RuntimeAgentDelegateHasAccessToSessionState) { +TEST_F(HostTargetProtocolTest, RuntimeAgentDelegateHasAccessToSessionState) { InSequence s; // Send Runtime.enable before registering the Instance (which in turns creates diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h index 4a2346cc6381ab..f0b73ae9dcaf40 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h @@ -115,9 +115,9 @@ class MockInspectorPackagerConnectionDelegate folly::Executor& executor_; }; -class MockPageTargetDelegate : public PageTargetDelegate { +class MockHostTargetDelegate : public HostTargetDelegate { public: - // PageTargetDelegate methods + // HostTargetDelegate methods MOCK_METHOD(void, onReload, (const PageReloadRequest& request), (override)); }; @@ -133,7 +133,13 @@ class MockRuntimeTargetDelegate : public RuntimeTargetDelegate { SessionState& sessionState, std::unique_ptr previouslyExportedState, - const ExecutionContextDescription&), + const ExecutionContextDescription&, + RuntimeExecutor), + (override)); + MOCK_METHOD( + void, + addConsoleMessage, + (jsi::Runtime & runtime, ConsoleMessage message), (override)); }; @@ -143,10 +149,11 @@ class MockRuntimeAgentDelegate : public RuntimeAgentDelegate { FrontendChannel frontendChannel, SessionState& sessionState, std::unique_ptr, - const ExecutionContextDescription& executionContextDescription) + ExecutionContextDescription executionContextDescription, + const RuntimeExecutor& /*runtimeExecutor*/) : frontendChannel(std::move(frontendChannel)), sessionState(sessionState), - executionContextDescription(executionContextDescription) {} + executionContextDescription(std::move(executionContextDescription)) {} // RuntimeAgentDelegate methods MOCK_METHOD( diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp index 3e306fe5ec3a20..6255c9e568ce31 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp @@ -6,20 +6,8 @@ */ #include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "FollyDynamicMatchers.h" -#include "InspectorMocks.h" -#include "UniquePtrFactory.h" +#include "JsiIntegrationTest.h" #include "engines/JsiIntegrationTestGenericEngineAdapter.h" #include "engines/JsiIntegrationTestHermesEngineAdapter.h" @@ -28,133 +16,6 @@ using folly::sformat; namespace facebook::react::jsinspector_modern { -namespace { - -/** - * A text fixture class for the integration between the modern RN CDP backend - * and a JSI engine, mocking out the rest of RN. For simplicity, everything is - * single-threaded and "async" work is actually done through a queued immediate - * executor ( = run immediately and finish all queued sub-tasks before - * returning). - * - * The main limitation of the simpler threading model is that we can't cover - * breakpoints etc - since pausing during JS execution would prevent the test - * from making progress. Such functionality is better suited for a full RN+CDP - * integration test (using RN's own thread management) as well as for each - * engine's unit tests. - * - * \tparam EngineAdapter An adapter class that implements RuntimeTargetDelegate - * for a particular engine, plus exposes access to a RuntimeExecutor (based on - * the provided folly::Executor) and the corresponding jsi::Runtime. - */ -template -class JsiIntegrationPortableTest : public Test, private PageTargetDelegate { - folly::QueuedImmediateExecutor immediateExecutor_; - - protected: - JsiIntegrationPortableTest() : engineAdapter_{immediateExecutor_} { - instance_ = &page_->registerInstance(instanceTargetDelegate_); - runtimeTarget_ = &instance_->registerRuntime( - *engineAdapter_, engineAdapter_->getRuntimeExecutor()); - } - - ~JsiIntegrationPortableTest() override { - toPage_.reset(); - if (runtimeTarget_) { - EXPECT_TRUE(instance_); - instance_->unregisterRuntime(*runtimeTarget_); - runtimeTarget_ = nullptr; - } - if (instance_) { - page_->unregisterInstance(*instance_); - instance_ = nullptr; - } - } - - void connect() { - ASSERT_FALSE(toPage_) << "Can only connect once in a JSI integration test."; - toPage_ = page_->connect( - remoteConnections_.make_unique(), - {.integrationName = "JsiIntegrationTest"}); - - // We'll always get an onDisconnect call when we tear - // down the test. Expect it in order to satisfy the strict mock. - EXPECT_CALL(*remoteConnections_[0], onDisconnect()); - } - - void reload() { - if (runtimeTarget_) { - ASSERT_TRUE(instance_); - instance_->unregisterRuntime(*runtimeTarget_); - runtimeTarget_ = nullptr; - } - if (instance_) { - page_->unregisterInstance(*instance_); - instance_ = nullptr; - } - // Recreate the engine (e.g. to wipe any state in the inner jsi::Runtime) - engineAdapter_.emplace(immediateExecutor_); - instance_ = &page_->registerInstance(instanceTargetDelegate_); - runtimeTarget_ = &instance_->registerRuntime( - *engineAdapter_, engineAdapter_->getRuntimeExecutor()); - } - - MockRemoteConnection& fromPage() { - assert(toPage_); - return *remoteConnections_[0]; - } - - VoidExecutor inspectorExecutor_ = [this](auto callback) { - immediateExecutor_.add(callback); - }; - - jsi::Value eval(std::string_view code) { - return engineAdapter_->getRuntime().evaluateJavaScript( - std::make_shared(std::string(code)), ""); - } - - /** - * Expect a message matching the provided gmock \c matcher and return a holder - * that will eventually contain the parsed JSON payload. - */ - template - std::shared_ptr> expectMessageFromPage( - Matcher&& matcher) { - std::shared_ptr result = - std::make_shared>(std::nullopt); - EXPECT_CALL(fromPage(), onMessage(matcher)) - .WillOnce( - ([result](auto message) { *result = folly::parseJson(message); })) - .RetiresOnSaturation(); - return result; - } - - std::shared_ptr page_ = - PageTarget::create(*this, inspectorExecutor_); - InstanceTarget* instance_{}; - RuntimeTarget* runtimeTarget_{}; - - MockInstanceTargetDelegate instanceTargetDelegate_; - std::optional engineAdapter_; - - private: - UniquePtrFactory> remoteConnections_; - - protected: - // NOTE: Needs to be destroyed before page_. - std::unique_ptr toPage_; - - private: - // PageTargetDelegate methods - - void onReload(const PageReloadRequest& request) override { - (void)request; - reload(); - } -}; - -} // namespace - //////////////////////////////////////////////////////////////////////////////// // Some tests are specific to Hermes's CDP capabilities and some are not. @@ -176,7 +37,7 @@ template using JsiIntegrationHermesTest = JsiIntegrationPortableTest; TYPED_TEST_SUITE(JsiIntegrationHermesTest, AllHermesVariants); -//////////////////////////////////////////////////////////////////////////////// +#pragma region AllEngines TYPED_TEST(JsiIntegrationPortableTest, ConnectWithoutCrashing) { this->connect(); @@ -285,6 +146,7 @@ TYPED_TEST(JsiIntegrationPortableTest, AddBinding) { "id": 1, "method": "Runtime.enable" })"); + ASSERT_TRUE(executionContextInfo->has_value()); auto executionContextId = executionContextInfo->value()["params"]["context"]["id"]; @@ -334,6 +196,7 @@ TYPED_TEST(JsiIntegrationPortableTest, AddedBindingSurvivesReload) { "id": 1, "method": "Runtime.enable" })"); + ASSERT_TRUE(executionContextInfo->has_value()); auto executionContextId = executionContextInfo->value()["params"]["context"]["id"]; @@ -454,7 +317,8 @@ TYPED_TEST(JsiIntegrationPortableTest, ExceptionDuringAddBindingIsIgnored) { EXPECT_TRUE(this->eval("globalThis.foo === 42").getBool()); } -//////////////////////////////////////////////////////////////////////////////// +#pragma endregion // AllEngines +#pragma region AllHermesVariants TYPED_TEST(JsiIntegrationHermesTest, EvaluateExpression) { this->connect(); @@ -490,6 +354,7 @@ TYPED_TEST(JsiIntegrationHermesTest, EvaluateExpressionInExecutionContext) { "id": 1, "method": "Runtime.enable" })"); + ASSERT_TRUE(executionContextInfo->has_value()); auto executionContextId = executionContextInfo->value()["params"]["context"]["id"].getInt(); @@ -523,7 +388,7 @@ TYPED_TEST(JsiIntegrationHermesTest, EvaluateExpressionInExecutionContext) { // Now the old execution context is stale. this->expectMessageFromPage( - JsonParsed(AllOf(AtJsonPtr("/id", 3), AtJsonPtr("/error/code", -32000)))); + JsonParsed(AllOf(AtJsonPtr("/id", 3), AtJsonPtr("/error/code", -32600)))); this->toPage_->sendMessage(sformat( R"({{ "id": 3, @@ -538,24 +403,24 @@ TYPED_TEST(JsiIntegrationHermesTest, ResolveBreakpointAfterReload) { InSequence s; - this->expectMessageFromPage(JsonParsed(AtJsonPtr("/id", 1))); + this->expectMessageFromPage(JsonEq(R"({ + "id": 1, + "result": {} + })")); this->toPage_->sendMessage(R"({ "id": 1, - "method": "Debugger.setBreakpointByUrl", - "params": {"lineNumber": 2, "url": "breakpointTest.js"} + "method": "Debugger.enable" })"); - this->reload(); - - this->expectMessageFromPage(JsonEq(R"({ - "id": 2, - "result": {} - })")); + this->expectMessageFromPage(JsonParsed(AtJsonPtr("/id", 2))); this->toPage_->sendMessage(R"({ "id": 2, - "method": "Debugger.enable" + "method": "Debugger.setBreakpointByUrl", + "params": {"lineNumber": 2, "url": "breakpointTest.js"} })"); + this->reload(); + auto scriptInfo = this->expectMessageFromPage(JsonParsed(AllOf( AtJsonPtr("/method", "Debugger.scriptParsed"), AtJsonPtr("/params/url", "breakpointTest.js")))); @@ -568,9 +433,101 @@ TYPED_TEST(JsiIntegrationHermesTest, ResolveBreakpointAfterReload) { }; //# sourceURL=breakpointTest.js )"); + ASSERT_TRUE(breakpointInfo->has_value()); + ASSERT_TRUE(scriptInfo->has_value()); EXPECT_EQ( breakpointInfo->value()["params"]["location"]["scriptId"], scriptInfo->value()["params"]["scriptId"]); } +TYPED_TEST(JsiIntegrationHermesTest, CDPAgentReentrancyRegressionTest) { + this->connect(); + + // TODO(moti): Add an InSequence guard here once Hermes processes the messages + // in the order they were received. + + this->inspectorExecutor_([&]() { + // Tasks scheduled on our executor here will be executed when this lambda + // returns. This is integral to the bug we're trying to reproduce, so we + // place the EXPECT_* calls at the end of the lambda body to ensure the + // test fails if we get eager (unexpected) responses. + + // 1. Cause CDPAgent to schedule a task on the JS executor to process the + // message. The task is simultaneously scheduled as an interrupt on the + // JS VM (but will be called via the executor, since the interpreter is + // idle at the moment). + this->toPage_->sendMessage(R"({ + "id": 1, + "method": "Runtime.evaluate", + "params": {"expression": "1 + 2"} + })"); + + // 2. Cause CDPAgent to schedule another task+interrupt. + this->toPage_->sendMessage(R"({ + "id": 2, + "method": "Runtime.evaluate", + "params": {"expression": "3 + 4"} + })"); + + // 3. When the first scheduled task runs (via the executor), it enters the + // interpreter to evaluate the expression, at which point the + // interpreter begins processing interrupts and enters the second task. + // This used to trigger two distinct bugs in CDPAgent: + // - The first task would be triggered twice due to a race condition + // between the executor and the interrupt handler. (D54771697) + // - The second task would deadlock due to the first task holding a + // lock preventing any other CDPAgent tasks from running. (D54838179) + + this->expectMessageFromPage(JsonEq(R"({ + "id": 1, + "result": { + "result": { + "type": "number", + "value": 3 + } + } + })")); + + this->expectMessageFromPage(JsonEq(R"({ + "id": 2, + "result": { + "result": { + "type": "number", + "value": 7 + } + } + })")); + }); +} + +TYPED_TEST(JsiIntegrationHermesTest, ScriptParsedExactlyOnce) { + // Regression test for T182003727 (multiple scriptParsed events for a single + // script under Hermes lazy compilation). + + this->connect(); + + InSequence s; + + this->eval(R"( + // NOTE: Triggers lazy compilation in Hermes when running with + // CompilationMode::ForceLazyCompilation. + (function foo(){var x = 2;})() + //# sourceURL=script.js + )"); + + this->expectMessageFromPage(JsonParsed(AllOf( + AtJsonPtr("/method", "Debugger.scriptParsed"), + AtJsonPtr("/params/url", "script.js")))); + this->expectMessageFromPage(JsonEq(R"({ + "id": 1, + "result": {} + })")); + this->toPage_->sendMessage(R"({ + "id": 1, + "method": "Debugger.enable" + })"); +} + +#pragma endregion // AllHermesVariants + } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h new file mode 100644 index 00000000000000..00f262d3736d13 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h @@ -0,0 +1,179 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include "FollyDynamicMatchers.h" +#include "InspectorMocks.h" +#include "UniquePtrFactory.h" +#include "utils/InspectorFlagOverridesGuard.h" + +namespace facebook::react::jsinspector_modern { + +/** + * A text fixture class for the integration between the modern RN CDP backend + * and a JSI engine, mocking out the rest of RN. For simplicity, everything is + * single-threaded and "async" work is actually done through a queued immediate + * executor ( = run immediately and finish all queued sub-tasks before + * returning). + * + * The main limitation of the simpler threading model is that we can't cover + * breakpoints etc - since pausing during JS execution would prevent the test + * from making progress. Such functionality is better suited for a full RN+CDP + * integration test (using RN's own thread management) as well as for each + * engine's unit tests. + * + * \tparam EngineAdapter An adapter class that implements RuntimeTargetDelegate + * for a particular engine, plus exposes access to a RuntimeExecutor (based on + * the provided folly::Executor) and the corresponding jsi::Runtime. + */ +template +class JsiIntegrationPortableTest : public ::testing::Test, + private HostTargetDelegate { + folly::QueuedImmediateExecutor immediateExecutor_; + + protected: + JsiIntegrationPortableTest() + : inspectorFlagsGuard_{EngineAdapter::getInspectorFlagOverrides()}, + engineAdapter_{immediateExecutor_} {} + + void SetUp() override { + // NOTE: Using SetUp() so we can call virtual methods like + // setupRuntimeBeforeRegistration(). + instance_ = &page_->registerInstance(instanceTargetDelegate_); + setupRuntimeBeforeRegistration(engineAdapter_->getRuntime()); + runtimeTarget_ = &instance_->registerRuntime( + engineAdapter_->getRuntimeTargetDelegate(), + engineAdapter_->getRuntimeExecutor()); + loadMainBundle(); + } + + ~JsiIntegrationPortableTest() override { + toPage_.reset(); + if (runtimeTarget_) { + EXPECT_TRUE(instance_); + instance_->unregisterRuntime(*runtimeTarget_); + runtimeTarget_ = nullptr; + } + if (instance_) { + page_->unregisterInstance(*instance_); + instance_ = nullptr; + } + } + + /** + * Noop in JsiIntegrationPortableTest, but can be overridden by derived + * fixture classes to load some code at startup and after each reload. + */ + virtual void loadMainBundle() {} + + /** + * Noop in JsiIntegrationPortableTest, but can be overridden by derived + * fixture classes to set up the runtime before registering it with the + * CDP backend. + */ + virtual void setupRuntimeBeforeRegistration(jsi::Runtime& /*runtime*/) {} + + void connect() { + ASSERT_FALSE(toPage_) << "Can only connect once in a JSI integration test."; + toPage_ = page_->connect( + remoteConnections_.make_unique(), + {.integrationName = "JsiIntegrationTest"}); + + // We'll always get an onDisconnect call when we tear + // down the test. Expect it in order to satisfy the strict mock. + EXPECT_CALL(*remoteConnections_[0], onDisconnect()); + } + + void reload() { + if (runtimeTarget_) { + ASSERT_TRUE(instance_); + instance_->unregisterRuntime(*runtimeTarget_); + runtimeTarget_ = nullptr; + } + if (instance_) { + page_->unregisterInstance(*instance_); + instance_ = nullptr; + } + // Recreate the engine (e.g. to wipe any state in the inner jsi::Runtime) + engineAdapter_.emplace(immediateExecutor_); + instance_ = &page_->registerInstance(instanceTargetDelegate_); + setupRuntimeBeforeRegistration(engineAdapter_->getRuntime()); + runtimeTarget_ = &instance_->registerRuntime( + engineAdapter_->getRuntimeTargetDelegate(), + engineAdapter_->getRuntimeExecutor()); + loadMainBundle(); + } + + MockRemoteConnection& fromPage() { + assert(toPage_); + return *remoteConnections_[0]; + } + + VoidExecutor inspectorExecutor_ = [this](auto callback) { + immediateExecutor_.add(callback); + }; + + jsi::Value eval(std::string_view code) { + return engineAdapter_->getRuntime().evaluateJavaScript( + std::make_shared(std::string(code)), ""); + } + + /** + * Expect a message matching the provided gmock \c matcher and return a holder + * that will eventually contain the parsed JSON payload. + */ + template + std::shared_ptr> expectMessageFromPage( + Matcher&& matcher) { + std::shared_ptr result = + std::make_shared>(std::nullopt); + EXPECT_CALL(fromPage(), onMessage(matcher)) + .WillOnce( + ([result](auto message) { *result = folly::parseJson(message); })) + .RetiresOnSaturation(); + return result; + } + + std::shared_ptr page_ = + HostTarget::create(*this, inspectorExecutor_); + InstanceTarget* instance_{}; + RuntimeTarget* runtimeTarget_{}; + + InspectorFlagOverridesGuard inspectorFlagsGuard_; + MockInstanceTargetDelegate instanceTargetDelegate_; + std::optional engineAdapter_; + + private: + UniquePtrFactory<::testing::StrictMock> + remoteConnections_; + + protected: + // NOTE: Needs to be destroyed before page_. + std::unique_ptr toPage_; + + private: + // HostTargetDelegate methods + + void onReload(const PageReloadRequest& request) override { + (void)request; + reload(); + } +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.cpp new file mode 100644 index 00000000000000..47739d51ba25f3 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ReactInstanceIntegrationTest.h" +#include "FollyDynamicMatchers.h" +#include "UniquePtrFactory.h" +#include "prelude.js.h" + +#include +#include +#include +#include +#include +#include + +using namespace ::testing; + +namespace facebook::react::jsinspector_modern { + +#pragma region ReactInstanceIntegrationTest + +ReactInstanceIntegrationTest::ReactInstanceIntegrationTest() + : runtime(nullptr), + instance(nullptr), + messageQueueThread(std::make_shared()), + errorHandler(std::make_shared()) {} + +void ReactInstanceIntegrationTest::SetUp() { + auto mockRegistry = std::make_unique(); + auto timerManager = + std::make_shared(std::move(mockRegistry)); + + auto jsErrorHandlingFunc = [](react::MapBuffer error) noexcept { + LOG(INFO) << "Error: \nFile: " << error.getString(react::kFrameFileName) + << "\nLine: " << error.getInt(react::kFrameLineNumber) + << "\nColumn: " << error.getInt(react::kFrameColumnNumber) + << "\nMethod: " << error.getString(react::kFrameMethodName); + }; + + auto jsRuntimeFactory = std::make_unique(); + std::unique_ptr runtime_ = + jsRuntimeFactory->createJSRuntime(nullptr, nullptr, messageQueueThread); + jsi::Runtime* jsiRuntime = &runtime_->getRuntime(); + + // Error handler: + jsiRuntime->global().setProperty( + *jsiRuntime, + "ErrorUtils", + jsi::Object::createFromHostObject(*jsiRuntime, errorHandler)); + + std::shared_ptr hostTargetIfModernCDP = nullptr; + + if (InspectorFlags::getInstance().getEnableModernCDPRegistry()) { + VoidExecutor inspectorExecutor = [this](auto callback) { + immediateExecutor_.add(callback); + }; + MockHostTargetDelegate hostTargetDelegate; + hostTargetIfModernCDP = + HostTarget::create(hostTargetDelegate, inspectorExecutor); + } + + instance = std::make_unique( + std::move(runtime_), + messageQueueThread, + timerManager, + std::move(jsErrorHandlingFunc), + hostTargetIfModernCDP == nullptr ? nullptr : hostTargetIfModernCDP.get()); + + timerManager->setRuntimeExecutor(instance->getBufferedRuntimeExecutor()); + + // JS Environment: + initializeRuntime(preludeJsCode); + + // Inspector: + auto& inspector = getInspectorInstance(); + + if (hostTargetIfModernCDP != nullptr) { + // Under modern CDP, the React host is responsible for adding itself as + // the root target on startup. + pageId_ = inspector.addPage( + "mock-title", + "mock-vm", + [hostTargetIfModernCDP](std::unique_ptr remote) + -> std::unique_ptr { + auto localConnection = hostTargetIfModernCDP->connect( + std::move(remote), + { + .integrationName = "ReactInstanceIntegrationTest", + }); + return localConnection; + }, + // TODO: Allow customisation of InspectorTargetCapabilities + {}); + } else { + // Under legacy CDP, Hermes' DecoratedRuntime adds its page automatically + // within ConnectionDemux.enableDebugging. + auto pages = inspector.getPages(); + ASSERT_GT(pages.size(), 0); + pageId_ = pages.back().id; + } + + clientToVM_ = + inspector.connect(pageId_.value(), mockRemoteConnections_.make_unique()); + + ASSERT_NE(clientToVM_, nullptr); +} + +void ReactInstanceIntegrationTest::TearDown() { + clientToVM_->disconnect(); + // Destroy the local connection. + clientToVM_.reset(); + + if (pageId_.has_value() && + InspectorFlags::getInstance().getEnableModernCDPRegistry()) { + // Under modern CDP, clean up the page we added in SetUp and destroy + // resources owned by HostTarget. + getInspectorInstance().removePage(pageId_.value()); + } + pageId_.reset(); + + // Expect the remote connection to have been destroyed. + EXPECT_EQ(mockRemoteConnections_[0], nullptr); + ReactNativeFeatureFlags::dangerouslyReset(); +} + +void ReactInstanceIntegrationTest::initializeRuntime(std::string_view script) { + react::ReactInstance::JSRuntimeFlags flags{ + .isProfiling = false, + }; + instance->initializeRuntime(flags, [](jsi::Runtime& rt) { + // NOTE: RN's console polyfill (included in prelude.js.h) depends on the + // native logging hook being installed, even if it's a noop. + facebook::react::bindNativeLogger(rt, [](auto, auto) {}); + }); + + messageQueueThread->tick(); + + std::string init(script); + // JS calls no longer buffered after calling loadScript + instance->loadScript(std::make_unique(init), ""); +} + +void ReactInstanceIntegrationTest::send( + const std::string& method, + const folly::dynamic& params) { + folly::dynamic request = folly::dynamic::object(); + + request["method"] = method; + request["id"] = id_++; + request["params"] = params; + + sendJSONString(folly::toJson(request)); +} + +void ReactInstanceIntegrationTest::sendJSONString(const std::string& message) { + // The runtime must be initialized and connected to before messaging + clientToVM_->sendMessage(message); +} + +jsi::Value ReactInstanceIntegrationTest::run(const std::string& script) { + auto runtimeExecutor = instance->getUnbufferedRuntimeExecutor(); + auto ret = jsi::Value::undefined(); + + runtimeExecutor([script, &ret](jsi::Runtime& rt) { + ret = rt.evaluateJavaScript( + std::make_unique(script), ""); + }); + + messageQueueThread->flush(); + + while (verbose_ && errorHandler->size() > 0) { + LOG(INFO) << "Error: " << errorHandler->getLastError().getMessage(); + } + + return ret; +} + +bool ReactInstanceIntegrationTest::verbose(bool isVerbose) { + const bool previous = verbose_; + verbose_ = isVerbose; + return previous; +} + +#pragma endregion + +TEST_F(ReactInstanceIntegrationTest, RuntimeEvalTest) { + auto val = run("1 + 2"); + EXPECT_EQ(val.asNumber(), 3); +} + +TEST_P(ReactInstanceIntegrationTestWithFlags, ConsoleLog) { + EXPECT_CALL( + getRemoteConnection(), + onMessage(JsonParsed( + AtJsonPtr("/method", Eq("Runtime.executionContextCreated"))))); + + EXPECT_CALL( + getRemoteConnection(), onMessage(JsonParsed(AtJsonPtr("/id", Eq(1))))); + + InSequence s; + + EXPECT_CALL( + getRemoteConnection(), + onMessage(JsonParsed(AllOf( + AtJsonPtr("/params/args/0/value", Eq("Hello, World!")), + AtJsonPtr("/method", Eq("Runtime.consoleAPICalled")))))); + + EXPECT_CALL(getRemoteConnection(), onDisconnect()); + + send("Runtime.enable"); + run("console.log('Hello, World!');"); +} + +INSTANTIATE_TEST_SUITE_P( + ReactInstanceVaryingInspectorFlags, + ReactInstanceIntegrationTestWithFlags, + ::testing::Values( + InspectorFlagOverrides{ + .enableCxxInspectorPackagerConnection = false, + .enableModernCDPRegistry = false}, + InspectorFlagOverrides{ + .enableCxxInspectorPackagerConnection = true, + .enableModernCDPRegistry = false}, + InspectorFlagOverrides{ + .enableCxxInspectorPackagerConnection = true, + .enableModernCDPRegistry = true})); + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h new file mode 100644 index 00000000000000..e141d6925d4128 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include "InspectorMocks.h" +#include "ReactNativeMocks.h" +#include "UniquePtrFactory.h" +#include "utils/InspectorFlagOverridesGuard.h" + +#include +#include +#include +#include + +#include +#include + +namespace facebook::react::jsinspector_modern { + +using namespace ::testing; + +struct FeatureFlags { + const bool enableCxxInspectorPackagerConnection = true; + const bool enableModernCDPRegistry = true; +}; + +class ReactInstanceIntegrationTest : public Test { + protected: + ReactInstanceIntegrationTest(); + + void SetUp() override; + void TearDown() override; + + jsi::Value run(const std::string& script); + bool verbose(bool isVerbose); + + void send( + const std::string& method, + const folly::dynamic& params = folly::dynamic::object()); + void sendJSONString(const std::string& message); + + jsi::Runtime* runtime; + std::unique_ptr instance; + std::shared_ptr messageQueueThread; + std::shared_ptr errorHandler; + + MockRemoteConnection& getRemoteConnection() { + EXPECT_EQ(mockRemoteConnections_.objectsVended(), 1); + auto rawPtr = mockRemoteConnections_[0]; + assert(rawPtr); + return *rawPtr; + } + + private: + void initializeRuntime(std::string_view script); + + size_t id_ = 1; + bool verbose_ = false; + std::optional pageId_; + UniquePtrFactory mockRemoteConnections_; + std::unique_ptr clientToVM_; + folly::QueuedImmediateExecutor immediateExecutor_; +}; + +class ReactInstanceIntegrationTestWithFlags + : public ReactInstanceIntegrationTest, + public ::testing::WithParamInterface { + protected: + ReactInstanceIntegrationTestWithFlags() : inspectorFlagsGuard_(GetParam()) {} + + private: + InspectorFlagOverridesGuard inspectorFlagsGuard_; +}; +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.cpp new file mode 100644 index 00000000000000..aa74f01cbc2f33 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ReactNativeMocks.h" + +namespace facebook::react::jsinspector_modern { + +// +// MockMessageQueueThread +// + +void MockMessageQueueThread::runOnQueue(std::function&& func) { + callbackQueue_.push(func); +} + +void MockMessageQueueThread::tick() { + if (!callbackQueue_.empty()) { + auto callback = callbackQueue_.front(); + callback(); + callbackQueue_.pop(); + } +} + +void MockMessageQueueThread::guardedTick() { + try { + tick(); + } catch (const std::exception& e) { + // For easier debugging + FAIL() << e.what(); + } +} + +void MockMessageQueueThread::flush() { + while (!callbackQueue_.empty()) { + tick(); + } +} + +size_t MockMessageQueueThread::size() { + return callbackQueue_.size(); +} + +void MockMessageQueueThread::quitSynchronous() { + assert(false && "Not implemented"); +} +void MockMessageQueueThread::runOnQueueSync(std::function&& callback) { + callback(); +} + +// +// ErrorUtils +// +jsi::Value ErrorUtils::get(jsi::Runtime& rt, const jsi::PropNameID& name) { + auto methodName = name.utf8(rt); + + if (methodName == "reportFatalError") { + return jsi::Function::createFromHostFunction( + rt, + name, + 1, + [this]( + jsi::Runtime& runtime, + /* thisValue */ const jsi::Value&, + const jsi::Value* arguments, + size_t count) { + if (count >= 1) { + auto value = jsi::Value(runtime, arguments[0]); + auto error = jsi::JSError(runtime, std::move(value)); + LOG(INFO) << "JSI Fatal: " << error.getMessage(); + reportFatalError(std::move(error)); + } + return jsi::Value::undefined(); + }); + } else { + throw std::runtime_error("Unknown method: " + methodName); + } +} + +size_t ErrorUtils::size() { + return errors_.size(); +} + +jsi::JSError ErrorUtils::getLastError() { + auto error = errors_.back(); + errors_.pop_back(); + return error; +} + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h new file mode 100644 index 00000000000000..5eea24259aab01 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace facebook::react::jsinspector_modern { + +class MockTimerRegistry : public react::PlatformTimerRegistry { + public: + MOCK_METHOD2(createTimer, void(uint32_t, double)); + MOCK_METHOD2(createRecurringTimer, void(uint32_t, double)); + MOCK_METHOD1(deleteTimer, void(uint32_t)); +}; + +class MockMessageQueueThread : public react::MessageQueueThread { + public: + void runOnQueue(std::function&& func) override; + + // Unused + void runOnQueueSync(std::function&&) override; + + // Unused + void quitSynchronous() override; + + void tick(); + + void flush(); + + void guardedTick(); + + size_t size(); + + private: + std::queue> callbackQueue_; +}; + +class ErrorUtils : public jsi::HostObject { + public: + jsi::Value get(jsi::Runtime& rt, const jsi::PropNameID& name) override; + + void reportFatalError(jsi::JSError&& error) { + errors_.push_back(std::move(error)); + } + + size_t size(); + + jsi::JSError getLastError(); + + private: + std::vector errors_; +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.cpp index ee842d237dcd31..f46c98fab83a87 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#include - #include #include @@ -18,19 +16,19 @@ namespace facebook::react::jsinspector_modern { JsiIntegrationTestGenericEngineAdapter::JsiIntegrationTestGenericEngineAdapter( folly::Executor& jsExecutor) - : runtime_{hermes::makeHermesRuntime()}, jsExecutor_{jsExecutor} {} - -std::unique_ptr -JsiIntegrationTestGenericEngineAdapter::createAgentDelegate( - FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr, - const ExecutionContextDescription&) { - return std::unique_ptr( - new FallbackRuntimeAgentDelegate( - frontendChannel, - sessionState, - "Generic engine (" + runtime_->description() + ")")); + : runtime_{hermes::makeHermesRuntime()}, + jsExecutor_{jsExecutor}, + runtimeTargetDelegate_{ + "Generic engine (" + runtime_->description() + ")"} {} + +/* static */ InspectorFlagOverrides +JsiIntegrationTestGenericEngineAdapter::getInspectorFlagOverrides() noexcept { + return {.enableModernCDPRegistry = true}; +} + +RuntimeTargetDelegate& +JsiIntegrationTestGenericEngineAdapter::getRuntimeTargetDelegate() { + return runtimeTargetDelegate_; } jsi::Runtime& JsiIntegrationTestGenericEngineAdapter::getRuntime() diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h index 665477e303b644..836d09530bfff8 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h @@ -7,6 +7,9 @@ #pragma once +#include "../utils/InspectorFlagOverridesGuard.h" + +#include #include #include @@ -21,16 +24,13 @@ namespace facebook::react::jsinspector_modern { * JSI-compatible engine, with no engine-specific CDP support. Uses Hermes under * the hood, without Hermes's CDP support. */ -class JsiIntegrationTestGenericEngineAdapter : public RuntimeTargetDelegate { +class JsiIntegrationTestGenericEngineAdapter { public: explicit JsiIntegrationTestGenericEngineAdapter(folly::Executor& jsExecutor); - virtual std::unique_ptr createAgentDelegate( - FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription) override; + static InspectorFlagOverrides getInspectorFlagOverrides() noexcept; + + RuntimeTargetDelegate& getRuntimeTargetDelegate(); jsi::Runtime& getRuntime() const noexcept; @@ -39,6 +39,7 @@ class JsiIntegrationTestGenericEngineAdapter : public RuntimeTargetDelegate { private: std::unique_ptr runtime_; folly::Executor& jsExecutor_; + jsinspector_modern::FallbackRuntimeTargetDelegate runtimeTargetDelegate_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.cpp index 57efca34257a2e..9720e927ff01ab 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.cpp @@ -5,35 +5,30 @@ * LICENSE file in the root directory of this source tree. */ -#include - -#include - #include "JsiIntegrationTestHermesEngineAdapter.h" -using facebook::hermes::makeHermesRuntime; - namespace facebook::react::jsinspector_modern { JsiIntegrationTestHermesEngineAdapter::JsiIntegrationTestHermesEngineAdapter( folly::Executor& jsExecutor) - : runtime_{hermes::makeHermesRuntime()}, jsExecutor_{jsExecutor} {} - -std::unique_ptr -JsiIntegrationTestHermesEngineAdapter::createAgentDelegate( - FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription) { - return std::unique_ptr( - new HermesRuntimeAgentDelegate( - frontendChannel, - sessionState, - std::move(previouslyExportedState), - executionContextDescription, - runtime_, - getRuntimeExecutor())); + : runtime_{hermes::makeHermesRuntime( + ::hermes::vm::RuntimeConfig::Builder() + .withCompilationMode( + ::hermes::vm::CompilationMode::ForceLazyCompilation) + .build())}, + jsExecutor_{jsExecutor}, + runtimeTargetDelegate_{runtime_} {} + +/* static */ InspectorFlagOverrides +JsiIntegrationTestHermesEngineAdapter::getInspectorFlagOverrides() noexcept { + return { + .enableModernCDPRegistry = true, + }; +} + +RuntimeTargetDelegate& +JsiIntegrationTestHermesEngineAdapter::getRuntimeTargetDelegate() { + return runtimeTargetDelegate_; } jsi::Runtime& JsiIntegrationTestHermesEngineAdapter::getRuntime() diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h index 08c35800e257d7..8bf3b2dcb86a55 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h @@ -7,10 +7,13 @@ #pragma once +#include "../utils/InspectorFlagOverridesGuard.h" + #include #include #include +#include #include #include @@ -18,19 +21,16 @@ namespace facebook::react::jsinspector_modern { /** - * An engine adapter for JsiIntegrationTest that uses Hermes (and Hermes's - * CDP support). + * An engine adapter for JsiIntegrationTest that uses Hermes (and Hermes' + * modern CDPAgent API). */ -class JsiIntegrationTestHermesEngineAdapter : public RuntimeTargetDelegate { +class JsiIntegrationTestHermesEngineAdapter { public: explicit JsiIntegrationTestHermesEngineAdapter(folly::Executor& jsExecutor); - virtual std::unique_ptr createAgentDelegate( - FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription) override; + static InspectorFlagOverrides getInspectorFlagOverrides() noexcept; + + RuntimeTargetDelegate& getRuntimeTargetDelegate(); jsi::Runtime& getRuntime() const noexcept; @@ -39,6 +39,7 @@ class JsiIntegrationTestHermesEngineAdapter : public RuntimeTargetDelegate { private: std::shared_ptr runtime_; folly::Executor& jsExecutor_; + HermesRuntimeTargetDelegate runtimeTargetDelegate_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h new file mode 100644 index 00000000000000..994222a3d5b307 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h @@ -0,0 +1,635 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @polyfill + * @nolint + * @format + */ + +/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, no-control-regex */ + +#pragma once + +constexpr std::string_view preludeJsCode = R"___( +(function (global, __DEV__) {const inspect = (function () { + // Copyright Joyent, Inc. and other Node contributors. + // + // 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. + // + // https://github.com/joyent/node/blob/master/lib/util.js + + function inspect(obj, opts) { + var ctx = { + seen: [], + formatValueCalls: 0, + stylize: stylizeNoColor, + }; + return formatValue(ctx, obj, opts.depth); + } + + function stylizeNoColor(str, styleType) { + return str; + } + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function (val, idx) { + hash[val] = true; + }); + + return hash; + } + + function formatValue(ctx, value, recurseTimes) { + ctx.formatValueCalls++; + if (ctx.formatValueCalls > 200) { + return `[TOO BIG formatValueCalls ${ctx.formatValueCalls} exceeded limit of 200]`; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if ( + isError(value) && + (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0) + ) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', + array = false, + braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function (key) { + return formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + key, + array, + ); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = + "'" + + JSON.stringify(value) + .replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + + "'"; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) return ctx.stylize('null', 'null'); + } + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push( + formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + String(i), + true, + ), + ); + } else { + output.push(''); + } + } + keys.forEach(function (key) { + if (!key.match(/^\d+$/)) { + output.push( + formatProperty(ctx, value, recurseTimes, visibleKeys, key, true), + ); + } + }); + return output; + } + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || {value: value[key]}; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str + .split('\n') + .map(function (line) { + return ' ' + line; + }) + .join('\n') + .slice(2); + } else { + str = + '\n' + + str + .split('\n') + .map(function (line) { + return ' ' + line; + }) + .join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, name.length - 1); + name = ctx.stylize(name, 'name'); + } else { + name = name + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function (prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return ( + braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1] + ); + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return ( + isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error) + ); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + return inspect; +})(); + +const OBJECT_COLUMN_NAME = '(index)'; +const LOG_LEVELS = { + trace: 0, + info: 1, + warn: 2, + error: 3, +}; +const INSPECTOR_LEVELS = []; +INSPECTOR_LEVELS[LOG_LEVELS.trace] = 'debug'; +INSPECTOR_LEVELS[LOG_LEVELS.info] = 'log'; +INSPECTOR_LEVELS[LOG_LEVELS.warn] = 'warning'; +INSPECTOR_LEVELS[LOG_LEVELS.error] = 'error'; + +// Strip the inner function in getNativeLogFunction(), if in dev also +// strip method printing to originalConsole. +const INSPECTOR_FRAMES_TO_SKIP = __DEV__ ? 2 : 1; + +function getNativeLogFunction(level) { + return function () { + let str; + if (arguments.length === 1 && typeof arguments[0] === 'string') { + str = arguments[0]; + } else { + str = Array.prototype.map + .call(arguments, function (arg) { + return inspect(arg, {depth: 10}); + }) + .join(', '); + } + + // TRICKY + // If more than one argument is provided, the code above collapses them all + // into a single formatted string. This transform wraps string arguments in + // single quotes (e.g. "foo" -> "'foo'") which then breaks the "Warning:" + // check below. So it's important that we look at the first argument, rather + // than the formatted argument string. + const firstArg = arguments[0]; + + let logLevel = level; + if ( + typeof firstArg === 'string' && + firstArg.slice(0, 9) === 'Warning: ' && + logLevel >= LOG_LEVELS.error + ) { + // React warnings use console.error so that a stack trace is shown, + // but we don't (currently) want these to show a redbox + // (Note: Logic duplicated in ExceptionsManager.js.) + logLevel = LOG_LEVELS.warn; + } + if (global.__inspectorLog) { + global.__inspectorLog( + INSPECTOR_LEVELS[logLevel], + str, + [].slice.call(arguments), + INSPECTOR_FRAMES_TO_SKIP, + ); + } + if (groupStack.length) { + str = groupFormat('', str); + } + global.nativeLoggingHook(str, logLevel); + }; +} + +function repeat(element, n) { + return Array.apply(null, Array(n)).map(function () { + return element; + }); +} + +function consoleTablePolyfill(rows) { + // convert object -> array + if (!Array.isArray(rows)) { + var data = rows; + rows = []; + for (var key in data) { + if (data.hasOwnProperty(key)) { + var row = data[key]; + row[OBJECT_COLUMN_NAME] = key; + rows.push(row); + } + } + } + if (rows.length === 0) { + global.nativeLoggingHook('', LOG_LEVELS.info); + return; + } + + var columns = Object.keys(rows[0]).sort(); + var stringRows = []; + var columnWidths = []; + + // Convert each cell to a string. Also + // figure out max cell width for each column + columns.forEach(function (k, i) { + columnWidths[i] = k.length; + for (var j = 0; j < rows.length; j++) { + var cellStr = (rows[j][k] || '?').toString(); + stringRows[j] = stringRows[j] || []; + stringRows[j][i] = cellStr; + columnWidths[i] = Math.max(columnWidths[i], cellStr.length); + } + }); + + // Join all elements in the row into a single string with | separators + // (appends extra spaces to each cell to make separators | aligned) + function joinRow(row, space) { + var cells = row.map(function (cell, i) { + var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join(''); + return cell + extraSpaces; + }); + space = space || ' '; + return cells.join(space + '|' + space); + } + + var separators = columnWidths.map(function (columnWidth) { + return repeat('-', columnWidth).join(''); + }); + var separatorRow = joinRow(separators, '-'); + var header = joinRow(columns); + var table = [header, separatorRow]; + + for (var i = 0; i < rows.length; i++) { + table.push(joinRow(stringRows[i])); + } + + // Notice extra empty line at the beginning. + // Native logging hook adds "RCTLog >" at the front of every + // logged string, which would shift the header and screw up + // the table + global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info); +} + +const GROUP_PAD = '\u2502'; // Box light vertical +const GROUP_OPEN = '\u2510'; // Box light down+left +const GROUP_CLOSE = '\u2518'; // Box light up+left + +const groupStack = []; + +function groupFormat(prefix, msg) { + // Insert group formatting before the console message + return groupStack.join('') + prefix + ' ' + (msg || ''); +} + +function consoleGroupPolyfill(label) { + global.nativeLoggingHook(groupFormat(GROUP_OPEN, label), LOG_LEVELS.info); + groupStack.push(GROUP_PAD); +} + +function consoleGroupCollapsedPolyfill(label) { + global.nativeLoggingHook(groupFormat(GROUP_CLOSE, label), LOG_LEVELS.info); + groupStack.push(GROUP_PAD); +} + +function consoleGroupEndPolyfill() { + groupStack.pop(); + global.nativeLoggingHook(groupFormat(GROUP_CLOSE), LOG_LEVELS.info); +} + +function consoleAssertPolyfill(expression, label) { + if (!expression) { + global.nativeLoggingHook('Assertion failed: ' + label, LOG_LEVELS.error); + } +} + +if (global.nativeLoggingHook) { + const originalConsole = global.console; + // Preserve the original `console` as `originalConsole` + if (__DEV__ && originalConsole) { + const descriptor = Object.getOwnPropertyDescriptor(global, 'console'); + if (descriptor) { + Object.defineProperty(global, 'originalConsole', descriptor); + } + } + + global.console = { + ...(originalConsole ?? {}), + error: getNativeLogFunction(LOG_LEVELS.error), + info: getNativeLogFunction(LOG_LEVELS.info), + log: getNativeLogFunction(LOG_LEVELS.info), + warn: getNativeLogFunction(LOG_LEVELS.warn), + trace: getNativeLogFunction(LOG_LEVELS.trace), + debug: getNativeLogFunction(LOG_LEVELS.trace), + table: consoleTablePolyfill, + group: consoleGroupPolyfill, + groupEnd: consoleGroupEndPolyfill, + groupCollapsed: consoleGroupCollapsedPolyfill, + assert: consoleAssertPolyfill, + }; + + Object.defineProperty(console, '_isPolyfilled', { + value: true, + enumerable: false, + }); + + // If available, also call the original `console` method since that is + // sometimes useful. Ex: on OS X, this will let you see rich output in + // the Safari Web Inspector console. + if (__DEV__ && originalConsole) { + Object.keys(console).forEach(methodName => { + const reactNativeMethod = console[methodName]; + if ( + originalConsole[methodName] && + reactNativeMethod !== originalConsole[methodName] + ) { + console[methodName] = function () { + originalConsole[methodName](...arguments); + reactNativeMethod.apply(console, arguments); + }; + } + }); + + // The following methods are not supported by this polyfill but + // we still should pass them to original console if they are + // supported by it. + ['clear', 'dir', 'dirxml', 'profile', 'profileEnd'].forEach(methodName => { + if (typeof originalConsole[methodName] === 'function') { + console[methodName] = function () { + originalConsole[methodName](...arguments); + }; + } + }); + } +} else if (!global.console) { + function stub() {} + const log = global.print || stub; + + global.console = { + debug: log, + error: log, + info: log, + log: log, + trace: log, + warn: log, + assert(expression, label) { + if (!expression) { + log('Assertion failed: ' + label); + } + }, + clear: stub, + dir: stub, + dirxml: stub, + group: stub, + groupCollapsed: stub, + groupEnd: stub, + profile: stub, + profileEnd: stub, + table: stub, + }; + + Object.defineProperty(console, '_isPolyfilled', { + value: true, + enumerable: false, + }); +}})(globalThis, true) +)___"; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.cpp new file mode 100644 index 00000000000000..2f50fbbd667649 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "InspectorFlagOverridesGuard.h" + +#include +#include +#include + +#include + +namespace facebook::react::jsinspector_modern { + +/** + * Helper class that maps \c InspectorFlagOverrides to the shape of \c + * ReactNativeFeatureFlagsDefaults. + */ +class ReactNativeFeatureFlagsOverrides + : public ReactNativeFeatureFlagsDefaults { + public: + explicit ReactNativeFeatureFlagsOverrides( + const InspectorFlagOverrides& overrides) + : overrides_(overrides) {} + + bool inspectorEnableCxxInspectorPackagerConnection() override { + return overrides_.enableCxxInspectorPackagerConnection.value_or( + ReactNativeFeatureFlagsDefaults:: + inspectorEnableCxxInspectorPackagerConnection()); + } + + bool inspectorEnableModernCDPRegistry() override { + return overrides_.enableModernCDPRegistry.value_or( + ReactNativeFeatureFlagsDefaults::inspectorEnableModernCDPRegistry()); + } + + private: + InspectorFlagOverrides overrides_; +}; + +InspectorFlagOverridesGuard::InspectorFlagOverridesGuard( + const InspectorFlagOverrides& overrides) { + InspectorFlags::getInstance().dangerouslyResetFlags(); + ReactNativeFeatureFlags::override( + std::make_unique(overrides)); +} + +InspectorFlagOverridesGuard::~InspectorFlagOverridesGuard() { + ReactNativeFeatureFlags::dangerouslyReset(); +} + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h new file mode 100644 index 00000000000000..cbf8e779b76149 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace facebook::react::jsinspector_modern { + +/** + * Overridden \c InspectorFlags values for use in tests. + */ +struct InspectorFlagOverrides { + // NOTE: Keep these entries in sync with ReactNativeFeatureFlagsOverrides in + // the implementation file. + std::optional enableCxxInspectorPackagerConnection; + std::optional enableModernCDPRegistry; +}; + +/** + * A RAII helper to set up and tear down \c InspectorFlags (via \c + * ReactNativeFeatureFlags) with overrides for the lifetime of a test object. + */ +class InspectorFlagOverridesGuard { + public: + explicit InspectorFlagOverridesGuard(const InspectorFlagOverrides& overrides); + InspectorFlagOverridesGuard(const InspectorFlagOverridesGuard&) = delete; + InspectorFlagOverridesGuard(InspectorFlagOverridesGuard&&) = default; + InspectorFlagOverridesGuard& operator=(const InspectorFlagOverridesGuard&) = + delete; + InspectorFlagOverridesGuard& operator=(InspectorFlagOverridesGuard&&) = + default; + + ~InspectorFlagOverridesGuard(); +}; + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h b/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h index 228f0948d8f3b8..122d9f75b7db0c 100644 --- a/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h +++ b/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h @@ -24,12 +24,11 @@ class CallbackWrapper : public LongLivedObject { jsi::Function&& callback, jsi::Runtime& runtime, std::shared_ptr jsInvoker) - : callback_(std::move(callback)), - runtime_(runtime), + : LongLivedObject(runtime), + callback_(std::move(callback)), jsInvoker_(std::move(jsInvoker)) {} jsi::Function callback_; - jsi::Runtime& runtime_; std::shared_ptr jsInvoker_; public: @@ -39,7 +38,7 @@ class CallbackWrapper : public LongLivedObject { std::shared_ptr jsInvoker) { auto wrapper = std::shared_ptr(new CallbackWrapper( std::move(callback), runtime, std::move(jsInvoker))); - LongLivedObjectCollection::get().add(wrapper); + LongLivedObjectCollection::get(runtime).add(wrapper); return wrapper; } diff --git a/packages/react-native/ReactCommon/react/bridging/Function.h b/packages/react-native/ReactCommon/react/bridging/Function.h index 58cb238ac08c3b..fc124bc0a7f266 100644 --- a/packages/react-native/ReactCommon/react/bridging/Function.h +++ b/packages/react-native/ReactCommon/react/bridging/Function.h @@ -64,9 +64,8 @@ class AsyncCallback { if (auto wrapper = callback_->wrapper_.lock()) { auto fn = [callback = callback_, argsPtr = std::make_shared>( - std::make_tuple(std::forward(args)...))] { - callback->apply(std::move(*argsPtr)); - }; + std::make_tuple(std::forward(args)...))]( + jsi::Runtime&) { callback->apply(std::move(*argsPtr)); }; auto& jsInvoker = wrapper->jsInvoker(); if (priority) { @@ -85,9 +84,10 @@ class AsyncCallback { // Capture callback_ and not wrapper_. If callback_ is deallocated or the // JSVM is shutdown before the async task is scheduled, the underlying // function will have been deallocated. - auto fn = [callback = callback_, callImpl = std::move(callImpl)]() { + auto fn = [callback = callback_, + callImpl = std::move(callImpl)](jsi::Runtime& rt) { if (auto wrapper2 = callback->wrapper_.lock()) { - callImpl(wrapper2->runtime(), wrapper2->callback()); + callImpl(rt, wrapper2->callback()); } }; @@ -101,6 +101,9 @@ class AsyncCallback { } }; +// You must ensure that when invoking this you're located on the JS thread, or +// have exclusive control of the JS VM context. If you cannot ensure this, use +// AsyncCallback instead. template class SyncCallback { public: @@ -113,9 +116,19 @@ class SyncCallback { rt, std::move(jsInvoker))) {} - // Disallow moving to prevent function from get called on another thread. - SyncCallback(SyncCallback&&) = delete; - SyncCallback& operator=(SyncCallback&&) = delete; + // Disallow copying, as we can no longer safely destroy the callback + // from the destructor if there's multiple copies + SyncCallback(const SyncCallback&) = delete; + SyncCallback& operator=(const SyncCallback&) = delete; + + // Allow move + SyncCallback(SyncCallback&& other) noexcept + : wrapper_(std::move(other.wrapper_)) {} + + SyncCallback& operator=(SyncCallback&& other) noexcept { + wrapper_ = std::move(other.wrapper_); + return *this; + } ~SyncCallback() { if (auto wrapper = wrapper_.lock()) { diff --git a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp index 410f52d22ea9e7..9c6d7c38d86fb2 100644 --- a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp +++ b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp @@ -6,13 +6,27 @@ */ #include "LongLivedObject.h" +#include namespace facebook::react { // LongLivedObjectCollection -LongLivedObjectCollection& LongLivedObjectCollection::get() { - static LongLivedObjectCollection instance; - return instance; + +LongLivedObjectCollection& LongLivedObjectCollection::get( + jsi::Runtime& runtime) { + static std::unordered_map> + instances; + static std::mutex instancesMutex; + + std::scoped_lock lock(instancesMutex); + void* key = static_cast(&runtime); + auto entry = instances.find(key); + if (entry == instances.end()) { + entry = + instances.emplace(key, std::make_shared()) + .first; + } + return *(entry->second); } void LongLivedObjectCollection::add(std::shared_ptr so) { @@ -43,7 +57,7 @@ size_t LongLivedObjectCollection::size() const { // LongLivedObject void LongLivedObject::allowRelease() { - LongLivedObjectCollection::get().remove(this); + LongLivedObjectCollection::get(runtime_).remove(this); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h index f8ca6671da906e..d043a0a9a91940 100644 --- a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h +++ b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h @@ -7,6 +7,7 @@ #pragma once +#include #include #include #include @@ -31,8 +32,9 @@ class LongLivedObject { virtual void allowRelease(); protected: - LongLivedObject() = default; + explicit LongLivedObject(jsi::Runtime& runtime) : runtime_(runtime) {} virtual ~LongLivedObject() = default; + jsi::Runtime& runtime_; }; /** @@ -40,7 +42,7 @@ class LongLivedObject { */ class LongLivedObjectCollection { public: - static LongLivedObjectCollection& get(); + static LongLivedObjectCollection& get(jsi::Runtime& runtime); LongLivedObjectCollection() = default; LongLivedObjectCollection(const LongLivedObjectCollection&) = delete; diff --git a/packages/react-native/ReactCommon/react/bridging/Promise.h b/packages/react-native/ReactCommon/react/bridging/Promise.h index 058faea13d1f78..5a049c8574e5be 100644 --- a/packages/react-native/ReactCommon/react/bridging/Promise.h +++ b/packages/react-native/ReactCommon/react/bridging/Promise.h @@ -34,8 +34,9 @@ class AsyncPromise { }, jsInvoker)); - auto promiseHolder = std::make_shared(promise.asObject(rt)); - LongLivedObjectCollection::get().add(promiseHolder); + auto promiseHolder = + std::make_shared(rt, promise.asObject(rt)); + LongLivedObjectCollection::get(rt).add(promiseHolder); // The shared state can retain the promise holder weakly now. state_->promiseHolder = promiseHolder; @@ -71,7 +72,8 @@ class AsyncPromise { private: struct PromiseHolder : LongLivedObject { - PromiseHolder(jsi::Object p) : promise(std::move(p)) {} + PromiseHolder(jsi::Runtime& runtime, jsi::Object p) + : LongLivedObject(runtime), promise(std::move(p)) {} jsi::Object promise; }; diff --git a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp index e89c4eeaa2b131..45beaeff7b4e8a 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp @@ -316,7 +316,7 @@ TEST_F(BridgingTest, asyncCallbackInvalidation) { [](jsi::Runtime& rt, jsi::Function& f) { f.call(rt, "hello"); }); // LongLivedObjectCollection goes away before callback is executed - LongLivedObjectCollection::get().clear(); + LongLivedObjectCollection::get(rt).clear(); flushQueue(); diff --git a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h index 9b60ec82f691ed..7fef3c9726a258 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h @@ -17,18 +17,18 @@ namespace facebook::react { class TestCallInvoker : public CallInvoker { public: - void invokeAsync(std::function&& fn) noexcept override { + void invokeAsync(CallFunc&& fn) noexcept override { queue_.push_back(std::move(fn)); } - void invokeSync(std::function&&) override { + void invokeSync(CallFunc&&) override { FAIL() << "JSCallInvoker does not support invokeSync()"; } private: friend class BridgingTest; - std::list> queue_; + std::list queue_; }; class BridgingTest : public ::testing::Test { @@ -43,14 +43,14 @@ class BridgingTest : public ::testing::Test { rt(*runtime) {} ~BridgingTest() { - LongLivedObjectCollection::get().clear(); + LongLivedObjectCollection::get(rt).clear(); } void TearDown() override { flushQueue(); // After flushing the invoker queue, we shouldn't leak memory. - EXPECT_EQ(0, LongLivedObjectCollection::get().size()); + EXPECT_EQ(0, LongLivedObjectCollection::get(rt).size()); } jsi::Value eval(const std::string& js) { @@ -63,7 +63,7 @@ class BridgingTest : public ::testing::Test { void flushQueue() { while (!invoker->queue_.empty()) { - invoker->queue_.front()(); + invoker->queue_.front()(*runtime); invoker->queue_.pop_front(); rt.drainMicrotasks(); // Run microtasks every cycle. } diff --git a/packages/react-native/ReactCommon/react/config/.clang-tidy b/packages/react-native/ReactCommon/react/config/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/react/config/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/react/debug/react_native_assert.h b/packages/react-native/ReactCommon/react/debug/react_native_assert.h index 5f4036486bdce8..1d399d45421759 100644 --- a/packages/react-native/ReactCommon/react/debug/react_native_assert.h +++ b/packages/react-native/ReactCommon/react/debug/react_native_assert.h @@ -18,6 +18,8 @@ // For recoverable conditions that can be violated by user mistake (e.g. JS // code passes an unexpected prop value), consider react_native_expect instead. +#pragma once + #include "flags.h" #undef react_native_assert diff --git a/packages/react-native/ReactCommon/react/debug/react_native_expect.h b/packages/react-native/ReactCommon/react/debug/react_native_expect.h index 45656664101e43..cfc4d66f8da82a 100644 --- a/packages/react-native/ReactCommon/react/debug/react_native_expect.h +++ b/packages/react-native/ReactCommon/react/debug/react_native_expect.h @@ -20,6 +20,8 @@ // will see a helpful diagnostic (beyond a low level log). That concern is the // caller's responsibility. +#pragma once + #include "flags.h" #undef react_native_expect diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp index caec5678dd7b3c..163c9e238845fe 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<82f226df2b3824d03b755a042b20bec5>> + * @generated SignedSource<> */ /** @@ -25,34 +25,34 @@ bool ReactNativeFeatureFlags::commonTestFlag() { return getAccessor().commonTestFlag(); } +bool ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop() { + return getAccessor().batchRenderingUpdatesInEventLoop(); +} + bool ReactNativeFeatureFlags::enableBackgroundExecutor() { return getAccessor().enableBackgroundExecutor(); } -bool ReactNativeFeatureFlags::useModernRuntimeScheduler() { - return getAccessor().useModernRuntimeScheduler(); +bool ReactNativeFeatureFlags::enableCustomDrawOrderFabric() { + return getAccessor().enableCustomDrawOrderFabric(); +} + +bool ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash() { + return getAccessor().enableFixForClippedSubviewsCrash(); } bool ReactNativeFeatureFlags::enableMicrotasks() { return getAccessor().enableMicrotasks(); } -bool ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop() { - return getAccessor().batchRenderingUpdatesInEventLoop(); +bool ReactNativeFeatureFlags::enableMountHooksAndroid() { + return getAccessor().enableMountHooksAndroid(); } bool ReactNativeFeatureFlags::enableSpannableBuildingUnification() { return getAccessor().enableSpannableBuildingUnification(); } -bool ReactNativeFeatureFlags::enableCustomDrawOrderFabric() { - return getAccessor().enableCustomDrawOrderFabric(); -} - -bool ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash() { - return getAccessor().enableFixForClippedSubviewsCrash(); -} - bool ReactNativeFeatureFlags::inspectorEnableCxxInspectorPackagerConnection() { return getAccessor().inspectorEnableCxxInspectorPackagerConnection(); } @@ -61,6 +61,10 @@ bool ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry() { return getAccessor().inspectorEnableModernCDPRegistry(); } +bool ReactNativeFeatureFlags::useModernRuntimeScheduler() { + return getAccessor().useModernRuntimeScheduler(); +} + void ReactNativeFeatureFlags::override( std::unique_ptr provider) { getAccessor().override(std::move(provider)); diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h index 8f82ea192014c9..9f51ae019bc457 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<3bfae310dfd28040f4b80d1a1df8b7b3>> + * @generated SignedSource<> */ /** @@ -23,6 +23,10 @@ #include #include +#ifndef RN_EXPORT +#define RN_EXPORT __attribute__((visibility("default"))) +#endif + namespace facebook::react { /** @@ -36,52 +40,57 @@ class ReactNativeFeatureFlags { /** * Common flag for testing. Do NOT modify. */ - static bool commonTestFlag(); + RN_EXPORT static bool commonTestFlag(); /** - * Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used). + * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. */ - static bool enableBackgroundExecutor(); + RN_EXPORT static bool batchRenderingUpdatesInEventLoop(); /** - * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + * Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used). */ - static bool useModernRuntimeScheduler(); + RN_EXPORT static bool enableBackgroundExecutor(); /** - * Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution). + * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). */ - static bool enableMicrotasks(); + RN_EXPORT static bool enableCustomDrawOrderFabric(); /** - * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. + * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix */ - static bool batchRenderingUpdatesInEventLoop(); + RN_EXPORT static bool enableFixForClippedSubviewsCrash(); /** - * Uses new, deduplicated logic for constructing Android Spannables from text fragments + * Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution). */ - static bool enableSpannableBuildingUnification(); + RN_EXPORT static bool enableMicrotasks(); /** - * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). + * Enables the notification of mount operations to mount hooks on Android. */ - static bool enableCustomDrawOrderFabric(); + RN_EXPORT static bool enableMountHooksAndroid(); /** - * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix + * Uses new, deduplicated logic for constructing Android Spannables from text fragments */ - static bool enableFixForClippedSubviewsCrash(); + RN_EXPORT static bool enableSpannableBuildingUnification(); /** * Flag determining if the C++ implementation of InspectorPackagerConnection should be used instead of the per-platform one. This flag is global and should not be changed across React Host lifetimes. */ - static bool inspectorEnableCxxInspectorPackagerConnection(); + RN_EXPORT static bool inspectorEnableCxxInspectorPackagerConnection(); /** * Flag determining if the modern CDP backend should be enabled. This flag is global and should not be changed across React Host lifetimes. */ - static bool inspectorEnableModernCDPRegistry(); + RN_EXPORT static bool inspectorEnableModernCDPRegistry(); + + /** + * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + */ + RN_EXPORT static bool useModernRuntimeScheduler(); /** * Overrides the feature flags with the ones provided by the given provider @@ -101,7 +110,7 @@ class ReactNativeFeatureFlags { * std::make_unique()); * ``` */ - static void override( + RN_EXPORT static void override( std::unique_ptr provider); /** @@ -116,7 +125,7 @@ class ReactNativeFeatureFlags { * call `dangerouslyReset` after destroying the runtime and `override` again * before initializing the new one. */ - static void dangerouslyReset(); + RN_EXPORT static void dangerouslyReset(); private: ReactNativeFeatureFlags() = delete; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp index d46d461bfd4261..9adeb8f60d422d 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<2154292f89306f25289583537833a065>> + * @generated SignedSource<> */ /** @@ -47,8 +47,8 @@ bool ReactNativeFeatureFlagsAccessor::commonTestFlag() { return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::enableBackgroundExecutor() { - auto flagValue = enableBackgroundExecutor_.load(); +bool ReactNativeFeatureFlagsAccessor::batchRenderingUpdatesInEventLoop() { + auto flagValue = batchRenderingUpdatesInEventLoop_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -56,17 +56,17 @@ bool ReactNativeFeatureFlagsAccessor::enableBackgroundExecutor() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(1, "enableBackgroundExecutor"); + markFlagAsAccessed(1, "batchRenderingUpdatesInEventLoop"); - flagValue = currentProvider_->enableBackgroundExecutor(); - enableBackgroundExecutor_ = flagValue; + flagValue = currentProvider_->batchRenderingUpdatesInEventLoop(); + batchRenderingUpdatesInEventLoop_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::useModernRuntimeScheduler() { - auto flagValue = useModernRuntimeScheduler_.load(); +bool ReactNativeFeatureFlagsAccessor::enableBackgroundExecutor() { + auto flagValue = enableBackgroundExecutor_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -74,17 +74,17 @@ bool ReactNativeFeatureFlagsAccessor::useModernRuntimeScheduler() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(2, "useModernRuntimeScheduler"); + markFlagAsAccessed(2, "enableBackgroundExecutor"); - flagValue = currentProvider_->useModernRuntimeScheduler(); - useModernRuntimeScheduler_ = flagValue; + flagValue = currentProvider_->enableBackgroundExecutor(); + enableBackgroundExecutor_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::enableMicrotasks() { - auto flagValue = enableMicrotasks_.load(); +bool ReactNativeFeatureFlagsAccessor::enableCustomDrawOrderFabric() { + auto flagValue = enableCustomDrawOrderFabric_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -92,17 +92,17 @@ bool ReactNativeFeatureFlagsAccessor::enableMicrotasks() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(3, "enableMicrotasks"); + markFlagAsAccessed(3, "enableCustomDrawOrderFabric"); - flagValue = currentProvider_->enableMicrotasks(); - enableMicrotasks_ = flagValue; + flagValue = currentProvider_->enableCustomDrawOrderFabric(); + enableCustomDrawOrderFabric_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::batchRenderingUpdatesInEventLoop() { - auto flagValue = batchRenderingUpdatesInEventLoop_.load(); +bool ReactNativeFeatureFlagsAccessor::enableFixForClippedSubviewsCrash() { + auto flagValue = enableFixForClippedSubviewsCrash_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -110,17 +110,17 @@ bool ReactNativeFeatureFlagsAccessor::batchRenderingUpdatesInEventLoop() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(4, "batchRenderingUpdatesInEventLoop"); + markFlagAsAccessed(4, "enableFixForClippedSubviewsCrash"); - flagValue = currentProvider_->batchRenderingUpdatesInEventLoop(); - batchRenderingUpdatesInEventLoop_ = flagValue; + flagValue = currentProvider_->enableFixForClippedSubviewsCrash(); + enableFixForClippedSubviewsCrash_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::enableSpannableBuildingUnification() { - auto flagValue = enableSpannableBuildingUnification_.load(); +bool ReactNativeFeatureFlagsAccessor::enableMicrotasks() { + auto flagValue = enableMicrotasks_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -128,17 +128,17 @@ bool ReactNativeFeatureFlagsAccessor::enableSpannableBuildingUnification() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(5, "enableSpannableBuildingUnification"); + markFlagAsAccessed(5, "enableMicrotasks"); - flagValue = currentProvider_->enableSpannableBuildingUnification(); - enableSpannableBuildingUnification_ = flagValue; + flagValue = currentProvider_->enableMicrotasks(); + enableMicrotasks_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::enableCustomDrawOrderFabric() { - auto flagValue = enableCustomDrawOrderFabric_.load(); +bool ReactNativeFeatureFlagsAccessor::enableMountHooksAndroid() { + auto flagValue = enableMountHooksAndroid_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -146,17 +146,17 @@ bool ReactNativeFeatureFlagsAccessor::enableCustomDrawOrderFabric() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(6, "enableCustomDrawOrderFabric"); + markFlagAsAccessed(6, "enableMountHooksAndroid"); - flagValue = currentProvider_->enableCustomDrawOrderFabric(); - enableCustomDrawOrderFabric_ = flagValue; + flagValue = currentProvider_->enableMountHooksAndroid(); + enableMountHooksAndroid_ = flagValue; } return flagValue.value(); } -bool ReactNativeFeatureFlagsAccessor::enableFixForClippedSubviewsCrash() { - auto flagValue = enableFixForClippedSubviewsCrash_.load(); +bool ReactNativeFeatureFlagsAccessor::enableSpannableBuildingUnification() { + auto flagValue = enableSpannableBuildingUnification_.load(); if (!flagValue.has_value()) { // This block is not exclusive but it is not necessary. @@ -164,10 +164,10 @@ bool ReactNativeFeatureFlagsAccessor::enableFixForClippedSubviewsCrash() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(7, "enableFixForClippedSubviewsCrash"); + markFlagAsAccessed(7, "enableSpannableBuildingUnification"); - flagValue = currentProvider_->enableFixForClippedSubviewsCrash(); - enableFixForClippedSubviewsCrash_ = flagValue; + flagValue = currentProvider_->enableSpannableBuildingUnification(); + enableSpannableBuildingUnification_ = flagValue; } return flagValue.value(); @@ -209,6 +209,24 @@ bool ReactNativeFeatureFlagsAccessor::inspectorEnableModernCDPRegistry() { return flagValue.value(); } +bool ReactNativeFeatureFlagsAccessor::useModernRuntimeScheduler() { + auto flagValue = useModernRuntimeScheduler_.load(); + + if (!flagValue.has_value()) { + // This block is not exclusive but it is not necessary. + // If multiple threads try to initialize the feature flag, we would only + // be accessing the provider multiple times but the end state of this + // instance and the returned flag value would be the same. + + markFlagAsAccessed(10, "useModernRuntimeScheduler"); + + flagValue = currentProvider_->useModernRuntimeScheduler(); + useModernRuntimeScheduler_ = flagValue; + } + + return flagValue.value(); +} + void ReactNativeFeatureFlagsAccessor::override( std::unique_ptr provider) { if (wasOverridden_) { diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h index b177bfe53b6b33..5199fc1ca59371 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<95487968b66d40e1ec53936b06084931>> + * @generated SignedSource<> */ /** @@ -32,15 +32,16 @@ class ReactNativeFeatureFlagsAccessor { ReactNativeFeatureFlagsAccessor(); bool commonTestFlag(); - bool enableBackgroundExecutor(); - bool useModernRuntimeScheduler(); - bool enableMicrotasks(); bool batchRenderingUpdatesInEventLoop(); - bool enableSpannableBuildingUnification(); + bool enableBackgroundExecutor(); bool enableCustomDrawOrderFabric(); bool enableFixForClippedSubviewsCrash(); + bool enableMicrotasks(); + bool enableMountHooksAndroid(); + bool enableSpannableBuildingUnification(); bool inspectorEnableCxxInspectorPackagerConnection(); bool inspectorEnableModernCDPRegistry(); + bool useModernRuntimeScheduler(); void override(std::unique_ptr provider); @@ -51,18 +52,19 @@ class ReactNativeFeatureFlagsAccessor { std::unique_ptr currentProvider_; bool wasOverridden_; - std::array, 10> accessedFeatureFlags_; + std::array, 11> accessedFeatureFlags_; std::atomic> commonTestFlag_; - std::atomic> enableBackgroundExecutor_; - std::atomic> useModernRuntimeScheduler_; - std::atomic> enableMicrotasks_; std::atomic> batchRenderingUpdatesInEventLoop_; - std::atomic> enableSpannableBuildingUnification_; + std::atomic> enableBackgroundExecutor_; std::atomic> enableCustomDrawOrderFabric_; std::atomic> enableFixForClippedSubviewsCrash_; + std::atomic> enableMicrotasks_; + std::atomic> enableMountHooksAndroid_; + std::atomic> enableSpannableBuildingUnification_; std::atomic> inspectorEnableCxxInspectorPackagerConnection_; std::atomic> inspectorEnableModernCDPRegistry_; + std::atomic> useModernRuntimeScheduler_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h index ce2aadae3b63ce..85f6d322e89d79 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<4832483bb3648380f2bb9312311f579c>> + * @generated SignedSource<<62de1b0e27590ad769296358a4f42c7a>> */ /** @@ -31,31 +31,31 @@ class ReactNativeFeatureFlagsDefaults : public ReactNativeFeatureFlagsProvider { return false; } - bool enableBackgroundExecutor() override { + bool batchRenderingUpdatesInEventLoop() override { return false; } - bool useModernRuntimeScheduler() override { + bool enableBackgroundExecutor() override { return false; } - bool enableMicrotasks() override { + bool enableCustomDrawOrderFabric() override { return false; } - bool batchRenderingUpdatesInEventLoop() override { + bool enableFixForClippedSubviewsCrash() override { return false; } - bool enableSpannableBuildingUnification() override { + bool enableMicrotasks() override { return false; } - bool enableCustomDrawOrderFabric() override { + bool enableMountHooksAndroid() override { return false; } - bool enableFixForClippedSubviewsCrash() override { + bool enableSpannableBuildingUnification() override { return false; } @@ -66,6 +66,10 @@ class ReactNativeFeatureFlagsDefaults : public ReactNativeFeatureFlagsProvider { bool inspectorEnableModernCDPRegistry() override { return false; } + + bool useModernRuntimeScheduler() override { + return false; + } }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h index f6f55b5fc15e4a..48ec9f28697f87 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<<3117fc0389416297369a47ee480eb906>> */ /** @@ -26,15 +26,16 @@ class ReactNativeFeatureFlagsProvider { virtual ~ReactNativeFeatureFlagsProvider() = default; virtual bool commonTestFlag() = 0; - virtual bool enableBackgroundExecutor() = 0; - virtual bool useModernRuntimeScheduler() = 0; - virtual bool enableMicrotasks() = 0; virtual bool batchRenderingUpdatesInEventLoop() = 0; - virtual bool enableSpannableBuildingUnification() = 0; + virtual bool enableBackgroundExecutor() = 0; virtual bool enableCustomDrawOrderFabric() = 0; virtual bool enableFixForClippedSubviewsCrash() = 0; + virtual bool enableMicrotasks() = 0; + virtual bool enableMountHooksAndroid() = 0; + virtual bool enableSpannableBuildingUnification() = 0; virtual bool inspectorEnableCxxInspectorPackagerConnection() = 0; virtual bool inspectorEnableModernCDPRegistry() = 0; + virtual bool useModernRuntimeScheduler() = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/.clang-tidy b/packages/react-native/ReactCommon/react/nativemodule/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.cpp index d1704b57b9f53e..f0de6f80d20c97 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.cpp @@ -33,24 +33,23 @@ CxxModule::Callback makeTurboCxxModuleCallback( return; } - strongWrapper->jsInvoker().invokeAsync([weakWrapper, args]() { - auto strongWrapper2 = weakWrapper.lock(); - if (!strongWrapper2) { - return; - } + strongWrapper->jsInvoker().invokeAsync( + [weakWrapper, args](jsi::Runtime& rt) { + auto strongWrapper2 = weakWrapper.lock(); + if (!strongWrapper2) { + return; + } - std::vector innerArgs; - for (auto& a : args) { - innerArgs.push_back( - jsi::valueFromDynamic(strongWrapper2->runtime(), a)); - } - strongWrapper2->callback().call( - strongWrapper2->runtime(), - (const jsi::Value*)innerArgs.data(), - innerArgs.size()); + std::vector innerArgs; + innerArgs.reserve(args.size()); + for (auto& a : args) { + innerArgs.push_back(jsi::valueFromDynamic(rt, a)); + } + strongWrapper2->callback().call( + rt, (const jsi::Value*)innerArgs.data(), innerArgs.size()); - strongWrapper2->destroy(); - }); + strongWrapper2->destroy(); + }); wrapperWasCalled = true; }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp index b0924be26e1ab8..fe2411974d20cd 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp @@ -40,25 +40,22 @@ TurboModule::TurboModule( : name_(std::move(name)), jsInvoker_(std::move(jsInvoker)) {} void TurboModule::emitDeviceEvent( - jsi::Runtime& runtime, const std::string& eventName, ArgFactory argFactory) { - jsInvoker_->invokeAsync([&runtime, eventName, argFactory]() { - jsi::Value emitter = - runtime.global().getProperty(runtime, "__rctDeviceEventEmitter"); + jsInvoker_->invokeAsync([eventName, argFactory](jsi::Runtime& rt) { + jsi::Value emitter = rt.global().getProperty(rt, "__rctDeviceEventEmitter"); if (!emitter.isUndefined()) { - jsi::Object emitterObject = emitter.asObject(runtime); + jsi::Object emitterObject = emitter.asObject(rt); // TODO: consider caching these jsi::Function emitFunction = - emitterObject.getPropertyAsFunction(runtime, "emit"); + emitterObject.getPropertyAsFunction(rt, "emit"); std::vector args; - args.emplace_back( - jsi::String::createFromAscii(runtime, eventName.c_str())); + args.emplace_back(jsi::String::createFromAscii(rt, eventName.c_str())); if (argFactory) { - argFactory(runtime, args); + argFactory(rt, args); } emitFunction.callWithThis( - runtime, emitterObject, (const jsi::Value*)args.data(), args.size()); + rt, emitterObject, (const jsi::Value*)args.data(), args.size()); } }); } diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h index ccd9d1f85968ef..aad026af97b7fb 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h @@ -106,10 +106,18 @@ class JSI_EXPORT TurboModule : public facebook::jsi::HostObject { * }); */ void emitDeviceEvent( - jsi::Runtime& runtime, const std::string& eventName, ArgFactory argFactory = nullptr); + // Backwards compatibility version + void emitDeviceEvent( + jsi::Runtime& /*runtime*/, + + const std::string& eventName, + ArgFactory argFactory = nullptr) { + emitDeviceEvent(eventName, std::move(argFactory)); + } + virtual jsi::Value create( jsi::Runtime& runtime, const jsi::PropNameID& propName) { diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.cpp index 360ad45f9da864..e4d1a6e79e5a2e 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.cpp @@ -67,9 +67,11 @@ class BridgelessNativeModuleProxy : public jsi::HostObject { */ TurboModuleBinding::TurboModuleBinding( + jsi::Runtime& runtime, TurboModuleProviderFunctionType&& moduleProvider, std::shared_ptr longLivedObjectCollection) - : moduleProvider_(std::move(moduleProvider)), + : runtime_(runtime), + moduleProvider_(std::move(moduleProvider)), longLivedObjectCollection_(std::move(longLivedObjectCollection)) {} void TurboModuleBinding::install( @@ -85,7 +87,7 @@ void TurboModuleBinding::install( jsi::PropNameID::forAscii(runtime, "__turboModuleProxy"), 1, [binding = TurboModuleBinding( - std::move(moduleProvider), longLivedObjectCollection)]( + runtime, std::move(moduleProvider), longLivedObjectCollection)]( jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, @@ -102,7 +104,9 @@ void TurboModuleBinding::install( bool rnTurboInterop = legacyModuleProvider != nullptr; auto turboModuleBinding = legacyModuleProvider ? std::make_unique( - std::move(legacyModuleProvider), longLivedObjectCollection) + runtime, + std::move(legacyModuleProvider), + longLivedObjectCollection) : nullptr; auto nativeModuleProxy = std::make_shared( std::move(turboModuleBinding)); @@ -119,7 +123,7 @@ TurboModuleBinding::~TurboModuleBinding() { if (longLivedObjectCollection_) { longLivedObjectCollection_->clear(); } else { - LongLivedObjectCollection::get().clear(); + LongLivedObjectCollection::get(runtime_).clear(); } } diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h index 0556c697f1e7cd..d45a72f25ca282 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h @@ -34,6 +34,7 @@ class TurboModuleBinding { nullptr); TurboModuleBinding( + jsi::Runtime& runtime, TurboModuleProviderFunctionType&& moduleProvider, std::shared_ptr longLivedObjectCollection); @@ -49,6 +50,7 @@ class TurboModuleBinding { jsi::Value getModule(jsi::Runtime& runtime, const std::string& moduleName) const; + jsi::Runtime& runtime_; TurboModuleProviderFunctionType moduleProvider_; std::shared_ptr longLivedObjectCollection_; }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp index 328c3f71a58415..2a7bbb51429603 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp @@ -63,7 +63,9 @@ jsi::Array deepCopyJSIArray(jsi::Runtime& rt, const jsi::Array& arr) { } Promise::Promise(jsi::Runtime& rt, jsi::Function resolve, jsi::Function reject) - : runtime_(rt), resolve_(std::move(resolve)), reject_(std::move(reject)) {} + : LongLivedObject(rt), + resolve_(std::move(resolve)), + reject_(std::move(reject)) {} void Promise::resolve(const jsi::Value& result) { resolve_.call(runtime_, result); diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h index 786c4cdb3cec02..abc56408aee855 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h @@ -26,7 +26,6 @@ struct Promise : public LongLivedObject { void resolve(const jsi::Value& result); void reject(const std::string& error); - jsi::Runtime& runtime_; jsi::Function resolve_; jsi::Function reject_; }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h index 66ebd30f92a4f4..cb020a852e6a1a 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h @@ -19,7 +19,7 @@ namespace facebook::react { struct JTurboModule : jni::JavaClass { static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/internal/turbomodule/core/interfaces/TurboModule;"; + "Lcom/facebook/react/turbomodule/core/interfaces/TurboModule;"; }; class JSI_EXPORT JavaTurboModule : public TurboModule { diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTRuntimeExecutor.h b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTRuntimeExecutor.h index 191e94f3b0ddbd..cdcda53ce391ab 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTRuntimeExecutor.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTRuntimeExecutor.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#import + #import #import diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModuleManager.h b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModuleManager.h index 014745be16d1ee..68a457ae6c2ed3 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModuleManager.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModuleManager.h @@ -10,7 +10,6 @@ #import #import -#import #import #import #import @@ -18,6 +17,7 @@ #import "RCTTurboModule.h" +@class RCTBridgeProxy; @class RCTTurboModuleManager; @protocol RCTTurboModuleManagerDelegate diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/CMakeLists.txt b/packages/react-native/ReactCommon/react/nativemodule/featureflags/CMakeLists.txt new file mode 100644 index 00000000000000..65c0bd433a56f6 --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/CMakeLists.txt @@ -0,0 +1,25 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +cmake_minimum_required(VERSION 3.13) +set(CMAKE_VERBOSE_MAKEFILE on) + +add_compile_options( + -fexceptions + -frtti + -std=c++20 + -Wall + -Wpedantic + -DLOG_TAG=\"ReactNative\") + +file(GLOB react_nativemodule_featureflags_SRC CONFIGURE_DEPENDS *.cpp) +add_library(react_nativemodule_featureflags SHARED ${react_nativemodule_featureflags_SRC}) + +target_include_directories(react_nativemodule_featureflags PUBLIC ${REACT_COMMON_DIR}) + +target_link_libraries(react_nativemodule_featureflags + react_featureflags + react_codegen_rncore + reactnative) diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp index 67f799f556c1ee..30c6d98f483d24 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<2466af777a1d69da2c3810e5a2d53a70>> + * @generated SignedSource<<27923a2dbf1dcbad238a4d06ebb54fb5>> */ /** @@ -20,7 +20,9 @@ #include "NativeReactNativeFeatureFlags.h" #include +#ifdef RN_DISABLE_OSS_PLUGIN_HEADER #include "Plugins.h" +#endif std::shared_ptr NativeReactNativeFeatureFlagsModuleProvider( @@ -40,39 +42,39 @@ bool NativeReactNativeFeatureFlags::commonTestFlag( return ReactNativeFeatureFlags::commonTestFlag(); } -bool NativeReactNativeFeatureFlags::enableBackgroundExecutor( +bool NativeReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::enableBackgroundExecutor(); + return ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop(); } -bool NativeReactNativeFeatureFlags::useModernRuntimeScheduler( +bool NativeReactNativeFeatureFlags::enableBackgroundExecutor( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::useModernRuntimeScheduler(); + return ReactNativeFeatureFlags::enableBackgroundExecutor(); } -bool NativeReactNativeFeatureFlags::enableMicrotasks( +bool NativeReactNativeFeatureFlags::enableCustomDrawOrderFabric( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::enableMicrotasks(); + return ReactNativeFeatureFlags::enableCustomDrawOrderFabric(); } -bool NativeReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop( +bool NativeReactNativeFeatureFlags::enableFixForClippedSubviewsCrash( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop(); + return ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash(); } -bool NativeReactNativeFeatureFlags::enableSpannableBuildingUnification( +bool NativeReactNativeFeatureFlags::enableMicrotasks( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::enableSpannableBuildingUnification(); + return ReactNativeFeatureFlags::enableMicrotasks(); } -bool NativeReactNativeFeatureFlags::enableCustomDrawOrderFabric( +bool NativeReactNativeFeatureFlags::enableMountHooksAndroid( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::enableCustomDrawOrderFabric(); + return ReactNativeFeatureFlags::enableMountHooksAndroid(); } -bool NativeReactNativeFeatureFlags::enableFixForClippedSubviewsCrash( +bool NativeReactNativeFeatureFlags::enableSpannableBuildingUnification( jsi::Runtime& /*runtime*/) { - return ReactNativeFeatureFlags::enableFixForClippedSubviewsCrash(); + return ReactNativeFeatureFlags::enableSpannableBuildingUnification(); } bool NativeReactNativeFeatureFlags::inspectorEnableCxxInspectorPackagerConnection( @@ -85,4 +87,9 @@ bool NativeReactNativeFeatureFlags::inspectorEnableModernCDPRegistry( return ReactNativeFeatureFlags::inspectorEnableModernCDPRegistry(); } +bool NativeReactNativeFeatureFlags::useModernRuntimeScheduler( + jsi::Runtime& /*runtime*/) { + return ReactNativeFeatureFlags::useModernRuntimeScheduler(); +} + } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h index 203dfce52c07e1..ffe0f7044d544f 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<30481dc57cc7f389d1ed87d097caedda>> + * @generated SignedSource<<53251a11631eccf1fcc334b14f9ca4c6>> */ /** @@ -19,36 +19,43 @@ #pragma once +#if __has_include("rncoreJSI.h") // Cmake headers on Android +#include "rncoreJSI.h" +#elif __has_include("FBReactNativeSpecJSI.h") // CocoaPod headers on Apple +#include "FBReactNativeSpecJSI.h" +#else #include +#endif namespace facebook::react { class NativeReactNativeFeatureFlags : public NativeReactNativeFeatureFlagsCxxSpec< - NativeReactNativeFeatureFlags>, - std::enable_shared_from_this { + NativeReactNativeFeatureFlags> { public: NativeReactNativeFeatureFlags(std::shared_ptr jsInvoker); bool commonTestFlag(jsi::Runtime& runtime); + bool batchRenderingUpdatesInEventLoop(jsi::Runtime& runtime); + bool enableBackgroundExecutor(jsi::Runtime& runtime); - bool useModernRuntimeScheduler(jsi::Runtime& runtime); + bool enableCustomDrawOrderFabric(jsi::Runtime& runtime); + + bool enableFixForClippedSubviewsCrash(jsi::Runtime& runtime); bool enableMicrotasks(jsi::Runtime& runtime); - bool batchRenderingUpdatesInEventLoop(jsi::Runtime& runtime); + bool enableMountHooksAndroid(jsi::Runtime& runtime); bool enableSpannableBuildingUnification(jsi::Runtime& runtime); - bool enableCustomDrawOrderFabric(jsi::Runtime& runtime); - - bool enableFixForClippedSubviewsCrash(jsi::Runtime& runtime); - bool inspectorEnableCxxInspectorPackagerConnection(jsi::Runtime& runtime); bool inspectorEnableModernCDPRegistry(jsi::Runtime& runtime); + + bool useModernRuntimeScheduler(jsi::Runtime& runtime); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/React-featureflagsnativemodule.podspec b/packages/react-native/ReactCommon/react/nativemodule/featureflags/React-featureflagsnativemodule.podspec new file mode 100644 index 00000000000000..5edea69a167c1a --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/React-featureflagsnativemodule.podspec @@ -0,0 +1,48 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "..", "..", "..", "..", "package.json"))) +version = package['version'] + +source = { :git => 'https://github.com/facebook/react-native.git' } +if version == '1000.0.0' + # This is an unpublished version, use the latest commit hash of the react-native repo, which we’re presumably in. + source[:commit] = `git rev-parse HEAD`.strip if system("git rev-parse --git-dir > /dev/null 2>&1") +else + source[:tag] = "v#{version}" +end + +header_search_paths = [] + +if ENV['USE_FRAMEWORKS'] + header_search_paths << "\"$(PODS_TARGET_SRCROOT)/../../..\"" # this is needed to allow the feature flags access its own files +end + +Pod::Spec.new do |s| + s.name = "React-featureflagsnativemodule" + s.version = version + s.summary = "React Native internal feature flags" + s.homepage = "https://reactnative.dev/" + s.license = package["license"] + s.author = "Meta Platforms, Inc. and its affiliates" + s.platforms = min_supported_versions + s.source = source + s.source_files = "*.{cpp,h}" + s.header_dir = "react/nativemodule/featureflags" + s.pod_target_xcconfig = { "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", + "HEADER_SEARCH_PATHS" => header_search_paths.join(' '), + "DEFINES_MODULE" => "YES" } + + if ENV['USE_FRAMEWORKS'] + s.module_name = "React_featureflagsnativemodule" + s.header_mappings_dir = "../.." + end + + install_modules_dependencies(s) + + s.dependency "ReactCommon/turbomodule/core" +end diff --git a/packages/react-native/ReactCommon/react/nativemodule/microtasks/CMakeLists.txt b/packages/react-native/ReactCommon/react/nativemodule/microtasks/CMakeLists.txt new file mode 100644 index 00000000000000..80fe7fdc29ef2e --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/microtasks/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +cmake_minimum_required(VERSION 3.13) +set(CMAKE_VERBOSE_MAKEFILE on) + +add_compile_options( + -fexceptions + -frtti + -std=c++20 + -Wall + -Wpedantic + -DLOG_TAG=\"ReactNative\") + +file(GLOB react_nativemodule_microtasks_SRC CONFIGURE_DEPENDS *.cpp) +add_library(react_nativemodule_microtasks SHARED ${react_nativemodule_microtasks_SRC}) + +target_include_directories(react_nativemodule_microtasks PUBLIC ${REACT_COMMON_DIR}) + +target_link_libraries(react_nativemodule_microtasks + react_codegen_rncore + reactnative) diff --git a/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.cpp b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.cpp new file mode 100644 index 00000000000000..25d5f2c41a5253 --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "NativeMicrotasks.h" + +#ifdef RN_DISABLE_OSS_PLUGIN_HEADER +#include "Plugins.h" +#endif + +std::shared_ptr NativeMicrotasksModuleProvider( + std::shared_ptr jsInvoker) { + return std::make_shared( + std::move(jsInvoker)); +} + +namespace facebook::react { + +NativeMicrotasks::NativeMicrotasks(std::shared_ptr jsInvoker) + : NativeMicrotasksCxxSpec(std::move(jsInvoker)) {} + +void NativeMicrotasks::queueMicrotask( + jsi::Runtime& runtime, + jsi::Function callback) { + runtime.queueMicrotask(callback); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h new file mode 100644 index 00000000000000..560b39bd0ef746 --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#if __has_include("rncoreJSI.h") // Cmake headers on Android +#include "rncoreJSI.h" +#elif __has_include("FBReactNativeSpecJSI.h") // CocoaPod headers on Apple +#include "FBReactNativeSpecJSI.h" +#else +#include +#endif + +namespace facebook::react { + +class NativeMicrotasks : public NativeMicrotasksCxxSpec { + public: + NativeMicrotasks(std::shared_ptr jsInvoker); + + void queueMicrotask(jsi::Runtime& runtime, jsi::Function callback); +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/microtasks/React-microtasksnativemodule.podspec b/packages/react-native/ReactCommon/react/nativemodule/microtasks/React-microtasksnativemodule.podspec new file mode 100644 index 00000000000000..20ff70d9e43624 --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/microtasks/React-microtasksnativemodule.podspec @@ -0,0 +1,48 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "..", "..", "..", "..", "package.json"))) +version = package['version'] + +source = { :git => 'https://github.com/facebook/react-native.git' } +if version == '1000.0.0' + # This is an unpublished version, use the latest commit hash of the react-native repo, which we’re presumably in. + source[:commit] = `git rev-parse HEAD`.strip if system("git rev-parse --git-dir > /dev/null 2>&1") +else + source[:tag] = "v#{version}" +end + +header_search_paths = [] + +if ENV['USE_FRAMEWORKS'] + header_search_paths << "\"$(PODS_TARGET_SRCROOT)/../../..\"" # this is needed to allow the microtasks module access its own files +end + +Pod::Spec.new do |s| + s.name = "React-microtasksnativemodule" + s.version = version + s.summary = "React Native microtasks native module" + s.homepage = "https://reactnative.dev/" + s.license = package["license"] + s.author = "Meta Platforms, Inc. and its affiliates" + s.platforms = min_supported_versions + s.source = source + s.source_files = "*.{cpp,h}" + s.header_dir = "react/nativemodule/microtasks" + s.pod_target_xcconfig = { "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", + "HEADER_SEARCH_PATHS" => header_search_paths.join(' '), + "DEFINES_MODULE" => "YES" } + + if ENV['USE_FRAMEWORKS'] + s.module_name = "React_microtasksnativemodule" + s.header_mappings_dir = "../.." + end + + install_modules_dependencies(s) + + s.dependency "ReactCommon/turbomodule/core" +end diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon-Samples.podspec b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon-Samples.podspec index a034edc582ee23..5c6fc31aa5333d 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon-Samples.podspec +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon-Samples.podspec @@ -64,7 +64,7 @@ Pod::Spec.new do |s| s.dependency "React-Core" s.dependency "React-cxxreact" s.dependency "React-jsi" - add_dependency(s, "React-Codegen", :additional_framework_paths => ["build/generated/ios"]) + add_dependency(s, "ReactCodegen", :additional_framework_paths => ["build/generated/ios"]) add_dependency(s, "ReactCommon", :subspec => "turbomodule/core", :additional_framework_paths => ["react/nativemodule/core"]) add_dependency(s, "React-NativeModulesApple", :additional_framework_paths => ["build/generated/ios"]) diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java index 6b05e380a21ee1..92d5687d7e7e5b 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java @@ -19,7 +19,7 @@ import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.internal.turbomodule.core.interfaces.TurboModule; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.Arrays; import java.util.HashSet; import java.util.Map; diff --git a/packages/react-native/src/private/webapis/performance/BoundedConsumableBuffer.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/BoundedConsumableBuffer.h similarity index 100% rename from packages/react-native/src/private/webapis/performance/BoundedConsumableBuffer.h rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/BoundedConsumableBuffer.h diff --git a/packages/react-native/src/private/webapis/performance/NativePerformance.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp similarity index 95% rename from packages/react-native/src/private/webapis/performance/NativePerformance.cpp rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp index ce57c6041ac58d..2c4e45e4c28139 100644 --- a/packages/react-native/src/private/webapis/performance/NativePerformance.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp @@ -7,6 +7,7 @@ #include +#include #include #include #include "NativePerformance.h" @@ -25,6 +26,10 @@ namespace facebook::react { NativePerformance::NativePerformance(std::shared_ptr jsInvoker) : NativePerformanceCxxSpec(std::move(jsInvoker)) {} +double NativePerformance::now(jsi::Runtime& /*rt*/) { + return JSExecutor::performanceNow(); +} + void NativePerformance::mark( jsi::Runtime& rt, std::string name, diff --git a/packages/react-native/src/private/webapis/performance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h similarity index 95% rename from packages/react-native/src/private/webapis/performance/NativePerformance.h rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index 7dfa5d36f540a6..65c1ef07e02fab 100644 --- a/packages/react-native/src/private/webapis/performance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -20,11 +20,12 @@ class PerformanceEntryReporter; #pragma mark - implementation -class NativePerformance : public NativePerformanceCxxSpec, - std::enable_shared_from_this { +class NativePerformance : public NativePerformanceCxxSpec { public: NativePerformance(std::shared_ptr jsInvoker); + double now(jsi::Runtime& rt); + void mark(jsi::Runtime& rt, std::string name, double startTime); void measure( diff --git a/packages/react-native/src/private/webapis/performance/NativePerformanceObserver.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformanceObserver.cpp similarity index 100% rename from packages/react-native/src/private/webapis/performance/NativePerformanceObserver.cpp rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformanceObserver.cpp diff --git a/packages/react-native/src/private/webapis/performance/NativePerformanceObserver.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformanceObserver.h similarity index 97% rename from packages/react-native/src/private/webapis/performance/NativePerformanceObserver.h rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformanceObserver.h index c5e7c3cc4b8ec4..f33d4586ebd521 100644 --- a/packages/react-native/src/private/webapis/performance/NativePerformanceObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformanceObserver.h @@ -48,8 +48,7 @@ struct Bridging #pragma mark - implementation class NativePerformanceObserver - : public NativePerformanceObserverCxxSpec, - std::enable_shared_from_this { + : public NativePerformanceObserverCxxSpec { public: NativePerformanceObserver(std::shared_ptr jsInvoker); ~NativePerformanceObserver(); diff --git a/packages/react-native/src/private/webapis/performance/PerformanceEntryReporter.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/PerformanceEntryReporter.cpp similarity index 100% rename from packages/react-native/src/private/webapis/performance/PerformanceEntryReporter.cpp rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/PerformanceEntryReporter.cpp diff --git a/packages/react-native/src/private/webapis/performance/PerformanceEntryReporter.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/PerformanceEntryReporter.h similarity index 100% rename from packages/react-native/src/private/webapis/performance/PerformanceEntryReporter.h rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/PerformanceEntryReporter.h diff --git a/packages/react-native/src/private/webapis/performance/__tests__/BoundedConsumableBufferTest.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/tests/BoundedConsumableBufferTest.cpp similarity index 100% rename from packages/react-native/src/private/webapis/performance/__tests__/BoundedConsumableBufferTest.cpp rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/tests/BoundedConsumableBufferTest.cpp diff --git a/packages/react-native/src/private/webapis/performance/__tests__/PerformanceEntryReporterTest.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/tests/PerformanceEntryReporterTest.cpp similarity index 100% rename from packages/react-native/src/private/webapis/performance/__tests__/PerformanceEntryReporterTest.cpp rename to packages/react-native/ReactCommon/react/nativemodule/webperformance/tests/PerformanceEntryReporterTest.cpp diff --git a/packages/react-native/ReactCommon/react/renderer/.clang-tidy b/packages/react-native/ReactCommon/react/renderer/.clang-tidy deleted file mode 100644 index 6ddb7b64c1b8c6..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/.clang-tidy +++ /dev/null @@ -1,195 +0,0 @@ ---- -InheritParentConfig: true -Checks: '> -clang-diagnostic-*, -modernize-avoid-bind, -modernize-avoid-c-arrays, -modernize-concat-nested-namespaces, -modernize-deprecated-headers, -modernize-deprecated-ios-base-aliases, -modernize-loop-convert, -modernize-make-shared, -modernize-redundant-void-arg, -modernize-return-braced-init-list, -modernize-use-auto, -modernize-make-unique, -modernize-pass-by-value, -modernize-raw-string-literal, -modernize-replace-auto-ptr, -modernize-use-bool-literals, -modernize-replace-random-shuffle, -modernize-unary-static-assert, -modernize-use-emplace, -modernize-shrink-to-fit, -modernize-use-equals-default, -modernize-use-default-member-init, -modernize-use-nullptr, -modernize-use-noexcept, -modernize-use-equals-delete, -modernize-use-override, -modernize-use-using, -modernize-use-transparent-functors, -performance-faster-string-find, -performance-for-range-copy, -performance-implicit-conversion-in-loop, -performance-inefficient-algorithm, -performance-inefficient-string-concatenation, -performance-inefficient-vector-operation, -performance-move-const-arg, -performance-move-constructor-init, -performance-noexcept-move-constructor, -performance-type-promotion-in-math-fn, -performance-unnecessary-copy-initialization, -performance-unnecessary-value-param, -cppcoreguidelines-macro-usage, -cppcoreguidelines-narrowing-conversions, -cppcoreguidelines-no-malloc, -cppcoreguidelines-pro-bounds-pointer-arithmetic, -cppcoreguidelines-pro-type-const-cast, -cppcoreguidelines-pro-type-cstyle-cast, -cppcoreguidelines-pro-type-member-init, -cppcoreguidelines-pro-type-reinterpret-cast, -cppcoreguidelines-pro-type-union-access, -cppcoreguidelines-pro-type-vararg, -cppcoreguidelines-slicing, -cppcoreguidelines-special-member-functions, -readability-avoid-const-params-in-decls, -readability-braces-around-statements, -readability-const-return-type, -readability-container-size-empty, -readability-deleted-default, -readability-delete-null-pointer, -readability-implicit-bool-conversion, -readability-inconsistent-declaration-parameter-name, -readability-isolate-declaration, -readability-misplaced-array-index, -readability-named-parameter, -readability-non-const-parameter, -readability-redundant-control-flow, -readability-redundant-declaration, -readability-redundant-function-ptr-dereference, -readability-redundant-preprocessor, -readability-redundant-smartptr-get, -readability-redundant-string-cstr, -readability-redundant-string-init, -readability-simplify-boolean-expr, -readability-simplify-subscript-expr, -readability-static-accessed-through-instance, -readability-static-definition-in-anonymous-namespace, -readability-string-compare, -readability-uniqueptr-delete-release, -misc-definitions-in-headers, -misc-new-delete-overloads, -misc-non-copyable-objects, -misc-static-assert, -misc-throw-by-value-catch-by-reference, -misc-unconventional-assign-operator, -misc-uniqueptr-reset-release, -misc-unused-alias-decls, -misc-unused-parameters, -misc-unused-using-decls, -bugprone-argument-comment, -bugprone-assert-side-effect, -bugprone-bool-pointer-implicit-conversion, -bugprone-copy-constructor-init, -bugprone-dangling-handle, -bugprone-exception-escape, -bugprone-fold-init-type, -bugprone-forward-declaration-namespace, -bugprone-forwarding-reference-overload, -bugprone-inaccurate-erase, -bugprone-incorrect-roundings, -bugprone-integer-division, -bugprone-macro-parentheses, -bugprone-macro-repeated-side-effects, -bugprone-misplaced-operator-in-strlen-in-alloc, -bugprone-misplaced-widening-cast, -bugprone-move-forwarding-reference, -bugprone-multiple-statement-macro, -bugprone-parent-virtual-call, -bugprone-sizeof-container, -bugprone-sizeof-expression, -bugprone-string-constructor, -bugprone-string-integer-assignment, -bugprone-string-literal-with-embedded-nul, -bugprone-suspicious-enum-usage, -bugprone-suspicious-memset-usage, -bugprone-suspicious-missing-comma, -bugprone-suspicious-semicolon, -bugprone-suspicious-string-compare, -bugprone-swapped-arguments, -bugprone-terminating-continue, -bugprone-throw-keyword-missing, -bugprone-too-small-loop-variable, -bugprone-undefined-memory-manipulation, -bugprone-undelegated-constructor, -bugprone-unused-return-value, -bugprone-use-after-move, -bugprone-virtual-near-miss, -clang-analyzer-apiModeling.StdCLibraryFunctions, -clang-analyzer-apiModeling.TrustNonnull, -clang-analyzer-apiModeling.google.GTest, -clang-analyzer-core.CallAndMessage, -clang-analyzer-core.DivideZero, -clang-analyzer-core.DynamicTypePropagation, -clang-analyzer-core.NonNullParamChecker, -clang-analyzer-core.NonnilStringConstants, -clang-analyzer-core.NullDereference, -clang-analyzer-core.StackAddressEscape, -clang-analyzer-core.UndefinedBinaryOperatorResult, -clang-analyzer-core.VLASize, -clang-analyzer-core.builtin.BuiltinFunctions, -clang-analyzer-core.builtin.NoReturnFunctions, -clang-analyzer-core.uninitialized.ArraySubscript, -clang-analyzer-core.uninitialized.Assign, -clang-analyzer-core.uninitialized.Branch, -clang-analyzer-core.uninitialized.CapturedBlockVariable, -clang-analyzer-core.uninitialized.UndefReturn, -clang-analyzer-cplusplus.InnerPointer, -clang-analyzer-cplusplus.Move, -clang-analyzer-cplusplus.NewDelete, -clang-analyzer-cplusplus.NewDeleteLeaks, -clang-analyzer-cplusplus.SelfAssignment, -clang-analyzer-deadcode.DeadStores, -clang-analyzer-optin.cplusplus.VirtualCall, -clang-analyzer-optin.mpi.MPI-Checker, -clang-analyzer-optin.performance.GCDAntipattern, -clang-analyzer-optin.performance.Padding, -clang-analyzer-optin.portability.UnixAPI, -clang-analyzer-nullability.NullPassedToNonnull, -clang-analyzer-nullability.NullReturnedFromNonnull, -clang-analyzer-nullability.NullableDereferenced, -clang-analyzer-nullability.NullablePassedToNonnull, -clang-analyzer-nullability.NullableReturnedFromNonnull, -clang-analyzer-security.FloatLoopCounter, -clang-analyzer-security.insecureAPI.UncheckedReturn, -clang-analyzer-security.insecureAPI.bcmp, -clang-analyzer-security.insecureAPI.bcopy, -clang-analyzer-security.insecureAPI.bzero, -clang-analyzer-security.insecureAPI.getpw, -clang-analyzer-security.insecureAPI.gets, -clang-analyzer-security.insecureAPI.mkstemp, -clang-analyzer-security.insecureAPI.mktemp, -clang-analyzer-security.insecureAPI.rand, -clang-analyzer-security.insecureAPI.strcpy, -clang-analyzer-security.insecureAPI.vfork, -clang-analyzer-unix.API, -clang-analyzer-unix.Malloc, -clang-analyzer-unix.MallocSizeof, -clang-analyzer-unix.MismatchedDeallocator, -clang-analyzer-unix.Vfork, -clang-analyzer-unix.cstring.BadSizeArg, -clang-analyzer-unix.cstring.NullArg, -clang-analyzer-valist.CopyToSelf, -clang-analyzer-valist.Uninitialized, -clang-analyzer-valist.Unterminated, -google-build-using-namespace, -' - -CheckOptions: -- key: performance-unnecessary-value-param.AllowedTypes - value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$;' -- key: performance-unnecessary-copy-initialization.AllowedTypes - value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$' - -... diff --git a/packages/react-native/ReactCommon/react/renderer/animations/conversions.h b/packages/react-native/ReactCommon/react/renderer/animations/conversions.h index 70f2486040390e..34a0957c6502b1 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/conversions.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h index 0909b49bff20dd..3cb643a8d5e0a2 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.cpp index fe97911c6807db..0b73576a74db02 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.cpp @@ -15,8 +15,9 @@ LegacyViewManagerInteropViewProps::LegacyViewManagerInteropViewProps( const LegacyViewManagerInteropViewProps& sourceProps, const RawProps& rawProps) : ViewProps(context, sourceProps, rawProps), - otherProps( - mergeDynamicProps(sourceProps.otherProps, (folly::dynamic)rawProps)) { -} + otherProps(mergeDynamicProps( + sourceProps.otherProps, + (folly::dynamic)rawProps, + NullValueStrategy::Override)) {} } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h index fdfbe9fc523157..843755a8fa5015 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.cpp b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.cpp index 9ea8c939900431..016c3316bb418e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.cpp @@ -94,14 +94,10 @@ void ScrollViewEventEmitter::onMomentumScrollEnd( void ScrollViewEventEmitter::dispatchScrollViewEvent( std::string name, - const ScrollViewMetrics& scrollViewMetrics, - EventPriority priority) const { - dispatchEvent( - std::move(name), - [scrollViewMetrics](jsi::Runtime& runtime) { - return scrollViewMetricsPayload(runtime, scrollViewMetrics); - }, - priority); + const ScrollViewMetrics& scrollViewMetrics) const { + dispatchEvent(std::move(name), [scrollViewMetrics](jsi::Runtime& runtime) { + return scrollViewMetricsPayload(runtime, scrollViewMetrics); + }); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h index 8a849db8a50935..12e271149149c0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h @@ -38,8 +38,7 @@ class ScrollViewEventEmitter : public ViewEventEmitter { private: void dispatchScrollViewEvent( std::string name, - const ScrollViewMetrics& scrollViewMetrics, - EventPriority priority = EventPriority::AsynchronousBatched) const; + const ScrollViewMetrics& scrollViewMetrics) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/text/conversions.h index f9002441c916c2..b9af7534475ab7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/conversions.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.cpp new file mode 100644 index 00000000000000..28dc7d87cbdad4 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "BaseTextInputProps.h" + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +BaseTextInputProps::BaseTextInputProps( + const PropsParserContext& context, + const BaseTextInputProps& sourceProps, + const RawProps& rawProps) + : ViewProps(context, sourceProps, rawProps), + BaseTextProps(context, sourceProps, rawProps), + paragraphAttributes(convertRawProp( + context, + rawProps, + sourceProps.paragraphAttributes, + {})), + defaultValue(convertRawProp( + context, + rawProps, + "defaultValue", + sourceProps.defaultValue, + {})), + placeholder(convertRawProp( + context, + rawProps, + "placeholder", + sourceProps.placeholder, + {})), + placeholderTextColor(convertRawProp( + context, + rawProps, + "placeholderTextColor", + sourceProps.placeholderTextColor, + {})), + cursorColor(convertRawProp( + context, + rawProps, + "cursorColor", + sourceProps.cursorColor, + {})), + selectionColor(convertRawProp( + context, + rawProps, + "selectionColor", + sourceProps.selectionColor, + {})), + selectionHandleColor(convertRawProp( + context, + rawProps, + "selectionHandleColor", + sourceProps.selectionHandleColor, + {})), + underlineColorAndroid(convertRawProp( + context, + rawProps, + "underlineColorAndroid", + sourceProps.underlineColorAndroid, + {})), + maxLength(convertRawProp( + context, + rawProps, + "maxLength", + sourceProps.maxLength, + {})), + text(convertRawProp(context, rawProps, "text", sourceProps.text, {})), + mostRecentEventCount(convertRawProp( + context, + rawProps, + "mostRecentEventCount", + sourceProps.mostRecentEventCount, + {})), + autoFocus(convertRawProp( + context, + rawProps, + "autoFocus", + sourceProps.autoFocus, + {})){}; + +void BaseTextInputProps::setProp( + const PropsParserContext& context, + RawPropsPropNameHash hash, + const char* propName, + const RawValue& value) { + ViewProps::setProp(context, hash, propName, value); + BaseTextProps::setProp(context, hash, propName, value); + + static auto defaults = BaseTextInputProps{}; + + // ParagraphAttributes has its own switch statement - to keep all + // of these fields together, and because there are some collisions between + // propnames parsed here and outside of ParagraphAttributes. For example, + // textBreakStrategy is duplicated. + // This code is also duplicated in ParagraphProps. + static auto paDefaults = ParagraphAttributes{}; + switch (hash) { + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + maximumNumberOfLines, + "numberOfLines"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, value, paragraphAttributes, ellipsizeMode, "ellipsizeMode"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + textBreakStrategy, + "textBreakStrategy"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + adjustsFontSizeToFit, + "adjustsFontSizeToFit"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + minimumFontSize, + "minimumFontSize"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + maximumFontSize, + "maximumFontSize"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + includeFontPadding, + "includeFontPadding"); + REBUILD_FIELD_SWITCH_CASE( + paDefaults, + value, + paragraphAttributes, + android_hyphenationFrequency, + "android_hyphenationFrequency"); + } + + switch (hash) { + RAW_SET_PROP_SWITCH_CASE_BASIC(underlineColorAndroid); + RAW_SET_PROP_SWITCH_CASE_BASIC(autoFocus); + RAW_SET_PROP_SWITCH_CASE_BASIC(maxLength); + RAW_SET_PROP_SWITCH_CASE_BASIC(placeholder); + RAW_SET_PROP_SWITCH_CASE_BASIC(placeholderTextColor); + RAW_SET_PROP_SWITCH_CASE_BASIC(selectionColor); + RAW_SET_PROP_SWITCH_CASE_BASIC(selectionHandleColor); + RAW_SET_PROP_SWITCH_CASE_BASIC(defaultValue); + RAW_SET_PROP_SWITCH_CASE_BASIC(cursorColor); + RAW_SET_PROP_SWITCH_CASE_BASIC(text); + RAW_SET_PROP_SWITCH_CASE_BASIC(mostRecentEventCount); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h new file mode 100644 index 00000000000000..c1a3ef1e202e5b --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +class BaseTextInputProps : public ViewProps, public BaseTextProps { + public: + BaseTextInputProps() = default; + BaseTextInputProps( + const PropsParserContext& context, + const BaseTextInputProps& sourceProps, + const RawProps& rawProps); + + void setProp( + const PropsParserContext& context, + RawPropsPropNameHash hash, + const char* propName, + const RawValue& value); + +#pragma mark - Props + + /* + * Contains all prop values that affect visual representation of the + * paragraph. + */ + ParagraphAttributes paragraphAttributes{}; + + std::string defaultValue{}; + + std::string placeholder{}; + SharedColor placeholderTextColor{}; + + /* + * Tint colors + */ + SharedColor cursorColor{}; + SharedColor selectionColor{}; + SharedColor selectionHandleColor{}; + // TODO: Rename to `tintColor` and make universal. + SharedColor underlineColorAndroid{}; + + int maxLength{}; + + /* + * "Private" (only used by TextInput.js) props + */ + std::string text{}; + int mostRecentEventCount{0}; + + bool autoFocus{false}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt b/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt index e8d12d59df91fd..98814617b5c546 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt @@ -14,13 +14,10 @@ add_compile_options( -Wpedantic -DLOG_TAG=\"Fabric\") -file(GLOB rrc_textinput_SRC CONFIGURE_DEPENDS platform/android/react/renderer/components/androidtextinput/*.cpp) +file(GLOB rrc_textinput_SRC CONFIGURE_DEPENDS *.cpp platform/android/react/renderer/components/androidtextinput/*.cpp) add_library(rrc_textinput STATIC ${rrc_textinput_SRC}) -target_include_directories(rrc_textinput - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/platform/android/ -) +target_include_directories(rrc_textinput PUBLIC . ${CMAKE_CURRENT_SOURCE_DIR}/platform/android/) target_link_libraries(rrc_textinput glog diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.cpp index ea0fb6a1674e3d..38f3474ac350e1 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.cpp @@ -36,8 +36,7 @@ AndroidTextInputProps::AndroidTextInputProps( const PropsParserContext &context, const AndroidTextInputProps &sourceProps, const RawProps &rawProps) - : ViewProps(context, sourceProps, rawProps), - BaseTextProps(context, sourceProps, rawProps), + : BaseTextInputProps(context, sourceProps, rawProps), autoComplete(CoreFeatures::enablePropIteratorSetter? sourceProps.autoComplete : convertRawProp( context, rawProps, @@ -60,10 +59,6 @@ AndroidTextInputProps::AndroidTextInputProps( "textBreakStrategy", sourceProps.textBreakStrategy, {})), - underlineColorAndroid(CoreFeatures::enablePropIteratorSetter? sourceProps.underlineColorAndroid : convertRawProp(context, rawProps, - "underlineColorAndroid", - sourceProps.underlineColorAndroid, - {})), inlineImageLeft(CoreFeatures::enablePropIteratorSetter? sourceProps.inlineImageLeft : convertRawProp(context, rawProps, "inlineImageLeft", sourceProps.inlineImageLeft, @@ -88,10 +83,6 @@ AndroidTextInputProps::AndroidTextInputProps( "autoCorrect", sourceProps.autoCorrect, {false})), - autoFocus(CoreFeatures::enablePropIteratorSetter? sourceProps.autoFocus : convertRawProp(context, rawProps, - "autoFocus", - sourceProps.autoFocus, - {false})), allowFontScaling(CoreFeatures::enablePropIteratorSetter? sourceProps.allowFontScaling : convertRawProp(context, rawProps, "allowFontScaling", sourceProps.allowFontScaling, @@ -110,35 +101,15 @@ AndroidTextInputProps::AndroidTextInputProps( "returnKeyType", sourceProps.returnKeyType, {})), - maxLength(CoreFeatures::enablePropIteratorSetter? sourceProps.maxLength : - convertRawProp(context, rawProps, "maxLength", sourceProps.maxLength, {0})), multiline(CoreFeatures::enablePropIteratorSetter? sourceProps.multiline : convertRawProp(context, rawProps, "multiline", sourceProps.multiline, {false})), - placeholder(CoreFeatures::enablePropIteratorSetter? sourceProps.placeholder : - convertRawProp(context, rawProps, "placeholder", sourceProps.placeholder, {})), - placeholderTextColor(CoreFeatures::enablePropIteratorSetter? sourceProps.placeholderTextColor : convertRawProp(context, rawProps, - "placeholderTextColor", - sourceProps.placeholderTextColor, - {})), secureTextEntry(CoreFeatures::enablePropIteratorSetter? sourceProps.secureTextEntry : convertRawProp(context, rawProps, "secureTextEntry", sourceProps.secureTextEntry, {false})), - selectionColor(CoreFeatures::enablePropIteratorSetter? sourceProps.selectionColor : convertRawProp(context, rawProps, - "selectionColor", - sourceProps.selectionColor, - {})), - selectionHandleColor(CoreFeatures::enablePropIteratorSetter? sourceProps.selectionHandleColor : convertRawProp(context, rawProps, - "selectionHandleColor", - sourceProps.selectionHandleColor, - {})), value(CoreFeatures::enablePropIteratorSetter? sourceProps.value : convertRawProp(context, rawProps, "value", sourceProps.value, {})), - defaultValue(CoreFeatures::enablePropIteratorSetter? sourceProps.defaultValue : convertRawProp(context, rawProps, - "defaultValue", - sourceProps.defaultValue, - {})), selectTextOnFocus(CoreFeatures::enablePropIteratorSetter? sourceProps.selectTextOnFocus : convertRawProp(context, rawProps, "selectTextOnFocus", sourceProps.selectTextOnFocus, @@ -202,15 +173,6 @@ AndroidTextInputProps::AndroidTextInputProps( "textAlignVertical", sourceProps.textAlignVertical, {})), - cursorColor(CoreFeatures::enablePropIteratorSetter? sourceProps.cursorColor : - convertRawProp(context, rawProps, "cursorColor", sourceProps.cursorColor, {})), - mostRecentEventCount(CoreFeatures::enablePropIteratorSetter? sourceProps.mostRecentEventCount : convertRawProp(context, rawProps, - "mostRecentEventCount", - sourceProps.mostRecentEventCount, - {0})), - text(CoreFeatures::enablePropIteratorSetter? sourceProps.text : convertRawProp(context, rawProps, "text", sourceProps.text, {})), - paragraphAttributes(CoreFeatures::enablePropIteratorSetter? sourceProps.paragraphAttributes : - convertRawProp(context, rawProps, sourceProps.paragraphAttributes, {})), // See AndroidTextInputComponentDescriptor for usage // TODO T63008435: can these, and this feature, be removed entirely? hasPadding(CoreFeatures::enablePropIteratorSetter? sourceProps.hasPadding : hasValue(rawProps, sourceProps.hasPadding, "padding")), @@ -252,91 +214,29 @@ void AndroidTextInputProps::setProp( // All Props structs setProp methods must always, unconditionally, // call all super::setProp methods, since multiple structs may // reuse the same values. - ViewProps::setProp(context, hash, propName, value); - BaseTextProps::setProp(context, hash, propName, value); + BaseTextInputProps::setProp(context, hash, propName, value); static auto defaults = AndroidTextInputProps{}; - // ParagraphAttributes has its own switch statement - to keep all - // of these fields together, and because there are some collisions between - // propnames parsed here and outside of ParagraphAttributes. For example, - // textBreakStrategy is duplicated. - // This code is also duplicated in ParagraphProps. - static auto paDefaults = ParagraphAttributes{}; - switch (hash) { - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - maximumNumberOfLines, - "numberOfLines"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, value, paragraphAttributes, ellipsizeMode, "ellipsizeMode"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - textBreakStrategy, - "textBreakStrategy"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - adjustsFontSizeToFit, - "adjustsFontSizeToFit"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - minimumFontSize, - "minimumFontSize"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - maximumFontSize, - "maximumFontSize"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - includeFontPadding, - "includeFontPadding"); - REBUILD_FIELD_SWITCH_CASE( - paDefaults, - value, - paragraphAttributes, - android_hyphenationFrequency, - "android_hyphenationFrequency"); - } - switch (hash) { RAW_SET_PROP_SWITCH_CASE_BASIC(autoComplete); RAW_SET_PROP_SWITCH_CASE_BASIC(returnKeyLabel); RAW_SET_PROP_SWITCH_CASE_BASIC(numberOfLines); RAW_SET_PROP_SWITCH_CASE_BASIC(disableFullscreenUI); RAW_SET_PROP_SWITCH_CASE_BASIC(textBreakStrategy); - RAW_SET_PROP_SWITCH_CASE_BASIC(underlineColorAndroid); RAW_SET_PROP_SWITCH_CASE_BASIC(inlineImageLeft); RAW_SET_PROP_SWITCH_CASE_BASIC(inlineImagePadding); RAW_SET_PROP_SWITCH_CASE_BASIC(importantForAutofill); RAW_SET_PROP_SWITCH_CASE_BASIC(showSoftInputOnFocus); RAW_SET_PROP_SWITCH_CASE_BASIC(autoCapitalize); RAW_SET_PROP_SWITCH_CASE_BASIC(autoCorrect); - RAW_SET_PROP_SWITCH_CASE_BASIC(autoFocus); RAW_SET_PROP_SWITCH_CASE_BASIC(allowFontScaling); RAW_SET_PROP_SWITCH_CASE_BASIC(maxFontSizeMultiplier); RAW_SET_PROP_SWITCH_CASE_BASIC(editable); RAW_SET_PROP_SWITCH_CASE_BASIC(keyboardType); RAW_SET_PROP_SWITCH_CASE_BASIC(returnKeyType); - RAW_SET_PROP_SWITCH_CASE_BASIC(maxLength); RAW_SET_PROP_SWITCH_CASE_BASIC(multiline); - RAW_SET_PROP_SWITCH_CASE_BASIC(placeholder); - RAW_SET_PROP_SWITCH_CASE_BASIC(placeholderTextColor); RAW_SET_PROP_SWITCH_CASE_BASIC(secureTextEntry); - RAW_SET_PROP_SWITCH_CASE_BASIC(selectionColor); - RAW_SET_PROP_SWITCH_CASE_BASIC(selectionHandleColor); - RAW_SET_PROP_SWITCH_CASE_BASIC(defaultValue); RAW_SET_PROP_SWITCH_CASE_BASIC(selectTextOnFocus); RAW_SET_PROP_SWITCH_CASE_BASIC(submitBehavior); RAW_SET_PROP_SWITCH_CASE_BASIC(caretHidden); @@ -356,9 +256,6 @@ void AndroidTextInputProps::setProp( RAW_SET_PROP_SWITCH_CASE_BASIC(fontWeight); RAW_SET_PROP_SWITCH_CASE_BASIC(fontFamily); RAW_SET_PROP_SWITCH_CASE_BASIC(textAlignVertical); - RAW_SET_PROP_SWITCH_CASE_BASIC(cursorColor); - RAW_SET_PROP_SWITCH_CASE_BASIC(mostRecentEventCount); - RAW_SET_PROP_SWITCH_CASE_BASIC(text); case CONSTEXPR_RAW_PROPS_KEY_HASH("value"): { fromRawValue(context, value, this->value, {}); diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h index 82fb75ea1028e4..28e5df5976be84 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h @@ -12,8 +12,7 @@ #include #include -#include -#include +#include #include #include #include @@ -58,7 +57,7 @@ inline folly::dynamic toDynamic( return dynamicValue; } -class AndroidTextInputProps final : public ViewProps, public BaseTextProps { +class AndroidTextInputProps final : public BaseTextInputProps { public: AndroidTextInputProps() = default; AndroidTextInputProps( @@ -81,28 +80,20 @@ class AndroidTextInputProps final : public ViewProps, public BaseTextProps { int numberOfLines{0}; bool disableFullscreenUI{false}; std::string textBreakStrategy{}; - SharedColor underlineColorAndroid{}; std::string inlineImageLeft{}; int inlineImagePadding{0}; std::string importantForAutofill{}; bool showSoftInputOnFocus{false}; std::string autoCapitalize{}; bool autoCorrect{false}; - bool autoFocus{false}; bool allowFontScaling{false}; Float maxFontSizeMultiplier{0.0}; bool editable{false}; std::string keyboardType{}; std::string returnKeyType{}; - int maxLength{0}; bool multiline{false}; - std::string placeholder{}; - SharedColor placeholderTextColor{}; bool secureTextEntry{false}; - SharedColor selectionColor{}; - SharedColor selectionHandleColor{}; std::string value{}; - std::string defaultValue{}; bool selectTextOnFocus{false}; std::string submitBehavior{}; bool caretHidden{false}; @@ -122,15 +113,6 @@ class AndroidTextInputProps final : public ViewProps, public BaseTextProps { std::string fontWeight{}; std::string fontFamily{}; std::string textAlignVertical{}; - SharedColor cursorColor{}; - int mostRecentEventCount{0}; - std::string text{}; - - /* - * Contains all prop values that affect visual representation of the - * paragraph. - */ - ParagraphAttributes paragraphAttributes{}; /** * Auxiliary information to detect if these props are set or not. diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.cpp index 88ae3f35a221c6..c2262b0326793c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.cpp @@ -11,7 +11,7 @@ namespace facebook::react { static jsi::Value textInputMetricsPayload( jsi::Runtime& runtime, - const TextInputMetrics& textInputMetrics) { + const TextInputEventEmitter::Metrics& textInputMetrics) { auto payload = jsi::Object(runtime); payload.setProperty( @@ -36,9 +36,59 @@ static jsi::Value textInputMetricsPayload( return payload; }; +static jsi::Value textInputMetricsScrollPayload( + jsi::Runtime& runtime, + const TextInputEventEmitter::Metrics& textInputMetrics) { + auto payload = jsi::Object(runtime); + + { + auto contentOffset = jsi::Object(runtime); + contentOffset.setProperty(runtime, "x", textInputMetrics.contentOffset.x); + contentOffset.setProperty(runtime, "y", textInputMetrics.contentOffset.y); + payload.setProperty(runtime, "contentOffset", contentOffset); + } + + { + auto contentInset = jsi::Object(runtime); + contentInset.setProperty(runtime, "top", textInputMetrics.contentInset.top); + contentInset.setProperty( + runtime, "left", textInputMetrics.contentInset.left); + contentInset.setProperty( + runtime, "bottom", textInputMetrics.contentInset.bottom); + contentInset.setProperty( + runtime, "right", textInputMetrics.contentInset.right); + payload.setProperty(runtime, "contentInset", contentInset); + } + + { + auto contentSize = jsi::Object(runtime); + contentSize.setProperty( + runtime, "width", textInputMetrics.contentSize.width); + contentSize.setProperty( + runtime, "height", textInputMetrics.contentSize.height); + payload.setProperty(runtime, "contentSize", contentSize); + } + + { + auto layoutMeasurement = jsi::Object(runtime); + layoutMeasurement.setProperty( + runtime, "width", textInputMetrics.layoutMeasurement.width); + layoutMeasurement.setProperty( + runtime, "height", textInputMetrics.layoutMeasurement.height); + payload.setProperty(runtime, "layoutMeasurement", layoutMeasurement); + } + + payload.setProperty( + runtime, + "zoomScale", + textInputMetrics.zoomScale ? textInputMetrics.zoomScale : 1); + + return payload; +}; + static jsi::Value textInputMetricsContentSizePayload( jsi::Runtime& runtime, - const TextInputMetrics& textInputMetrics) { + const TextInputEventEmitter::Metrics& textInputMetrics) { auto payload = jsi::Object(runtime); { @@ -55,7 +105,7 @@ static jsi::Value textInputMetricsContentSizePayload( static jsi::Value keyPressMetricsPayload( jsi::Runtime& runtime, - const KeyPressMetrics& keyPressMetrics) { + const TextInputEventEmitter::KeyPressMetrics& keyPressMetrics) { auto payload = jsi::Object(runtime); payload.setProperty(runtime, "eventCount", keyPressMetrics.eventCount); @@ -76,95 +126,66 @@ static jsi::Value keyPressMetricsPayload( return payload; }; -void TextInputEventEmitter::onFocus( - const TextInputMetrics& textInputMetrics) const { +void TextInputEventEmitter::onFocus(const Metrics& textInputMetrics) const { dispatchTextInputEvent("focus", textInputMetrics); } -void TextInputEventEmitter::onBlur( - const TextInputMetrics& textInputMetrics) const { +void TextInputEventEmitter::onBlur(const Metrics& textInputMetrics) const { dispatchTextInputEvent("blur", textInputMetrics); } -void TextInputEventEmitter::onChange( - const TextInputMetrics& textInputMetrics) const { +void TextInputEventEmitter::onChange(const Metrics& textInputMetrics) const { dispatchTextInputEvent("change", textInputMetrics); } -void TextInputEventEmitter::onChangeSync( - const TextInputMetrics& textInputMetrics) const { - dispatchTextInputEvent( - "changeSync", textInputMetrics, EventPriority::SynchronousBatched); -} - void TextInputEventEmitter::onContentSizeChange( - const TextInputMetrics& textInputMetrics) const { + const Metrics& textInputMetrics) const { dispatchTextInputContentSizeChangeEvent( "contentSizeChange", textInputMetrics); } void TextInputEventEmitter::onSelectionChange( - const TextInputMetrics& textInputMetrics) const { + const Metrics& textInputMetrics) const { dispatchTextInputEvent("selectionChange", textInputMetrics); } void TextInputEventEmitter::onEndEditing( - const TextInputMetrics& textInputMetrics) const { + const Metrics& textInputMetrics) const { dispatchTextInputEvent("endEditing", textInputMetrics); } void TextInputEventEmitter::onSubmitEditing( - const TextInputMetrics& textInputMetrics) const { + const Metrics& textInputMetrics) const { dispatchTextInputEvent("submitEditing", textInputMetrics); } void TextInputEventEmitter::onKeyPress( const KeyPressMetrics& keyPressMetrics) const { - dispatchEvent( - "keyPress", - [keyPressMetrics](jsi::Runtime& runtime) { - return keyPressMetricsPayload(runtime, keyPressMetrics); - }, - EventPriority::AsynchronousBatched); -} - -void TextInputEventEmitter::onKeyPressSync( - const KeyPressMetrics& keyPressMetrics) const { - dispatchEvent( - "keyPressSync", - [keyPressMetrics](jsi::Runtime& runtime) { - return keyPressMetricsPayload(runtime, keyPressMetrics); - }, - EventPriority::SynchronousBatched); + dispatchEvent("keyPress", [keyPressMetrics](jsi::Runtime& runtime) { + return keyPressMetricsPayload(runtime, keyPressMetrics); + }); } -void TextInputEventEmitter::onScroll( - const TextInputMetrics& textInputMetrics) const { - dispatchTextInputEvent("scroll", textInputMetrics); +void TextInputEventEmitter::onScroll(const Metrics& textInputMetrics) const { + dispatchEvent("scroll", [textInputMetrics](jsi::Runtime& runtime) { + return textInputMetricsScrollPayload(runtime, textInputMetrics); + }); } void TextInputEventEmitter::dispatchTextInputEvent( const std::string& name, - const TextInputMetrics& textInputMetrics, - EventPriority priority) const { - dispatchEvent( - name, - [textInputMetrics](jsi::Runtime& runtime) { - return textInputMetricsPayload(runtime, textInputMetrics); - }, - priority); + const Metrics& textInputMetrics) const { + dispatchEvent(name, [textInputMetrics](jsi::Runtime& runtime) { + return textInputMetricsPayload(runtime, textInputMetrics); + }); } void TextInputEventEmitter::dispatchTextInputContentSizeChangeEvent( const std::string& name, - const TextInputMetrics& textInputMetrics, - EventPriority priority) const { - dispatchEvent( - name, - [textInputMetrics](jsi::Runtime& runtime) { - return textInputMetricsContentSizePayload(runtime, textInputMetrics); - }, - priority); + const Metrics& textInputMetrics) const { + dispatchEvent(name, [textInputMetrics](jsi::Runtime& runtime) { + return textInputMetricsContentSizePayload(runtime, textInputMetrics); + }); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.h index 0ab2b18544fc34..9182dd3d2edccb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputEventEmitter.h @@ -12,52 +12,46 @@ namespace facebook::react { -class TextInputMetrics { - public: - std::string text; - AttributedString::Range selectionRange; - // ScrollView-like metrics - Size contentSize; - Point contentOffset; - EdgeInsets contentInset; - Size containerSize; - int eventCount; - Size layoutMeasurement; - float zoomScale; -}; - -class KeyPressMetrics { - public: - std::string text; - int eventCount; -}; - class TextInputEventEmitter : public ViewEventEmitter { public: using ViewEventEmitter::ViewEventEmitter; - void onFocus(const TextInputMetrics& textInputMetrics) const; - void onBlur(const TextInputMetrics& textInputMetrics) const; - void onChange(const TextInputMetrics& textInputMetrics) const; - void onChangeSync(const TextInputMetrics& textInputMetrics) const; - void onContentSizeChange(const TextInputMetrics& textInputMetrics) const; - void onSelectionChange(const TextInputMetrics& textInputMetrics) const; - void onEndEditing(const TextInputMetrics& textInputMetrics) const; - void onSubmitEditing(const TextInputMetrics& textInputMetrics) const; + struct Metrics { + std::string text; + AttributedString::Range selectionRange; + // ScrollView-like metrics + Size contentSize; + Point contentOffset; + EdgeInsets contentInset; + Size containerSize; + int eventCount; + Size layoutMeasurement; + Float zoomScale; + }; + + struct KeyPressMetrics { + std::string text; + int eventCount; + }; + + void onFocus(const Metrics& textInputMetrics) const; + void onBlur(const Metrics& textInputMetrics) const; + void onChange(const Metrics& textInputMetrics) const; + void onContentSizeChange(const Metrics& textInputMetrics) const; + void onSelectionChange(const Metrics& textInputMetrics) const; + void onEndEditing(const Metrics& textInputMetrics) const; + void onSubmitEditing(const Metrics& textInputMetrics) const; void onKeyPress(const KeyPressMetrics& keyPressMetrics) const; - void onKeyPressSync(const KeyPressMetrics& keyPressMetrics) const; - void onScroll(const TextInputMetrics& textInputMetrics) const; + void onScroll(const Metrics& textInputMetrics) const; private: void dispatchTextInputEvent( const std::string& name, - const TextInputMetrics& textInputMetrics, - EventPriority priority = EventPriority::AsynchronousBatched) const; + const Metrics& textInputMetrics) const; void dispatchTextInputContentSizeChangeEvent( const std::string& name, - const TextInputMetrics& textInputMetrics, - EventPriority priority = EventPriority::AsynchronousBatched) const; + const Metrics& textInputMetrics) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp index a825971ddbe8c8..43f5e9efa54c58 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp @@ -18,75 +18,8 @@ TextInputProps::TextInputProps( const PropsParserContext& context, const TextInputProps& sourceProps, const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - BaseTextProps(context, sourceProps, rawProps), + : BaseTextInputProps(context, sourceProps, rawProps), traits(convertRawProp(context, rawProps, sourceProps.traits, {})), - paragraphAttributes(convertRawProp( - context, - rawProps, - sourceProps.paragraphAttributes, - {})), - defaultValue(convertRawProp( - context, - rawProps, - "defaultValue", - sourceProps.defaultValue, - {})), - placeholder(convertRawProp( - context, - rawProps, - "placeholder", - sourceProps.placeholder, - {})), - placeholderTextColor(convertRawProp( - context, - rawProps, - "placeholderTextColor", - sourceProps.placeholderTextColor, - {})), - maxLength(convertRawProp( - context, - rawProps, - "maxLength", - sourceProps.maxLength, - {})), - cursorColor(convertRawProp( - context, - rawProps, - "cursorColor", - sourceProps.cursorColor, - {})), - selectionColor(convertRawProp( - context, - rawProps, - "selectionColor", - sourceProps.selectionColor, - {})), - selectionHandleColor(convertRawProp( - context, - rawProps, - "selectionHandleColor", - sourceProps.selectionHandleColor, - {})), - underlineColorAndroid(convertRawProp( - context, - rawProps, - "underlineColorAndroid", - sourceProps.underlineColorAndroid, - {})), - text(convertRawProp(context, rawProps, "text", sourceProps.text, {})), - mostRecentEventCount(convertRawProp( - context, - rawProps, - "mostRecentEventCount", - sourceProps.mostRecentEventCount, - {})), - autoFocus(convertRawProp( - context, - rawProps, - "autoFocus", - sourceProps.autoFocus, - {})), selection(convertRawProp( context, rawProps, @@ -112,15 +45,6 @@ TextInputProps::TextInputProps( sourceProps.onChangeSync, {})){}; -void TextInputProps::setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value) { - ViewProps::setProp(context, hash, propName, value); - BaseTextProps::setProp(context, hash, propName, value); -} - TextAttributes TextInputProps::getEffectiveTextAttributes( Float fontSizeMultiplier) const { auto result = TextAttributes::defaultTextAttributes(); diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h index e3db155099c78e..ea1583c917136c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h @@ -11,18 +11,16 @@ #include #include #include -#include -#include +#include #include #include #include -#include #include #include namespace facebook::react { -class TextInputProps final : public ViewProps, public BaseTextProps { +class TextInputProps final : public BaseTextInputProps { public: TextInputProps() = default; TextInputProps( @@ -30,40 +28,12 @@ class TextInputProps final : public ViewProps, public BaseTextProps { const TextInputProps& sourceProps, const RawProps& rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); - #pragma mark - Props - const TextInputTraits traits{}; - const ParagraphAttributes paragraphAttributes{}; - - std::string const defaultValue{}; - - std::string const placeholder{}; - const SharedColor placeholderTextColor{}; - - int maxLength{}; - - /* - * Tint colors - */ - const SharedColor cursorColor{}; - const SharedColor selectionColor{}; - const SharedColor selectionHandleColor{}; - // TODO: Rename to `tintColor` and make universal. - const SharedColor underlineColorAndroid{}; /* * "Private" (only used by TextInput.js) props */ - std::string const text{}; - const int mostRecentEventCount{0}; - - bool autoFocus{false}; std::optional selection{}; std::string const inputAccessoryViewID{}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.cpp index 3d55f25c38cb9c..358fb3773ebf99 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.cpp @@ -140,6 +140,14 @@ BaseViewProps::BaseViewProps( "shadowRadius", sourceProps.shadowRadius, {})), + cursor( + CoreFeatures::enablePropIteratorSetter ? sourceProps.cursor + : convertRawProp( + context, + rawProps, + "cursor", + sourceProps.cursor, + {})), transform( CoreFeatures::enablePropIteratorSetter ? sourceProps.transform : convertRawProp( @@ -281,6 +289,7 @@ void BaseViewProps::setProp( RAW_SET_PROP_SWITCH_CASE_BASIC(collapsable); RAW_SET_PROP_SWITCH_CASE_BASIC(removeClippedSubviews); RAW_SET_PROP_SWITCH_CASE_BASIC(experimental_layoutConformance); + RAW_SET_PROP_SWITCH_CASE_BASIC(cursor); // events field VIEW_EVENT_CASE(PointerEnter); VIEW_EVENT_CASE(PointerEnterCapture); diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h index b7bdd9afc7eb55..73cf45387e871c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h @@ -52,9 +52,18 @@ class BaseViewProps : public YogaStylableProps, public AccessibilityProps { Float shadowOpacity{}; Float shadowRadius{3}; + Cursor cursor{}; + // Transform Transform transform{}; - TransformOrigin transformOrigin{}; + TransformOrigin transformOrigin{ + { + ValueUnit{50.0f, UnitType::Percent}, + ValueUnit{50.0f, UnitType::Percent}, + }, + 0.0f, + + }; BackfaceVisibility backfaceVisibility{}; bool shouldRasterize{}; std::optional zIndex{}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.cpp index 154273a830dfa3..d147e5db54112c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.cpp @@ -45,35 +45,25 @@ static jsi::Value touchEventPayload( void TouchEventEmitter::dispatchTouchEvent( std::string type, const TouchEvent& event, - EventPriority priority, RawEvent::Category category) const { dispatchEvent( std::move(type), [event](jsi::Runtime& runtime) { return touchEventPayload(runtime, event); }, - priority, category); } void TouchEventEmitter::dispatchPointerEvent( std::string type, const PointerEvent& event, - EventPriority priority, RawEvent::Category category) const { dispatchEvent( - std::move(type), - std::make_shared(event), - priority, - category); + std::move(type), std::make_shared(event), category); } void TouchEventEmitter::onTouchStart(const TouchEvent& event) const { - dispatchTouchEvent( - "touchStart", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + dispatchTouchEvent("touchStart", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onTouchMove(const TouchEvent& event) const { @@ -83,43 +73,25 @@ void TouchEventEmitter::onTouchMove(const TouchEvent& event) const { } void TouchEventEmitter::onTouchEnd(const TouchEvent& event) const { - dispatchTouchEvent( - "touchEnd", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + dispatchTouchEvent("touchEnd", event, RawEvent::Category::ContinuousEnd); } void TouchEventEmitter::onTouchCancel(const TouchEvent& event) const { - dispatchTouchEvent( - "touchCancel", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + dispatchTouchEvent("touchCancel", event, RawEvent::Category::ContinuousEnd); } void TouchEventEmitter::onClick(const PointerEvent& event) const { - dispatchPointerEvent( - "click", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::Discrete); + dispatchPointerEvent("click", event, RawEvent::Category::Discrete); } void TouchEventEmitter::onPointerCancel(const PointerEvent& event) const { dispatchPointerEvent( - "pointerCancel", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + "pointerCancel", event, RawEvent::Category::ContinuousEnd); } void TouchEventEmitter::onPointerDown(const PointerEvent& event) const { dispatchPointerEvent( - "pointerDown", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + "pointerDown", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onPointerMove(const PointerEvent& event) const { @@ -127,59 +99,37 @@ void TouchEventEmitter::onPointerMove(const PointerEvent& event) const { } void TouchEventEmitter::onPointerUp(const PointerEvent& event) const { - dispatchPointerEvent( - "pointerUp", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + dispatchPointerEvent("pointerUp", event, RawEvent::Category::ContinuousEnd); } void TouchEventEmitter::onPointerEnter(const PointerEvent& event) const { dispatchPointerEvent( - "pointerEnter", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + "pointerEnter", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onPointerLeave(const PointerEvent& event) const { dispatchPointerEvent( - "pointerLeave", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + "pointerLeave", event, RawEvent::Category::ContinuousEnd); } void TouchEventEmitter::onPointerOver(const PointerEvent& event) const { dispatchPointerEvent( - "pointerOver", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + "pointerOver", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onPointerOut(const PointerEvent& event) const { dispatchPointerEvent( - "pointerOut", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + "pointerOut", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onGotPointerCapture(const PointerEvent& event) const { dispatchPointerEvent( - "gotPointerCapture", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousStart); + "gotPointerCapture", event, RawEvent::Category::ContinuousStart); } void TouchEventEmitter::onLostPointerCapture(const PointerEvent& event) const { dispatchPointerEvent( - "lostPointerCapture", - event, - EventPriority::AsynchronousBatched, - RawEvent::Category::ContinuousEnd); + "lostPointerCapture", event, RawEvent::Category::ContinuousEnd); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h index 08b368c0eb552d..869e3ac34054ba 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h @@ -45,12 +45,10 @@ class TouchEventEmitter : public EventEmitter { void dispatchTouchEvent( std::string type, const TouchEvent& event, - EventPriority priority, RawEvent::Category category) const; void dispatchPointerEvent( std::string type, const PointerEvent& event, - EventPriority priority, RawEvent::Category category) const; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp index fe11e92e1a5771..9c92eac7ccc9e9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp @@ -60,7 +60,7 @@ void ViewShadowNode::initialize() noexcept { viewProps.accessibilityElementsHidden || viewProps.accessibilityViewIsModal || viewProps.importantForAccessibility != ImportantForAccessibility::Auto || - viewProps.removeClippedSubviews || + viewProps.removeClippedSubviews || viewProps.cursor != Cursor::Auto || HostPlatformViewTraitsInitializer::formsStackingContext(viewProps); bool formsView = formsStackingContext || diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h index aa6fb367daab7d..bbd9f46cfafa6a 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h @@ -705,6 +705,28 @@ inline void fromRawValue( react_native_expect(false); } +inline void fromRawValue( + const PropsParserContext& context, + const RawValue& value, + Cursor& result) { + result = Cursor::Auto; + react_native_expect(value.hasType()); + if (!value.hasType()) { + return; + } + auto stringValue = (std::string)value; + if (stringValue == "auto") { + result = Cursor::Auto; + return; + } + if (stringValue == "pointer") { + result = Cursor::Pointer; + return; + } + LOG(ERROR) << "Could not parse Cursor:" << stringValue; + react_native_expect(false); +} + inline void fromRawValue( const PropsParserContext& /*context*/, const RawValue& value, diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h b/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h index 162f2292cc6a64..09f98979517a13 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h @@ -91,6 +91,8 @@ enum class BorderCurve : uint8_t { Circular, Continuous }; enum class BorderStyle : uint8_t { Solid, Dotted, Dashed }; +enum class Cursor : uint8_t { Auto, Pointer }; + enum class LayoutConformance : uint8_t { Undefined, Classic, Strict }; template diff --git a/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.cpp b/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.cpp deleted file mode 100644 index 0a9467eb5540b8..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.cpp +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "BatchedEventQueue.h" - -namespace facebook::react { - -BatchedEventQueue::BatchedEventQueue( - EventQueueProcessor eventProcessor, - std::unique_ptr eventBeat) - : EventQueue(std::move(eventProcessor), std::move(eventBeat)) {} - -void BatchedEventQueue::onEnqueue() const { - eventBeat_->request(); -} -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.h b/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.h deleted file mode 100644 index bc3e5a669d7eeb..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/core/BatchedEventQueue.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -/* - * Event Queue that dispatches event in batches synchronizing them with - * an Event Beat. - */ -class BatchedEventQueue final : public EventQueue { - public: - BatchedEventQueue( - EventQueueProcessor eventProcessor, - std::unique_ptr eventBeat); - - void onEnqueue() const override; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h index 6a0ab8daf2f0b2..4755dc875c7c02 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h @@ -58,16 +58,10 @@ class ConcreteState : public State { * function for cases where a new value of data does not depend on an old * value. */ - void updateState(Data&& newData, EventPriority priority) const { - updateState( - [data{std::move(newData)}](const Data& oldData) -> SharedData { - return std::make_shared(data); - }, - priority); - } - void updateState(Data&& newData) const { - updateState(std::move(newData), EventPriority::AsynchronousBatched); + updateState([data{std::move(newData)}](const Data& oldData) -> SharedData { + return std::make_shared(data); + }); } /* @@ -79,8 +73,7 @@ class ConcreteState : public State { * return `nullptr`. */ void updateState( - std::function callback, - EventPriority priority = EventPriority::AsynchronousBatched) const { + std::function callback) const { auto family = family_.lock(); if (!family) { @@ -95,7 +88,7 @@ class ConcreteState : public State { return callback(*static_cast(oldData.get())); }}; - family->dispatchRawState(std::move(stateUpdate), priority); + family->dispatchRawState(std::move(stateUpdate)); } #ifdef ANDROID diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.cpp b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.cpp index e90aa160fd1614..7ec8b8e2ed336e 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.cpp @@ -11,7 +11,8 @@ namespace facebook::react { folly::dynamic mergeDynamicProps( const folly::dynamic& source, - const folly::dynamic& patch) { + const folly::dynamic& patch, + NullValueStrategy nullValueStrategy) { auto result = source; if (!result.isObject()) { @@ -25,6 +26,10 @@ folly::dynamic mergeDynamicProps( // Note, here we have to preserve sub-prop objects with `null` value as // an indication for the legacy mounting layer that it needs to clean them up. for (const auto& pair : patch.items()) { + if (nullValueStrategy == NullValueStrategy::Ignore && + source.find(pair.first) == source.items().end()) { + continue; + } result[pair.first] = pair.second; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h index f5abb9d21e3b00..d642d8cfdba8c7 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h @@ -12,13 +12,40 @@ namespace facebook::react { +/* + * Enum defining how missing value in `source` is handled if it is present in + * `patch`. + */ +enum class NullValueStrategy { + /* + * Key in source will be overriden by the matching key in patch. + * + * Example: + * source: {"key": "value"} + * patch: {"key": "new value"} + * returned: {"key": "new value"} + */ + Override, + + /* + * In case key is missing in source, value from patch will be ignored. + * + * Example: + * source: {"key 1": "value 1"} + * patch: {"key": "new value 1", "key 2": "new value 2"} + * returned: {"key": "new value 1"} + */ + Ignore +}; + /* * Accepts two `folly::dynamic` objects as arguments. Both arguments need to * represent a dictionary. It updates `source` with key/value pairs from - * `patch`, overriding existing keys. + * `patch`. */ folly::dynamic mergeDynamicProps( const folly::dynamic& source, - const folly::dynamic& patch); + const folly::dynamic& patch, + NullValueStrategy nullValueStrategy); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp index e6385ae6d41403..c6b98efd8201bd 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp @@ -10,9 +10,8 @@ #include #include "EventLogger.h" -#include "BatchedEventQueue.h" +#include "EventQueue.h" #include "RawEvent.h" -#include "UnbatchedEventQueue.h" namespace facebook::react { @@ -21,21 +20,10 @@ EventDispatcher::EventDispatcher( const EventBeat::Factory& synchonousEventBeatFactory, const EventBeat::Factory& asynchronousEventBeatFactory, const EventBeat::SharedOwnerBox& ownerBox) - : synchronousUnbatchedQueue_(std::make_unique( - eventProcessor, - synchonousEventBeatFactory(ownerBox))), - synchronousBatchedQueue_(std::make_unique( - eventProcessor, - synchonousEventBeatFactory(ownerBox))), - asynchronousUnbatchedQueue_(std::make_unique( - eventProcessor, - asynchronousEventBeatFactory(ownerBox))), - asynchronousBatchedQueue_(std::make_unique( - eventProcessor, - asynchronousEventBeatFactory(ownerBox))) {} + : eventQueue_( + EventQueue(eventProcessor, asynchronousEventBeatFactory(ownerBox))) {} -void EventDispatcher::dispatchEvent(RawEvent&& rawEvent, EventPriority priority) - const { +void EventDispatcher::dispatchEvent(RawEvent&& rawEvent) const { // Allows the event listener to interrupt default event dispatch if (eventListeners_.willDispatchEvent(rawEvent)) { return; @@ -45,13 +33,11 @@ void EventDispatcher::dispatchEvent(RawEvent&& rawEvent, EventPriority priority) if (eventLogger != nullptr) { rawEvent.loggingTag = eventLogger->onEventStart(rawEvent.type); } - getEventQueue(priority).enqueueEvent(std::move(rawEvent)); + eventQueue_.enqueueEvent(std::move(rawEvent)); } -void EventDispatcher::dispatchStateUpdate( - StateUpdate&& stateUpdate, - EventPriority priority) const { - getEventQueue(priority).enqueueStateUpdate(std::move(stateUpdate)); +void EventDispatcher::dispatchStateUpdate(StateUpdate&& stateUpdate) const { + eventQueue_.enqueueStateUpdate(std::move(stateUpdate)); } void EventDispatcher::dispatchUniqueEvent(RawEvent&& rawEvent) const { @@ -59,20 +45,7 @@ void EventDispatcher::dispatchUniqueEvent(RawEvent&& rawEvent) const { if (eventListeners_.willDispatchEvent(rawEvent)) { return; } - asynchronousBatchedQueue_->enqueueUniqueEvent(std::move(rawEvent)); -} - -const EventQueue& EventDispatcher::getEventQueue(EventPriority priority) const { - switch (priority) { - case EventPriority::SynchronousUnbatched: - return *synchronousUnbatchedQueue_; - case EventPriority::SynchronousBatched: - return *synchronousBatchedQueue_; - case EventPriority::AsynchronousUnbatched: - return *asynchronousUnbatchedQueue_; - case EventPriority::AsynchronousBatched: - return *asynchronousBatchedQueue_; - } + eventQueue_.enqueueUniqueEvent(std::move(rawEvent)); } void EventDispatcher::addListener( diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h index 77594bfb877606..3bc5fce8f69073 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h @@ -7,13 +7,11 @@ #pragma once -#include #include #include -#include +#include #include #include -#include namespace facebook::react { @@ -37,7 +35,7 @@ class EventDispatcher { /* * Dispatches a raw event with given priority using event-delivery pipe. */ - void dispatchEvent(RawEvent&& rawEvent, EventPriority priority) const; + void dispatchEvent(RawEvent&& rawEvent) const; /* * Dispatches a raw event with asynchronous batched priority. Before the @@ -49,8 +47,7 @@ class EventDispatcher { /* * Dispatches a state update with given priority. */ - void dispatchStateUpdate(StateUpdate&& stateUpdate, EventPriority priority) - const; + void dispatchStateUpdate(StateUpdate&& stateUpdate) const; #pragma mark - Event listeners /* @@ -65,12 +62,7 @@ class EventDispatcher { const std::shared_ptr& listener) const; private: - const EventQueue& getEventQueue(EventPriority priority) const; - - std::unique_ptr synchronousUnbatchedQueue_; - std::unique_ptr synchronousBatchedQueue_; - std::unique_ptr asynchronousUnbatchedQueue_; - std::unique_ptr asynchronousBatchedQueue_; + EventQueue eventQueue_; mutable EventListenerContainer eventListeners_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp index bd9a7c0e39a21b..1b37492583777a 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp @@ -58,14 +58,12 @@ EventEmitter::EventEmitter( void EventEmitter::dispatchEvent( std::string type, const folly::dynamic& payload, - EventPriority priority, RawEvent::Category category) const { dispatchEvent( std::move(type), [payload](jsi::Runtime& runtime) { return valueFromDynamic(runtime, payload); }, - priority, category); } @@ -80,19 +78,16 @@ void EventEmitter::dispatchUniqueEvent( void EventEmitter::dispatchEvent( std::string type, const ValueFactory& payloadFactory, - EventPriority priority, RawEvent::Category category) const { dispatchEvent( std::move(type), std::make_shared(payloadFactory), - priority, category); } void EventEmitter::dispatchEvent( std::string type, SharedEventPayload payload, - EventPriority priority, RawEvent::Category category) const { SystraceSection s("EventEmitter::dispatchEvent", "type", type); @@ -101,13 +96,11 @@ void EventEmitter::dispatchEvent( return; } - eventDispatcher->dispatchEvent( - RawEvent( - normalizeEventType(std::move(type)), - std::move(payload), - eventTarget_, - category), - priority); + eventDispatcher->dispatchEvent(RawEvent( + normalizeEventType(std::move(type)), + std::move(payload), + eventTarget_, + category)); } void EventEmitter::dispatchUniqueEvent( diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h index d31e30585ff101..04bb9ebe42c0d7 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -66,19 +65,16 @@ class EventEmitter { std::string type, const ValueFactory& payloadFactory = EventEmitter::defaultPayloadFactory(), - EventPriority priority = EventPriority::AsynchronousBatched, RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchEvent( std::string type, const folly::dynamic& payload, - EventPriority priority = EventPriority::AsynchronousBatched, RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchEvent( std::string type, SharedEventPayload payload, - EventPriority priority = EventPriority::AsynchronousBatched, RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchUniqueEvent(std::string type, const folly::dynamic& payload) diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp index 099e529e48dd56..cef50c68380d69 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp @@ -75,6 +75,10 @@ void EventQueue::enqueueStateUpdate(StateUpdate&& stateUpdate) const { onEnqueue(); } +void EventQueue::onEnqueue() const { + eventBeat_->request(); +} + void EventQueue::onBeat(jsi::Runtime& runtime) const { flushStateUpdates(); flushEvents(runtime); diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h index a4bd7b087e9e61..14e7c18d0b00ed 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h @@ -28,7 +28,6 @@ class EventQueue { EventQueue( EventQueueProcessor eventProcessor, std::unique_ptr eventBeat); - virtual ~EventQueue() = default; /* * Enqueues and (probably later) dispatch a given event. @@ -55,7 +54,7 @@ class EventQueue { * Override in subclasses to trigger beat `request` and/or beat `induce`. * Default implementation does nothing. */ - virtual void onEnqueue() const = 0; + void onEnqueue() const; void onBeat(jsi::Runtime& runtime) const; void flushEvents(jsi::Runtime& runtime) const; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp index d51cb8ff2311a1..e257f39e079c39 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp @@ -42,7 +42,9 @@ Props::Shared ShadowNode::propsForClonedShadowNode( if (!hasBeenMounted && sourceNodeHasRawProps && props) { auto& castedProps = const_cast(*props); castedProps.rawProps = mergeDynamicProps( - sourceShadowNode.getProps()->rawProps, props->rawProps); + sourceShadowNode.getProps()->rawProps, + props->rawProps, + NullValueStrategy::Override); return props; } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.cpp b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.cpp index 0e73b0a5cf3687..0e7fbdc2ca47ab 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.cpp @@ -136,15 +136,13 @@ std::shared_ptr ShadowNodeFamily::getMostRecentStateIfObsolete( return mostRecentState_; } -void ShadowNodeFamily::dispatchRawState( - StateUpdate&& stateUpdate, - EventPriority priority) const { +void ShadowNodeFamily::dispatchRawState(StateUpdate&& stateUpdate) const { auto eventDispatcher = eventDispatcher_.lock(); if (!eventDispatcher) { return; } - eventDispatcher->dispatchStateUpdate(std::move(stateUpdate), priority); + eventDispatcher->dispatchStateUpdate(std::move(stateUpdate)); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h index dc5dbc815317f0..92f79cfb532e2b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h @@ -96,8 +96,7 @@ class ShadowNodeFamily final { /* * Dispatches a state update with given priority. */ - void dispatchRawState(StateUpdate&& stateUpdate, EventPriority priority) - const; + void dispatchRawState(StateUpdate&& stateUpdate) const; /* * Holds currently applied native props. `nullptr` if setNativeProps API is diff --git a/packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.h b/packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.h deleted file mode 100644 index 9b2f9fd8207fdf..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/core/UnbatchedEventQueue.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -namespace facebook::react { - -/* - * Event Queue that dispatches events as granular as possible without waiting - * for the next beat. - */ -class UnbatchedEventQueue final : public EventQueue { - public: - using EventQueue::EventQueue; - - void onEnqueue() const override; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/DynamicPropsUtilitiesTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/DynamicPropsUtilitiesTest.cpp index 1ebb12b3a81cd2..a79767861dda6f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/DynamicPropsUtilitiesTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/DynamicPropsUtilitiesTest.cpp @@ -24,7 +24,7 @@ TEST(DynamicPropsUtilitiesTest, handleNestedObjects) { map2["style"] = dynamic::object("backgroundColor", "blue")("color", "black"); map2["height"] = 100; - auto result = mergeDynamicProps(map1, map2); + auto result = mergeDynamicProps(map1, map2, NullValueStrategy::Override); EXPECT_TRUE(result["style"].isObject()); EXPECT_TRUE(result["style"]["backgroundColor"].isString()); @@ -42,25 +42,39 @@ TEST(DynamicPropsUtilitiesTest, handleEmptyObject) { dynamic map2 = dynamic::object; map2["height"] = 100; - auto result = mergeDynamicProps(map1, map2); + auto result = mergeDynamicProps(map1, map2, NullValueStrategy::Override); EXPECT_TRUE(result["height"].isInt()); EXPECT_EQ(result["height"], 100); - result = mergeDynamicProps(map1, map2); + result = mergeDynamicProps(map1, map2, NullValueStrategy::Override); EXPECT_TRUE(result["height"].isInt()); EXPECT_EQ(result["height"], 100); } -TEST(DynamicPropsUtilitiesTest, handleNull) { +TEST(DynamicPropsUtilitiesTest, handleNullValue) { dynamic map1 = dynamic::object; map1["height"] = 100; dynamic map2 = dynamic::object; map2["height"] = nullptr; - auto result = mergeDynamicProps(map1, map2); + auto result = mergeDynamicProps(map1, map2, NullValueStrategy::Override); EXPECT_TRUE(result["height"].isNull()); } + +TEST(DynamicPropsUtilitiesTest, testNullValueStrategyIgnore) { + dynamic map1 = dynamic::object; + map1["height"] = 100; + + dynamic map2 = dynamic::object; + map2["width"] = 200; + map2["height"] = 101; + + auto result = mergeDynamicProps(map1, map2, NullValueStrategy::Ignore); + + EXPECT_EQ(result["height"], 101); + EXPECT_TRUE(result["width"].isNull()); +} diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.cpp b/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.cpp new file mode 100644 index 00000000000000..428747a31948c1 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ColorComponents.h" +#include + +namespace facebook::react { + +static ColorSpace defaultColorSpace = ColorSpace::sRGB; + +ColorSpace getDefaultColorSpace() { + return defaultColorSpace; +} + +void setDefaultColorSpace(ColorSpace newColorSpace) { + defaultColorSpace = newColorSpace; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.h b/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.h index 0a3887a3caeb7e..ce60f7a4074f4a 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ColorComponents.h @@ -9,11 +9,17 @@ namespace facebook::react { +enum class ColorSpace { sRGB, DisplayP3 }; + +ColorSpace getDefaultColorSpace(); +void setDefaultColorSpace(ColorSpace newColorSpace); + struct ColorComponents { float red{0}; float green{0}; float blue{0}; float alpha{0}; + ColorSpace colorSpace{getDefaultColorSpace()}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/React-graphics.podspec b/packages/react-native/ReactCommon/react/renderer/graphics/React-graphics.podspec index b5faee3286fc0e..94743610da2fe2 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/React-graphics.podspec +++ b/packages/react-native/ReactCommon/react/renderer/graphics/React-graphics.podspec @@ -61,7 +61,8 @@ Pod::Spec.new do |s| s.dependency "glog" s.dependency "RCT-Folly/Fabric", folly_version - s.dependency "React-Core/Default", version + s.dependency "React-jsi" + s.dependency "React-jsiexecutor" s.dependency "React-utils" s.dependency "DoubleConversion" s.dependency "fmt", "9.1.0" diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h b/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h index fbc07288fa318b..87b8fcab8c6f31 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h @@ -44,6 +44,24 @@ inline void fromRawValueShared( result = colorFromComponents(colorComponents); } else { + if (value.hasType>()) { + const auto& items = (std::unordered_map)value; + if (items.find("space") != items.end()) { + colorComponents.red = (float)items.at("r"); + colorComponents.green = (float)items.at("g"); + colorComponents.blue = (float)items.at("b"); + colorComponents.alpha = (float)items.at("a"); + colorComponents.colorSpace = getDefaultColorSpace(); + std::string space = (std::string)items.at("space"); + if (space == "display-p3") { + colorComponents.colorSpace = ColorSpace::DisplayP3; + } else if (space == "srgb") { + colorComponents.colorSpace = ColorSpace::sRGB; + } + result = colorFromComponents(colorComponents); + return; + } + } result = parsePlatformColor(contextContainer, surfaceId, value); } } diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.mm b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.mm index 36cd4ac08f7b75..3d1040f1542569 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.mm +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.mm @@ -87,6 +87,12 @@ int32_t ColorFromUIColor(const std::shared_ptr &uiColor) UIColor *_Nullable UIColorFromComponentsColor(const facebook::react::ColorComponents &components) { + if (components.colorSpace == ColorSpace::DisplayP3) { + return [UIColor colorWithDisplayP3Red:components.red + green:components.green + blue:components.blue + alpha:components.alpha]; + } return [UIColor colorWithRed:components.red green:components.green blue:components.blue alpha:components.alpha]; } } // anonymous namespace diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTImagePrimitivesConversions.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTImagePrimitivesConversions.h index 0aa6a75b92e0ba..6d63cdad1e6da7 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTImagePrimitivesConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTImagePrimitivesConversions.h @@ -48,10 +48,10 @@ inline static NSURL *NSURLFromImageSource(const facebook::react::ImageSource &im { // `NSURL` has a history of crashing with bad input, so let's be safe. @try { - NSString *urlString = [NSString stringWithCString:imageSource.uri.c_str() encoding:NSASCIIStringEncoding]; + NSString *urlString = [NSString stringWithUTF8String:imageSource.uri.c_str()]; if (!imageSource.bundle.empty()) { - NSString *bundle = [NSString stringWithCString:imageSource.bundle.c_str() encoding:NSASCIIStringEncoding]; + NSString *bundle = [NSString stringWithUTF8String:imageSource.bundle.c_str()]; urlString = [NSString stringWithFormat:@"%@.bundle/%@", bundle, urlString]; } diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp index 8a46d17fa3b0da..5d9c0aa56ef912 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp @@ -61,6 +61,14 @@ int32_t MapBuffer::getInt(Key key) const { bytes_.data() + valueOffset(bucketIndex)); } +int64_t MapBuffer::getLong(Key key) const { + auto bucketIndex = getKeyBucket(key); + react_native_assert(bucketIndex != -1 && "Key not found in MapBuffer"); + + return *reinterpret_cast( + bytes_.data() + valueOffset(bucketIndex)); +} + bool MapBuffer::getBool(Key key) const { return getInt(key) != 0; } diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h index 1efe45cf063114..968747ee64fb71 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h @@ -104,6 +104,7 @@ class MapBuffer { Double = 2, String = 3, Map = 4, + Long = 5, }; explicit MapBuffer(std::vector data); @@ -118,6 +119,8 @@ class MapBuffer { int32_t getInt(MapBuffer::Key key) const; + int64_t getLong(MapBuffer::Key key) const; + bool getBool(MapBuffer::Key key) const; double getDouble(MapBuffer::Key key) const; diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.cpp b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.cpp index 7bf76d91e6907e..c7eb0e38e9aeef 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.cpp @@ -13,6 +13,7 @@ using namespace facebook::react; namespace facebook::react { constexpr uint32_t INT_SIZE = sizeof(uint32_t); +constexpr uint32_t LONG_SIZE = sizeof(uint64_t); constexpr uint32_t DOUBLE_SIZE = sizeof(double); constexpr uint32_t MAX_BUCKET_VALUE_SIZE = sizeof(uint64_t); @@ -76,6 +77,14 @@ void MapBufferBuilder::putInt(MapBuffer::Key key, int32_t value) { INT_SIZE); } +void MapBufferBuilder::putLong(MapBuffer::Key key, int64_t value) { + storeKeyValue( + key, + MapBuffer::DataType::Long, + reinterpret_cast(&value), + LONG_SIZE); +} + void MapBufferBuilder::putString(MapBuffer::Key key, const std::string& value) { auto strSize = value.size(); const char* strData = value.data(); diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h index 60ca37d20aba74..2260e690a2d785 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h @@ -27,7 +27,7 @@ class MapBufferBuilder { void putInt(MapBuffer::Key key, int32_t value); - // TODO: Support 64 bit integers + void putLong(MapBuffer::Key key, int64_t value); void putBool(MapBuffer::Key key, bool value); diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/tests/MapBufferTest.cpp b/packages/react-native/ReactCommon/react/renderer/mapbuffer/tests/MapBufferTest.cpp index 8f3baaaf59fdcf..5be4c9e1272d25 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/tests/MapBufferTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/tests/MapBufferTest.cpp @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +#include #include #include @@ -27,6 +28,26 @@ TEST(MapBufferTest, testSimpleIntMap) { EXPECT_EQ(map.getInt(1), 4321); } +TEST(MapBufferTest, testSimpleLongMap) { + auto builder = MapBufferBuilder(); + + int64_t minInt64 = std::numeric_limits::min(); + int64_t maxInt64 = std::numeric_limits::max(); + + builder.putLong(0, minInt64); + builder.putLong(1, maxInt64); + builder.putLong(2, 1125899906842623LL); + builder.putLong(3, -1125899906842623LL); + + auto map = builder.build(); + + EXPECT_EQ(map.count(), 4); + EXPECT_EQ(map.getLong(0), minInt64); + EXPECT_EQ(map.getLong(1), maxInt64); + EXPECT_EQ(map.getLong(2), 1125899906842623LL); + EXPECT_EQ(map.getLong(3), -1125899906842623LL); +} + TEST(MapBufferTest, testMapBufferExtension) { // 26 = 2 buckets: 2*10 + 6 sizeof(header) int initialSize = 26; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.cpp index 9a8a36e7a7a3ae..001df23907f2ef 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.cpp @@ -68,10 +68,12 @@ bool MountingCoordinator::waitForTransaction( void MountingCoordinator::updateBaseRevision( const ShadowTreeRevision& baseRevision) const { + std::scoped_lock lock(mutex_); baseRevision_ = baseRevision; } void MountingCoordinator::resetLatestRevision() const { + std::scoped_lock lock(mutex_); lastRevision_.reset(); } @@ -106,6 +108,8 @@ std::optional MountingCoordinator::pullTransaction() mountingOverrideDelegate->shouldOverridePullTransaction(); if (shouldOverridePullTransaction) { + SystraceSection section2("MountingCoordinator::overridePullTransaction"); + auto mutations = ShadowViewMutation::List{}; auto telemetry = TransactionTelemetry{}; @@ -128,6 +132,9 @@ std::optional MountingCoordinator::pullTransaction() #ifdef RN_SHADOW_TREE_INTROSPECTION if (transaction.has_value()) { + SystraceSection section2( + "MountingCoordinator::verifyMutationsForDebugging"); + // We have something to validate. auto mutations = transaction->getMutations(); @@ -179,6 +186,7 @@ std::optional MountingCoordinator::pullTransaction() } bool MountingCoordinator::hasPendingTransactions() const { + std::scoped_lock lock(mutex_); return lastRevision_.has_value(); } @@ -186,7 +194,8 @@ const TelemetryController& MountingCoordinator::getTelemetryController() const { return telemetryController_; } -const ShadowTreeRevision& MountingCoordinator::getBaseRevision() const { +ShadowTreeRevision MountingCoordinator::getBaseRevision() const { + std::scoped_lock lock(mutex_); return baseRevision_; } diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h index e733fe5924068f..306e3faaa63a88 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h @@ -79,7 +79,7 @@ class MountingCoordinator final { const TelemetryController& getTelemetryController() const; - const ShadowTreeRevision& getBaseRevision() const; + ShadowTreeRevision getBaseRevision() const; /* * Methods from this section are meant to be used by @@ -112,6 +112,8 @@ class MountingCoordinator final { private: const SurfaceId surfaceId_; + // Protects access to `baseRevision_`, `lastRevision_` and + // `mountingOverrideDelegate_`. mutable std::mutex mutex_; mutable ShadowTreeRevision baseRevision_; mutable std::optional lastRevision_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/ErrorUtils.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/ErrorUtils.h index a73bb52ce3c347..c15de49aac6b82 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/ErrorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/ErrorUtils.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include namespace facebook::react { diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.cpp index 79be477d2c240a..4f2cf5d8646d20 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.cpp @@ -58,10 +58,6 @@ bool RuntimeScheduler::getShouldYield() const noexcept { return runtimeSchedulerImpl_->getShouldYield(); } -bool RuntimeScheduler::getIsSynchronous() const noexcept { - return runtimeSchedulerImpl_->getIsSynchronous(); -} - void RuntimeScheduler::cancelTask(Task& task) noexcept { return runtimeSchedulerImpl_->cancelTask(task); } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h index 26c2c336202df2..115bc3ec3d9930 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h @@ -30,7 +30,6 @@ class RuntimeSchedulerBase { RawCallback&& callback) noexcept = 0; virtual void cancelTask(Task& task) noexcept = 0; virtual bool getShouldYield() const noexcept = 0; - virtual bool getIsSynchronous() const noexcept = 0; virtual SchedulerPriority getCurrentPriorityLevel() const noexcept = 0; virtual RuntimeSchedulerTimePoint now() const noexcept = 0; virtual void callExpiredTasks(jsi::Runtime& runtime) = 0; @@ -100,14 +99,6 @@ class RuntimeScheduler final : RuntimeSchedulerBase { */ bool getShouldYield() const noexcept override; - /* - * Return value informs if the current task is executed inside synchronous - * block. - * - * Can be called from any thread. - */ - bool getIsSynchronous() const noexcept override; - /* * Returns value of currently executed task. Designed to be called from React. * diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp index 8bcb0420df9779..22312c98ca7f9a 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp @@ -61,10 +61,6 @@ RuntimeSchedulerBinding::RuntimeSchedulerBinding( std::shared_ptr runtimeScheduler) : runtimeScheduler_(std::move(runtimeScheduler)) {} -bool RuntimeSchedulerBinding::getIsSynchronous() const { - return runtimeScheduler_->getIsSynchronous(); -} - jsi::Value RuntimeSchedulerBinding::get( jsi::Runtime& runtime, const jsi::PropNameID& name) { diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h index 5058cb40252b60..ea892b043bc4b3 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h @@ -42,8 +42,6 @@ class RuntimeSchedulerBinding : public jsi::HostObject { */ jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& name) override; - bool getIsSynchronous() const; - private: std::shared_ptr runtimeScheduler_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.cpp index 081118f2c31ed5..10bd57157f747e 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.cpp @@ -19,14 +19,14 @@ RuntimeSchedulerCallInvoker::RuntimeSchedulerCallInvoker( void RuntimeSchedulerCallInvoker::invokeAsync(CallFunc&& func) noexcept { if (auto runtimeScheduler = runtimeScheduler_.lock()) { runtimeScheduler->scheduleWork( - [func = std::move(func)](jsi::Runtime&) { func(); }); + [func = std::move(func)](jsi::Runtime& rt) { func(rt); }); } } void RuntimeSchedulerCallInvoker::invokeSync(CallFunc&& func) { if (auto runtimeScheduler = runtimeScheduler_.lock()) { runtimeScheduler->executeNowOnTheSameThread( - [func = std::move(func)](jsi::Runtime&) { func(); }); + [func = std::move(func)](jsi::Runtime& rt) { func(rt); }); } } @@ -35,7 +35,7 @@ void RuntimeSchedulerCallInvoker::invokeAsync( CallFunc&& func) noexcept { if (auto runtimeScheduler = runtimeScheduler_.lock()) { runtimeScheduler->scheduleTask( - priority, [func = std::move(func)](jsi::Runtime&) { func(); }); + priority, [func = std::move(func)](jsi::Runtime& rt) { func(rt); }); } } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.cpp index 812eac2456d8c0..325de9f44c2700 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.cpp @@ -79,10 +79,6 @@ bool RuntimeScheduler_Legacy::getShouldYield() const noexcept { return runtimeAccessRequests_ > 0; } -bool RuntimeScheduler_Legacy::getIsSynchronous() const noexcept { - return isSynchronous_; -} - void RuntimeScheduler_Legacy::cancelTask(Task& task) noexcept { task.callback.reset(); } @@ -108,9 +104,7 @@ void RuntimeScheduler_Legacy::executeNowOnTheSameThread( "RuntimeScheduler::executeNowOnTheSameThread callback"); runtimeAccessRequests_ -= 1; - isSynchronous_ = true; callback(runtime); - isSynchronous_ = false; }); // Resume work loop if needed. In synchronous mode diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h index d4ad98d59a1f43..fc436b5d2283a6 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h @@ -77,14 +77,6 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { */ bool getShouldYield() const noexcept override; - /* - * Return value informs if the current task is executed inside synchronous - * block. - * - * Can be called from any thread. - */ - bool getIsSynchronous() const noexcept override; - /* * Returns value of currently executed task. Designed to be called from React. * diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp index 4a30a2ff5c4034..76011d0a272fb6 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.cpp @@ -11,45 +11,12 @@ #include #include #include +#include #include #include "ErrorUtils.h" namespace facebook::react { -namespace { -/** - * This is partially equivalent to the "Perform a microtask checkpoint" step in - * the Web event loop. See - * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint. - * - * Iterates on \c drainMicrotasks until it completes or hits the retries bound. - */ -void executeMicrotasks(jsi::Runtime& runtime) { - SystraceSection s("RuntimeScheduler::executeMicrotasks"); - - uint8_t retries = 0; - // A heuristic number to guard infinite or absurd numbers of retries. - const static unsigned int kRetriesBound = 255; - - while (retries < kRetriesBound) { - try { - // The default behavior of \c drainMicrotasks is unbounded execution. - // We may want to make it bounded in the future. - if (runtime.drainMicrotasks()) { - break; - } - } catch (jsi::JSError& error) { - handleJSError(runtime, error, true); - } - retries++; - } - - if (retries == kRetriesBound) { - throw std::runtime_error("Hits microtasks retries bound."); - } -} -} // namespace - #pragma mark - Public RuntimeScheduler_Modern::RuntimeScheduler_Modern( @@ -107,10 +74,6 @@ bool RuntimeScheduler_Modern::getShouldYield() const noexcept { (!taskQueue_.empty() && taskQueue_.top() != currentTask_); } -bool RuntimeScheduler_Modern::getIsSynchronous() const noexcept { - return isSynchronous_; -} - void RuntimeScheduler_Modern::cancelTask(Task& task) noexcept { task.callback.reset(); } @@ -138,8 +101,6 @@ void RuntimeScheduler_Modern::executeNowOnTheSameThread( syncTaskRequests_--; - isSynchronous_ = true; - auto currentTime = now_(); auto priority = SchedulerPriority::ImmediatePriority; auto expirationTime = @@ -148,8 +109,6 @@ void RuntimeScheduler_Modern::executeNowOnTheSameThread( priority, std::move(callback), expirationTime); executeTask(runtime, task, currentTime); - - isSynchronous_ = false; }); bool shouldScheduleWorkLoop = false; @@ -298,7 +257,7 @@ void RuntimeScheduler_Modern::executeTask( if (ReactNativeFeatureFlags::enableMicrotasks()) { // "Perform a microtask checkpoint" step. - executeMicrotasks(runtime); + performMicrotaskCheckpoint(runtime); } if (ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop()) { @@ -339,4 +298,44 @@ void RuntimeScheduler_Modern::executeMacrotask( } } +/** + * This is partially equivalent to the "Perform a microtask checkpoint" step in + * the Web event loop. See + * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint. + * + * Iterates on \c drainMicrotasks until it completes or hits the retries bound. + */ +void RuntimeScheduler_Modern::performMicrotaskCheckpoint( + jsi::Runtime& runtime) { + SystraceSection s("RuntimeScheduler::performMicrotaskCheckpoint"); + + if (performingMicrotaskCheckpoint_) { + return; + } + + performingMicrotaskCheckpoint_ = true; + OnScopeExit restoreFlag([&]() { performingMicrotaskCheckpoint_ = false; }); + + uint8_t retries = 0; + // A heuristic number to guard infinite or absurd numbers of retries. + const static unsigned int kRetriesBound = 255; + + while (retries < kRetriesBound) { + try { + // The default behavior of \c drainMicrotasks is unbounded execution. + // We may want to make it bounded in the future. + if (runtime.drainMicrotasks()) { + break; + } + } catch (jsi::JSError& error) { + handleJSError(runtime, error, true); + } + retries++; + } + + if (retries == kRetriesBound) { + throw std::runtime_error("Hits microtasks retries bound."); + } +} + } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h index 34c8eb4cf16cbf..d31707f5217c96 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h @@ -86,14 +86,6 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { */ bool getShouldYield() const noexcept override; - /* - * Return value informs if the current task is executed inside synchronous - * block. - * - * Can be called from any thread. - */ - bool getIsSynchronous() const noexcept override; - /* * Returns value of currently executed task. Designed to be called from React. * @@ -149,8 +141,6 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { const RuntimeExecutor runtimeExecutor_; SchedulerPriority currentPriority_{SchedulerPriority::NormalPriority}; - std::atomic_bool isSynchronous_{false}; - void scheduleWorkLoop(); void startWorkLoop(jsi::Runtime& runtime, bool onlyExpired); @@ -178,6 +168,9 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { void updateRendering(); + bool performingMicrotaskCheckpoint_{false}; + void performMicrotaskCheckpoint(jsi::Runtime& runtime); + /* * Returns a time point representing the current point in time. May be called * from multiple threads. diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp index 292b62c8916990..bff617dc5adc93 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp @@ -200,13 +200,7 @@ TEST_P( return jsi::Value::undefined(); }); - // Hermes doesn't expose a C++ API to schedule microtasks, so we just access - // the API that it exposes to JS. - auto global = runtime_->global(); - auto enqueueJobFn = global.getPropertyAsObject(*runtime_, "HermesInternal") - .getPropertyAsFunction(*runtime_, "enqueueJob"); - - enqueueJobFn.call(*runtime_, std::move(microtaskCallback)); + runtime_->queueMicrotask(microtaskCallback); return jsi::Value::undefined(); }); @@ -783,11 +777,9 @@ TEST_P(RuntimeSchedulerTest, basicSameThreadExecution) { bool didRunSynchronousTask = false; std::thread t1([this, &didRunSynchronousTask]() { runtimeScheduler_->executeNowOnTheSameThread( - [this, &didRunSynchronousTask](jsi::Runtime& /*rt*/) { - EXPECT_TRUE(runtimeScheduler_->getIsSynchronous()); + [&didRunSynchronousTask](jsi::Runtime& /*rt*/) { didRunSynchronousTask = true; }); - EXPECT_FALSE(runtimeScheduler_->getIsSynchronous()); }); auto hasTask = stubQueue_->waitForTask(); diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/AsynchronousEventBeat.h b/packages/react-native/ReactCommon/react/renderer/scheduler/AsynchronousEventBeat.h index 3c8dfa068b91d0..af877980b00dae 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/AsynchronousEventBeat.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/AsynchronousEventBeat.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/InspectorData.h b/packages/react-native/ReactCommon/react/renderer/scheduler/InspectorData.h index 1a0b1523adf917..d420c0329ebb9f 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/InspectorData.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/InspectorData.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include namespace facebook::react { diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.cpp index 6d99a35008fca5..b3e49dfed3a8aa 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.cpp @@ -29,6 +29,13 @@ TextMeasurement TextLayoutManager::measure( return TextMeasurement{{0, 0}, attachments}; } +TextMeasurement TextLayoutManager::measureCachedSpannableById( + int64_t /*cacheId*/, + const ParagraphAttributes& /*paragraphAttributes*/, + LayoutConstraints /*layoutConstraints*/) const { + return {}; +} + LinesMeasurements TextLayoutManager::measureLines( AttributedString attributedString, ParagraphAttributes paragraphAttributes, diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.h index 63903786a91b3d..0d323241190fc6 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/TextLayoutManager.h @@ -42,6 +42,15 @@ class TextLayoutManager { LayoutConstraints layoutConstraints, std::shared_ptr) const; + /** + * Measures an AttributedString on the platform, as identified by some + * opaque cache ID. + */ + virtual TextMeasurement measureCachedSpannableById( + int64_t cacheId, + const ParagraphAttributes& paragraphAttributes, + LayoutConstraints layoutConstraints) const; + /* * Measures lines of `attributedString` using native text rendering * infrastructure. diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm index b76bb2fba04117..74f5b65df1338d 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm @@ -285,7 +285,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex } // Special - if (textAttributes.isHighlighted) { + if (textAttributes.isHighlighted.value_or(false)) { attributes[RCTAttributedStringIsHighlightedAttributeName] = @YES; } diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.h index b0d906ca10cea8..41809ce12ae31d 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.h @@ -43,7 +43,8 @@ using RCTTextLayoutFragmentEnumerationBlock = - (void)drawAttributedString:(facebook::react::AttributedString)attributedString paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes frame:(CGRect)frame - textStorage:(NSTextStorage *_Nullable)textStorage; + textStorage:(NSTextStorage *_Nullable)textStorage + drawHighlightPath:(void (^_Nullable)(UIBezierPath *highlightPath))block; - (facebook::react::LinesMeasurements)getLinesForAttributedString:(facebook::react::AttributedString)attributedString paragraphAttributes: diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm index f7d17f52dc37bb..1b917150074a32 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm @@ -76,6 +76,7 @@ - (void)drawAttributedString:(AttributedString)attributedString paragraphAttributes:(ParagraphAttributes)paragraphAttributes frame:(CGRect)frame textStorage:(NSTextStorage *_Nullable)textStorage + drawHighlightPath:(void (^_Nullable)(UIBezierPath *highlightPath))block { BOOL createdStorageForFrame = NO; @@ -118,6 +119,38 @@ - (void)drawAttributedString:(AttributedString)attributedString #if TARGET_OS_MACCATALYST CGContextRestoreGState(context); #endif + + if (block != nil) { + __block UIBezierPath *highlightPath = nil; + NSRange characterRange = [layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL]; + + [textStorage + enumerateAttribute:RCTAttributedStringIsHighlightedAttributeName + inRange:characterRange + options:0 + usingBlock:^(NSNumber *value, NSRange range, __unused BOOL *stop) { + if (!value.boolValue) { + return; + } + + [layoutManager + enumerateEnclosingRectsForGlyphRange:range + withinSelectedGlyphRange:range + inTextContainer:textContainer + usingBlock:^(CGRect enclosingRect, __unused BOOL *anotherStop) { + UIBezierPath *path = [UIBezierPath + bezierPathWithRoundedRect:CGRectInset(enclosingRect, -2, -2) + cornerRadius:2]; + if (highlightPath) { + [highlightPath appendPath:path]; + } else { + highlightPath = path; + } + }]; + }]; + + block(highlightPath); + } } - (LinesMeasurements)getLinesForAttributedString:(AttributedString)attributedString diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.cpp b/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.cpp deleted file mode 100644 index 28c6128343eed2..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "Timeline.h" - -#include - -namespace facebook::react { - -Timeline::Timeline(const ShadowTree& shadowTree) : shadowTree_(&shadowTree) { - record(shadowTree.getCurrentRevision().rootShadowNode); -}; - -#pragma mark - Public - -SurfaceId Timeline::getSurfaceId() const noexcept { - return shadowTree_->getSurfaceId(); -} - -void Timeline::pause() const noexcept { - std::scoped_lock lock(mutex_); - assert(!paused_ && ""); - paused_ = true; -} - -void Timeline::resume() const noexcept { - std::scoped_lock lock(mutex_); - - if (!snapshots_.empty()) { - rewind(snapshots_.at(snapshots_.size() - 1)); - } - - assert(paused_ && ""); - paused_ = false; -} - -bool Timeline::isPaused() const noexcept { - std::scoped_lock lock(mutex_); - return paused_; -} - -TimelineFrame::List Timeline::getFrames() const noexcept { - std::scoped_lock lock(mutex_); - - auto frames = TimelineFrame::List{}; - frames.reserve(snapshots_.size()); - for (const auto& snapshot : snapshots_) { - frames.push_back(snapshot.getFrame()); - } - return frames; -} - -TimelineFrame Timeline::getCurrentFrame() const noexcept { - assert(snapshots_.size() > currentSnapshotIndex_); - return snapshots_.at(currentSnapshotIndex_).getFrame(); -} - -void Timeline::rewind(const TimelineFrame& frame) const noexcept { - std::scoped_lock lock(mutex_); - rewind(snapshots_.at(frame.getIndex())); -} - -RootShadowNode::Unshared Timeline::shadowTreeWillCommit( - const ShadowTree& /*shadowTree*/, - const RootShadowNode::Shared& /*oldRootShadowNode*/, - const RootShadowNode::Unshared& newRootShadowNode) const noexcept { - std::scoped_lock lock(mutex_); - - if (rewinding_) { - return newRootShadowNode; - } - - record(newRootShadowNode); - - if (paused_) { - return nullptr; - } - - return newRootShadowNode; -} - -#pragma mark - Private & Internal - -void Timeline::record( - const RootShadowNode::Shared& rootShadowNode) const noexcept { - auto index = (int)snapshots_.size(); - snapshots_.push_back(TimelineSnapshot{rootShadowNode, index}); - - if (!paused_) { - currentSnapshotIndex_ = index; - } -} - -void Timeline::rewind(const TimelineSnapshot& snapshot) const noexcept { - std::scoped_lock lock(mutex_); - - currentSnapshotIndex_ = snapshot.getFrame().getIndex(); - - assert(!rewinding_ && ""); - rewinding_ = true; - - auto rootShadowNode = snapshot.getRootShadowNode(); - - shadowTree_->commit( - [&](const RootShadowNode& /*oldRootShadowNode*/) - -> RootShadowNode::Unshared { - return std::static_pointer_cast( - rootShadowNode->ShadowNode::clone({})); - }, - {}); - - assert(rewinding_ && ""); - rewinding_ = false; -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.h b/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.h deleted file mode 100644 index 523f66d4aa0649..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/Timeline.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -#include -#include -#include - -namespace facebook::react { - -class UIManager; - -class Timeline final { - friend class TimelineHandler; - friend class TimelineController; - - public: - Timeline(const ShadowTree& shadowTree); - - private: -#pragma mark - Private methods to be used by `TimelineHandler`. - - void pause() const noexcept; - void resume() const noexcept; - bool isPaused() const noexcept; - TimelineFrame::List getFrames() const noexcept; - TimelineFrame getCurrentFrame() const noexcept; - void rewind(const TimelineFrame& frame) const noexcept; - SurfaceId getSurfaceId() const noexcept; - -#pragma mark - Private methods to be used by `TimelineController`. - - RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode) const noexcept; - -#pragma mark - Private & Internal - - void record(const RootShadowNode::Shared& rootShadowNode) const noexcept; - void rewind(const TimelineSnapshot& snapshot) const noexcept; - - mutable std::recursive_mutex mutex_; - mutable const ShadowTree* shadowTree_{nullptr}; - mutable int currentSnapshotIndex_{0}; - mutable TimelineSnapshot::List snapshots_{}; - mutable bool paused_{false}; - mutable bool rewinding_{false}; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.cpp b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.cpp deleted file mode 100644 index 3994e99edf3bd7..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TimelineController.h" - -#include -#include - -namespace facebook::react { - -TimelineHandler TimelineController::enable(SurfaceId surfaceId) const { - assert(uiManager_); - - const ShadowTree* shadowTreePtr = nullptr; - uiManager_->getShadowTreeRegistry().visit( - surfaceId, - [&](const ShadowTree& shadowTree) { shadowTreePtr = &shadowTree; }); - - assert(shadowTreePtr); - - { - std::unique_lock lock(timelinesMutex_); - - auto timeline = std::make_unique(*shadowTreePtr); - auto handler = TimelineHandler{*timeline}; - timelines_.emplace(surfaceId, std::move(timeline)); - return handler; - } -} - -void TimelineController::disable(TimelineHandler&& handler) const { - std::unique_lock lock(timelinesMutex_); - - auto iterator = timelines_.find(handler.getSurfaceId()); - assert(iterator != timelines_.end()); - timelines_.erase(iterator); - handler.release(); -} - -void TimelineController::commitHookWasRegistered( - const UIManager& uiManager) noexcept { - uiManager_ = &uiManager; -} - -void TimelineController::commitHookWasUnregistered( - const UIManager& /*uiManager*/) noexcept { - uiManager_ = nullptr; -} - -RootShadowNode::Unshared TimelineController::shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode) noexcept { - std::shared_lock lock(timelinesMutex_); - - assert(uiManager_ && "`uiManager_` must not be `nullptr`."); - - lastUpdatedSurface_ = shadowTree.getSurfaceId(); - - auto iterator = timelines_.find(shadowTree.getSurfaceId()); - if (iterator == timelines_.end()) { - return newRootShadowNode; - } - - auto& timeline = *iterator->second; - return timeline.shadowTreeWillCommit( - shadowTree, oldRootShadowNode, newRootShadowNode); -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.h b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.h deleted file mode 100644 index a4f54eadb2621f..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineController.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace facebook::react { - -/* - * Provides tools for introspecting the series of commits and associated - * side-effects, allowing to "rewind" UI to any particular commit from the past. - */ -class TimelineController final : public UIManagerCommitHook { - public: - using Shared = std::shared_ptr; - - /* - * Creates a `TimelineHandler` associated with given `SurfaceId` and starts - * the introspection process. - */ - TimelineHandler enable(SurfaceId surfaceId) const; - - /* - * Consumes and destroys a `TimelineHandler` instance triggering the - * destruction of all associated resources and stopping the introspection - * process. - */ - void disable(TimelineHandler&& handler) const; - - /* - * TO BE DELETED. - */ - SurfaceId lastUpdatedSurface() const { - return lastUpdatedSurface_; - } - -#pragma mark - UIManagerCommitHook - - RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode) noexcept override; - - void commitHookWasRegistered(const UIManager& uiManager) noexcept override; - - void commitHookWasUnregistered(const UIManager& uiManager) noexcept override; - - private: - /* - * Protects all the data members. - */ - mutable std::shared_mutex timelinesMutex_; - - /* - * Owning collection of all running `Timeline` instances. - */ - mutable std::unordered_map> timelines_; - - mutable const UIManager* uiManager_; - mutable SurfaceId lastUpdatedSurface_; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.cpp b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.cpp deleted file mode 100644 index d1aa4ac2e11eeb..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TimelineFrame.h" - -namespace facebook::react { - -TimelineFrame::TimelineFrame(int index, TelemetryTimePoint timePoint) noexcept - : index_(index), timePoint_(timePoint) {} - -int TimelineFrame::getIndex() const noexcept { - return index_; -} - -TelemetryTimePoint TimelineFrame::getTimePoint() const noexcept { - return timePoint_; -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.h b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.h deleted file mode 100644 index f36b0bd60e9b5e..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineFrame.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -/* - * Represents a reference to a commit from the past. - * The reference can be safely used to address a particular commit from non-core - * code. - */ -class TimelineFrame final { - friend class TimelineSnapshot; - - /* - * Constructor is private and must be called by `TimelineSnapshot` only. - */ - TimelineFrame(int index, TelemetryTimePoint timePoint) noexcept; - - public: - using List = std::vector; - - TimelineFrame() = delete; - TimelineFrame(const TimelineFrame& timelineFrame) noexcept = default; - TimelineFrame& operator=(const TimelineFrame& other) noexcept = default; - - int getIndex() const noexcept; - TelemetryTimePoint getTimePoint() const noexcept; - - private: - int index_; - TelemetryTimePoint timePoint_; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.cpp b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.cpp deleted file mode 100644 index 2bc96b636c8153..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TimelineHandler.h" - -#include - -#include - -namespace facebook::react { - -TimelineHandler::TimelineHandler(const Timeline& timeline) noexcept - : timeline_(&timeline) {} - -TimelineHandler::TimelineHandler(TimelineHandler&& other) noexcept { - this->operator=(std::move(other)); -} - -TimelineHandler::~TimelineHandler() noexcept { - if (timeline_ != nullptr) { - // Improper deallocation indicates a severe error in application logic: - abort(); - } -} - -TimelineHandler& TimelineHandler::operator=(TimelineHandler&& other) noexcept { - assert(other.timeline_ && "Moving from an empty `TimelineHandler`."); - timeline_ = other.timeline_; - other.timeline_ = nullptr; - return *this; -} - -#pragma mark - Public - -void TimelineHandler::pause() const noexcept { - ensureNotEmpty(); - timeline_->pause(); -} - -void TimelineHandler::resume() const noexcept { - ensureNotEmpty(); - timeline_->resume(); -} - -bool TimelineHandler::isPaused() const noexcept { - ensureNotEmpty(); - return timeline_->isPaused(); -} - -TimelineFrame TimelineHandler::getCurrentFrame() const noexcept { - ensureNotEmpty(); - return timeline_->getCurrentFrame(); -} - -TimelineFrame::List TimelineHandler::getFrames() const noexcept { - ensureNotEmpty(); - return timeline_->getFrames(); -} - -void TimelineHandler::rewind(const TimelineFrame& frame) const noexcept { - ensureNotEmpty(); - return timeline_->rewind(frame); -} - -void TimelineHandler::seek(int delta) const noexcept { - ensureNotEmpty(); - auto frames = timeline_->getFrames(); - auto currentFrame = timeline_->getCurrentFrame(); - auto seekFrameIndex = currentFrame.getIndex() + delta; - seekFrameIndex = - std::min((int)frames.size() - 1, std::max(0, seekFrameIndex)); - timeline_->rewind(frames.at(seekFrameIndex)); -} - -#pragma mark - Private - -SurfaceId TimelineHandler::getSurfaceId() const noexcept { - return timeline_->getSurfaceId(); -} - -void TimelineHandler::release() noexcept { - timeline_ = nullptr; -} - -void TimelineHandler::ensureNotEmpty() const noexcept { - if (timeline_ == nullptr) { - abort(); - } -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.h b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.h deleted file mode 100644 index f9cb7eb90e51f5..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineHandler.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -class Timeline; - -class TimelineHandler final { - public: - ~TimelineHandler() noexcept; - - /* - * Movable, not copyable. - */ - TimelineHandler(TimelineHandler&& other) noexcept; - TimelineHandler(const TimelineHandler& timelineHandler) = delete; - TimelineHandler& operator=(TimelineHandler&& other) noexcept; - TimelineHandler& operator=(const TimelineHandler& other) = delete; - - /* - * Stops (or resumes) mounting of new commits. - * A surface has to be paused to allow rewinding the UI to some past commit. - */ - void pause() const noexcept; - void resume() const noexcept; - bool isPaused() const noexcept; - - /* - * Provides access to recorded frames. - */ - TimelineFrame::List getFrames() const noexcept; - TimelineFrame getCurrentFrame() const noexcept; - - /* - * Rewinds the UI to a given frame. - */ - void rewind(const TimelineFrame& frame) const noexcept; - - /* - * Rewinds the UI for a given number of frames back or forward. - */ - void seek(int delta) const noexcept; - - private: - friend class TimelineController; - - /* - * Can only be constructed by `TimelineController`. - */ - TimelineHandler(const Timeline& timeline) noexcept; - - /* - * Must be called before deallocation to make it not crash. - * Must be only called by `TimelineController`. - */ - void release() noexcept; - - /* - * Returns a `SurfaceId` of the assigned Surface. - */ - SurfaceId getSurfaceId() const noexcept; - - void ensureNotEmpty() const noexcept; - - const Timeline* timeline_{}; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.cpp b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.cpp deleted file mode 100644 index 1500caebe92aa5..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TimelineSnapshot.h" - -#include - -#include - -namespace facebook::react { - -TimelineSnapshot::TimelineSnapshot( - RootShadowNode::Shared rootShadowNode, - int index) noexcept - : rootShadowNode_(std::move(rootShadowNode)), - frame_(TimelineFrame{index, telemetryTimePointNow()}) {} - -RootShadowNode::Shared TimelineSnapshot::getRootShadowNode() const noexcept { - return rootShadowNode_; -} - -TimelineFrame TimelineSnapshot::getFrame() const noexcept { - return frame_; -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.h b/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.h deleted file mode 100644 index cbada734a83460..00000000000000 --- a/packages/react-native/ReactCommon/react/renderer/timeline/TimelineSnapshot.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -/* - * Represents a reference to a commit from the past used by `Timeline`. - */ -class TimelineSnapshot final { - public: - using List = std::vector; - - TimelineSnapshot(RootShadowNode::Shared rootShadowNode, int index) noexcept; - - TimelineFrame getFrame() const noexcept; - RootShadowNode::Shared getRootShadowNode() const noexcept; - - private: - RootShadowNode::Shared rootShadowNode_; - TimelineFrame frame_; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/CMakeLists.txt b/packages/react-native/ReactCommon/react/renderer/uimanager/CMakeLists.txt index a7583450cadfb7..badeb64afcfdf0 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/CMakeLists.txt @@ -12,6 +12,7 @@ add_compile_options( -std=c++20 -Wall -Wpedantic + -Wno-unused-local-typedef -DLOG_TAG=\"Fabric\") file(GLOB react_render_uimanager_SRC CONFIGURE_DEPENDS *.cpp) @@ -24,6 +25,7 @@ target_link_libraries(react_render_uimanager folly_runtime jsi react_debug + react_featureflags react_render_componentregistry react_render_core react_render_debug diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp index 5cf3e5eeb6ce39..0ad24461223a56 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -129,7 +130,9 @@ std::shared_ptr UIManager::cloneNode( // was previously in `nativeProps_DEPRECATED`. family.nativeProps_DEPRECATED = std::make_unique(mergeDynamicProps( - *family.nativeProps_DEPRECATED, (folly::dynamic)rawProps)); + *family.nativeProps_DEPRECATED, + (folly::dynamic)rawProps, + NullValueStrategy::Ignore)); props = componentDescriptor.cloneProps( propsParserContext, @@ -513,7 +516,9 @@ void UIManager::setNativeProps_DEPRECATED( // previously in `nativeProps_DEPRECATED`. family.nativeProps_DEPRECATED = std::make_unique(mergeDynamicProps( - *family.nativeProps_DEPRECATED, (folly::dynamic)rawProps)); + *family.nativeProps_DEPRECATED, + (folly::dynamic)rawProps, + NullValueStrategy::Override)); } else { family.nativeProps_DEPRECATED = std::make_unique((folly::dynamic)rawProps); diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.cpp index 03633a8a48566f..212184bc023f19 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.cpp @@ -158,7 +158,9 @@ void UIManagerBinding::dispatchEventToJS( : jsi::Value::null(); if (instanceHandle.isNull()) { - LOG(WARNING) << "instanceHandle is null, event will be dropped"; + // Do not log all missing instanceHandles to avoid log spam + LOG_EVERY_N(INFO, 10) << "instanceHandle is null, event of type " << type + << " will be dropped"; } currentEventPriority_ = priority; @@ -498,18 +500,7 @@ jsi::Value UIManagerBinding::get( RuntimeSchedulerBinding::getBinding(runtime); auto surfaceId = surfaceIdFromValue(runtime, arguments[0]); - if (!uiManager->backgroundExecutor_ || - (runtimeSchedulerBinding && - runtimeSchedulerBinding->getIsSynchronous())) { - auto shadowNodeList = - shadowNodeListFromValue(runtime, arguments[1]); - uiManager->completeSurface( - surfaceId, - shadowNodeList, - {.enableStateReconciliation = true, - .mountSynchronously = false, - .shouldYield = nullptr}); - } else { + if (uiManager->backgroundExecutor_) { auto weakShadowNodeList = weakShadowNodeListFromValue(runtime, arguments[1]); static std::atomic_uint_fast8_t completeRootEventCounter{0}; @@ -540,6 +531,15 @@ jsi::Value UIManagerBinding::get( /* .shouldYield = */ shouldYield}); } }); + } else { + auto shadowNodeList = + shadowNodeListFromValue(runtime, arguments[1]); + uiManager->completeSurface( + surfaceId, + shadowNodeList, + {.enableStateReconciliation = true, + .mountSynchronously = false, + .shouldYield = nullptr}); } return jsi::Value::undefined(); diff --git a/packages/react-native/ReactCommon/react/runtime/.clang-tidy b/packages/react-native/ReactCommon/react/runtime/.clang-tidy deleted file mode 100644 index 72f0e8f7e89333..00000000000000 --- a/packages/react-native/ReactCommon/react/runtime/.clang-tidy +++ /dev/null @@ -1,17 +0,0 @@ ---- -InheritParentConfig: true -Checks: ' --cert-err60-cpp, --cppcoreguidelines-pro-bounds-pointer-arithmetic, --cppcoreguidelines-special-member-functions, --fuchsia-default-arguments-calls, --google-readability-casting, --google-runtime-references, --hicpp-special-member-functions, --llvm-header-guard, --misc-non-private-member-variables-in-classes, --misc-unused-parameters, --modernize-use-trailing-return-type, --performance-unnecessary-value-param, -' -... diff --git a/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.cpp b/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.cpp index 33b151a1e1fd5f..20519e6a3b4c88 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.cpp +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.cpp @@ -15,12 +15,12 @@ BridgelessJSCallInvoker::BridgelessJSCallInvoker( RuntimeExecutor runtimeExecutor) : runtimeExecutor_(std::move(runtimeExecutor)) {} -void BridgelessJSCallInvoker::invokeAsync( - std::function&& func) noexcept { - runtimeExecutor_([func = std::move(func)](jsi::Runtime& runtime) { func(); }); +void BridgelessJSCallInvoker::invokeAsync(CallFunc&& func) noexcept { + runtimeExecutor_( + [func = std::move(func)](jsi::Runtime& runtime) { func(runtime); }); } -void BridgelessJSCallInvoker::invokeSync(std::function&& func) { +void BridgelessJSCallInvoker::invokeSync(CallFunc&& /*func*/) { // TODO: Implement this method. The TurboModule infra doesn't call invokeSync. throw std::runtime_error( "Synchronous native -> JS calls are currently not supported."); diff --git a/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.h b/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.h index bfab788da2fa50..a411c5e8a03aca 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.h +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessJSCallInvoker.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include @@ -18,8 +20,8 @@ namespace facebook::react { class BridgelessJSCallInvoker : public CallInvoker { public: explicit BridgelessJSCallInvoker(RuntimeExecutor runtimeExecutor); - void invokeAsync(std::function&& func) noexcept override; - void invokeSync(std::function&& func) override; + void invokeAsync(CallFunc&& func) noexcept override; + void invokeSync(CallFunc&& func) override; private: RuntimeExecutor runtimeExecutor_; diff --git a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.cpp b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.cpp index e5f3e6813dc923..f81cba0e9e1356 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.cpp +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.cpp @@ -15,13 +15,13 @@ BridgelessNativeMethodCallInvoker::BridgelessNativeMethodCallInvoker( void BridgelessNativeMethodCallInvoker::invokeAsync( const std::string& methodName, - std::function&& func) noexcept { + NativeMethodCallFunc&& func) noexcept { messageQueueThread_->runOnQueue(std::move(func)); } void BridgelessNativeMethodCallInvoker::invokeSync( const std::string& methodName, - std::function&& func) { + NativeMethodCallFunc&& func) { messageQueueThread_->runOnQueueSync(std::move(func)); } diff --git a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h index 79f922976e18ff..60509b098678e4 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include @@ -18,8 +20,8 @@ class BridgelessNativeMethodCallInvoker : public NativeMethodCallInvoker { std::shared_ptr messageQueueThread); void invokeAsync( const std::string& methodName, - std::function&& func) noexcept override; - void invokeSync(const std::string& methodName, std::function&& func) + NativeMethodCallFunc&& func) noexcept override; + void invokeSync(const std::string& methodName, NativeMethodCallFunc&& func) override; private: diff --git a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h index 99a6a5352cfc85..17d3b3aff16ca6 100644 --- a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h +++ b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.cpp b/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.cpp index 832d21e40c7e9f..ed5b97fa432f5d 100644 --- a/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.cpp +++ b/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.cpp @@ -18,16 +18,12 @@ JSIRuntimeHolder::JSIRuntimeHolder(std::unique_ptr runtime) assert(runtime_ != nullptr); } -std::unique_ptr -JSIRuntimeHolder::createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) { - (void)executionContextDescription; - return std::make_unique( - std::move(frontendChannel), sessionState, runtime_->description()); +jsinspector_modern::RuntimeTargetDelegate& +JSRuntime::getRuntimeTargetDelegate() { + if (!runtimeTargetDelegate_) { + runtimeTargetDelegate_.emplace(getRuntime().description()); + } + return *runtimeTargetDelegate_; } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.h b/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.h index f7b17be856232c..dca9c1ac25c7b0 100644 --- a/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.h +++ b/packages/react-native/ReactCommon/react/runtime/JSRuntimeFactory.h @@ -17,11 +17,26 @@ namespace facebook::react { /** * An interface that represents an instance of a JS VM */ -class JSRuntime : public jsinspector_modern::RuntimeTargetDelegate { +class JSRuntime { public: virtual jsi::Runtime& getRuntime() noexcept = 0; virtual ~JSRuntime() = default; + + /** + * Get a reference to the \c RuntimeTargetDelegate owned (or implemented) by + * this JSRuntime. This reference must remain valid for the duration of the + * JSRuntime's lifetime. + */ + virtual jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate(); + + private: + /** + * Initialized by \c getRuntimeTargetDelegate if not overridden, and then + * never changes. + */ + std::optional + runtimeTargetDelegate_; }; /** @@ -41,13 +56,6 @@ class JSRuntimeFactory { class JSIRuntimeHolder : public JSRuntime { public: jsi::Runtime& getRuntime() noexcept override; - std::unique_ptr createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) override; explicit JSIRuntimeHolder(std::unique_ptr runtime); diff --git a/packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp b/packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp index e7a657ec1e7fe8..c95b10d7575c17 100644 --- a/packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp +++ b/packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp @@ -7,6 +7,7 @@ #include "ReactInstance.h" +#include #include #include #include @@ -15,11 +16,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -30,23 +33,20 @@ ReactInstance::ReactInstance( std::shared_ptr jsMessageQueueThread, std::shared_ptr timerManager, JsErrorHandler::JsErrorHandlingFunc jsErrorHandlingFunc, - jsinspector_modern::PageTarget* parentInspectorTarget) + jsinspector_modern::HostTarget* parentInspectorTarget) : runtime_(std::move(runtime)), jsMessageQueueThread_(jsMessageQueueThread), timerManager_(std::move(timerManager)), jsErrorHandler_(jsErrorHandlingFunc), hasFatalJsError_(std::make_shared(false)), parentInspectorTarget_(parentInspectorTarget) { - auto runtimeExecutor = [weakRuntime = std::weak_ptr(runtime_), - weakTimerManager = - std::weak_ptr(timerManager_), - weakJsMessageQueueThread = - std::weak_ptr( - jsMessageQueueThread_), - weakHasFatalJsError = - std::weak_ptr(hasFatalJsError_)]( - std::function&& - callback) { + RuntimeExecutor runtimeExecutor = [weakRuntime = std::weak_ptr(runtime_), + weakTimerManager = + std::weak_ptr(timerManager_), + weakJsMessageQueueThread = + std::weak_ptr(jsMessageQueueThread_), + weakHasFatalJsError = std::weak_ptr( + hasFatalJsError_)](auto callback) { if (std::shared_ptr sharedHasFatalJsError = weakHasFatalJsError.lock()) { if (*sharedHasFatalJsError) { @@ -85,13 +85,40 @@ ReactInstance::ReactInstance( }; if (parentInspectorTarget_) { - inspectorTarget_ = &parentInspectorTarget_->registerInstance(*this); - runtimeInspectorTarget_ = - &inspectorTarget_->registerRuntime(*runtime_, runtimeExecutor); + auto executor = parentInspectorTarget_->executorFromThis(); + + auto runtimeExecutorThatWaitsForInspectorSetup = + std::make_shared(runtimeExecutor); + + // This code can execute from any thread, so we need to make sure we set up + // the inspector logic in the right one. The callback executes immediately + // if we are already in the right thread. + executor([this, runtimeExecutor, runtimeExecutorThatWaitsForInspectorSetup]( + jsinspector_modern::HostTarget& hostTarget) { + // Callbacks scheduled through the page target executor are generally + // not guaranteed to run (e.g.: if the page target is destroyed) + // but in this case it is because the page target cannot be destroyed + // before the instance finishes its setup: + // * On iOS it's because we do the setup synchronously. + // * On Android it's because we explicitly wait for the instance + // creation task to finish before starting the destruction. + inspectorTarget_ = &hostTarget.registerInstance(*this); + runtimeInspectorTarget_ = &inspectorTarget_->registerRuntime( + runtime_->getRuntimeTargetDelegate(), runtimeExecutor); + runtimeExecutorThatWaitsForInspectorSetup->flush(); + }); + + // We decorate the runtime executor used everywhere else to wait for the + // inspector to finish its setup. + runtimeExecutor = + [runtimeExecutorThatWaitsForInspectorSetup]( + std::function&& callback) { + runtimeExecutorThatWaitsForInspectorSetup->execute( + std::move(callback)); + }; } - runtimeScheduler_ = - std::make_shared(std::move(runtimeExecutor)); + runtimeScheduler_ = std::make_shared(runtimeExecutor); auto pipedRuntimeExecutor = [runtimeScheduler = runtimeScheduler_.get()]( @@ -107,8 +134,10 @@ void ReactInstance::unregisterFromInspector() { if (inspectorTarget_) { assert(runtimeInspectorTarget_); inspectorTarget_->unregisterRuntime(*runtimeInspectorTarget_); + assert(parentInspectorTarget_); parentInspectorTarget_->unregisterInstance(*inspectorTarget_); + inspectorTarget_ = nullptr; } } diff --git a/packages/react-native/ReactCommon/react/runtime/ReactInstance.h b/packages/react-native/ReactCommon/react/runtime/ReactInstance.h index c82656c77679b9..7c5eb4dc4cb1bc 100644 --- a/packages/react-native/ReactCommon/react/runtime/ReactInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/ReactInstance.h @@ -35,7 +35,7 @@ class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate { std::shared_ptr jsMessageQueueThread, std::shared_ptr timerManager, JsErrorHandler::JsErrorHandlingFunc JsErrorHandlingFunc, - jsinspector_modern::PageTarget* parentInspectorTarget = nullptr); + jsinspector_modern::HostTarget* parentInspectorTarget = nullptr); RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept; @@ -87,7 +87,7 @@ class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate { jsinspector_modern::InstanceTarget* inspectorTarget_{nullptr}; jsinspector_modern::RuntimeTarget* runtimeInspectorTarget_{nullptr}; - jsinspector_modern::PageTarget* parentInspectorTarget_{nullptr}; + jsinspector_modern::HostTarget* parentInspectorTarget_{nullptr}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/hermes/HermesInstance.cpp b/packages/react-native/ReactCommon/react/runtime/hermes/HermesInstance.cpp index 13308c81c26704..b5ddd1eab15502 100644 --- a/packages/react-native/ReactCommon/react/runtime/hermes/HermesInstance.cpp +++ b/packages/react-native/ReactCommon/react/runtime/hermes/HermesInstance.cpp @@ -7,7 +7,7 @@ #include "HermesInstance.h" -#include +#include #include #include #include @@ -94,49 +94,25 @@ class DecoratedRuntime : public jsi::RuntimeDecorator { class HermesJSRuntime : public JSRuntime { public: - HermesJSRuntime( - std::unique_ptr runtime, - std::shared_ptr msgQueueThread) - : runtime_(std::move(runtime)), - msgQueueThread_(std::move(msgQueueThread)) {} + HermesJSRuntime(std::unique_ptr runtime) + : runtime_(std::move(runtime)) {} jsi::Runtime& getRuntime() noexcept override { return *runtime_; } - std::unique_ptr createAgentDelegate( - jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription) override { - return std::unique_ptr( - new jsinspector_modern::HermesRuntimeAgentDelegate( - frontendChannel, - sessionState, - std::move(previouslyExportedState), - executionContextDescription, - runtime_, - [msgQueueThreadWeak = std::weak_ptr(msgQueueThread_), - runtimeWeak = std::weak_ptr(runtime_)](auto fn) { - auto msgQueueThread = msgQueueThreadWeak.lock(); - if (!msgQueueThread) { - return; - } - msgQueueThread->runOnQueue([runtimeWeak, fn]() { - auto runtime = runtimeWeak.lock(); - if (!runtime) { - return; - } - fn(*runtime); - }); - })); + jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate() + override { + if (!targetDelegate_) { + targetDelegate_.emplace(runtime_); + } + return *targetDelegate_; } private: std::shared_ptr runtime_; - std::shared_ptr msgQueueThread_; + std::optional + targetDelegate_; }; std::unique_ptr HermesInstance::createJSRuntime( @@ -148,18 +124,11 @@ std::unique_ptr HermesInstance::createJSRuntime( ? reactNativeConfig->getInt64("ios_hermes:vm_experiment_flags") : 0; - int64_t heapSizeConfig = reactNativeConfig - ? reactNativeConfig->getInt64("ios_hermes:rn_heap_size_mb") - : 0; - // Default to 3GB if MobileConfigs is not available - auto heapSizeMB = heapSizeConfig > 0 - ? static_cast<::hermes::vm::gcheapsize_t>(heapSizeConfig) - : 3072; - ::hermes::vm::RuntimeConfig::Builder runtimeConfigBuilder = ::hermes::vm::RuntimeConfig::Builder() .withGCConfig(::hermes::vm::GCConfig::Builder() - .withMaxHeapSize(heapSizeMB << 20) + // Default to 3GB + .withMaxHeapSize(3072 << 20) .withName("RNBridgeless") // For the next two arguments: avoid GC before TTI // by initializing the runtime to allocate directly @@ -168,7 +137,6 @@ std::unique_ptr HermesInstance::createJSRuntime( .withAllocInYoung(false) .withRevertToYGAtTTI(true) .build()) - .withES6Proxy(false) .withEnableSampleProfiling(true) .withMicrotaskQueue(ReactNativeFeatureFlags::enableMicrotasks()) .withVMExperimentFlags(vmExperimentFlags); @@ -188,10 +156,11 @@ std::unique_ptr HermesInstance::createJSRuntime( std::move(hermesRuntime), msgQueueThread); return std::make_unique(std::move(decoratedRuntime)); } +#else + (void)msgQueueThread; #endif - return std::make_unique( - std::move(hermesRuntime), std::move(msgQueueThread)); + return std::make_unique(std::move(hermesRuntime)); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h index 6b869377a836a5..ea4492980f976f 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h @@ -52,6 +52,10 @@ typedef std::shared_ptr (^RCTHostJSEngineProv @property (nonatomic, weak, nullable) id runtimeDelegate; +@property (nonatomic, readonly) RCTSurfacePresenter *surfacePresenter; + +@property (nonatomic, readonly) RCTModuleRegistry *moduleRegistry; + - (void)start; - (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args; @@ -64,11 +68,11 @@ typedef std::shared_ptr (^RCTHostJSEngineProv - (RCTFabricSurface *)createSurfaceWithModuleName:(NSString *)moduleName initialProperties:(NSDictionary *)properties; -- (RCTSurfacePresenter *)getSurfacePresenter; +- (RCTSurfacePresenter *)getSurfacePresenter __attribute__((deprecated("Use `surfacePresenter` property instead."))); // Native module API -- (RCTModuleRegistry *)getModuleRegistry; +- (RCTModuleRegistry *)getModuleRegistry __attribute__((deprecated("Use `moduleRegistry` property instead."))); @end diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.mm b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.mm index 85602c4c8a6f8a..711f94dfac4c71 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.mm +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.mm @@ -28,9 +28,9 @@ using namespace facebook::react; -class RCTHostPageTargetDelegate : public facebook::react::jsinspector_modern::PageTargetDelegate { +class RCTHostHostTargetDelegate : public facebook::react::jsinspector_modern::HostTargetDelegate { public: - RCTHostPageTargetDelegate(RCTHost *host) : host_(host) {} + RCTHostHostTargetDelegate(RCTHost *host) : host_(host) {} void onReload(const PageReloadRequest &request) override { @@ -67,8 +67,8 @@ @implementation RCTHost { RCTModuleRegistry *_moduleRegistry; - std::unique_ptr _inspectorPageDelegate; - std::shared_ptr _inspectorTarget; + std::unique_ptr _inspectorHostDelegate; + std::shared_ptr _inspectorTarget; std::optional _inspectorPageId; } @@ -157,7 +157,7 @@ - (instancetype)initWithBundleURL:(NSURL *)bundleURL RCTRegisterReloadCommandListener(self); }); - _inspectorPageDelegate = std::make_unique(self); + _inspectorHostDelegate = std::make_unique(self); } return self; } @@ -169,7 +169,7 @@ - (void)start auto &inspectorFlags = jsinspector_modern::InspectorFlags::getInstance(); if (inspectorFlags.getEnableModernCDPRegistry() && !_inspectorPageId.has_value()) { _inspectorTarget = - facebook::react::jsinspector_modern::PageTarget::create(*_inspectorPageDelegate, [](auto callback) { + facebook::react::jsinspector_modern::HostTarget::create(*_inspectorHostDelegate, [](auto callback) { RCTExecuteOnMainQueue(^{ callback(); }); @@ -212,7 +212,7 @@ - (RCTFabricSurface *)createSurfaceWithModuleName:(NSString *)moduleName mode:(DisplayMode)displayMode initialProperties:(NSDictionary *)properties { - RCTFabricSurface *surface = [[RCTFabricSurface alloc] initWithSurfacePresenter:[self getSurfacePresenter] + RCTFabricSurface *surface = [[RCTFabricSurface alloc] initWithSurfacePresenter:self.surfacePresenter moduleName:moduleName initialProperties:properties]; surface.surfaceHandler.setDisplayMode(displayMode); @@ -235,16 +235,28 @@ - (RCTFabricSurface *)createSurfaceWithModuleName:(NSString *)moduleName initial return [self createSurfaceWithModuleName:moduleName mode:DisplayMode::Visible initialProperties:properties]; } -- (RCTModuleRegistry *)getModuleRegistry +- (RCTModuleRegistry *)moduleRegistry { return _moduleRegistry; } -- (RCTSurfacePresenter *)getSurfacePresenter +// Deprecated +- (RCTModuleRegistry *)getModuleRegistry +{ + return self.moduleRegistry; +} + +- (RCTSurfacePresenter *)surfacePresenter { return [_instance surfacePresenter]; } +// Deprecated +- (RCTSurfacePresenter *)getSurfacePresenter +{ + return self.surfacePresenter; +} + - (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args { [_instance callFunctionOnJSModule:moduleName method:method args:args]; @@ -276,7 +288,7 @@ - (void)didReceiveReloadCommand [_hostDelegate hostDidStart:self]; for (RCTFabricSurface *surface in [self _getAttachedSurfaces]) { - [surface resetWithSurfacePresenter:[self getSurfacePresenter]]; + [surface resetWithSurfacePresenter:self.surfacePresenter]; } } diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.h index a24cc08a496e0e..90d6911ce8be1e 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.h @@ -62,7 +62,7 @@ typedef void (^_Null_unspecified RCTInstanceInitialBundleLoadCompletionBlock)(); turboModuleManagerDelegate:(id)turboModuleManagerDelegate onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad moduleRegistry:(RCTModuleRegistry *)moduleRegistry - parentInspectorTarget:(facebook::react::jsinspector_modern::PageTarget *)parentInspectorTarget; + parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget; - (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args; diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm index a123105a672ce1..639cb889fab0e8 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm @@ -6,7 +6,6 @@ */ #import "RCTInstance.h" -#import #import @@ -16,6 +15,8 @@ #import #import #import +#import +#import #import #import #import @@ -28,6 +29,8 @@ #import #import #import +#import +#import #import #import #import @@ -84,7 +87,7 @@ @implementation RCTInstance { // APIs supporting interop with native modules and view managers RCTBridgeModuleDecorator *_bridgeModuleDecorator; - jsinspector_modern::PageTarget *_parentInspectorTarget; + jsinspector_modern::HostTarget *_parentInspectorTarget; } #pragma mark - Public @@ -95,7 +98,7 @@ - (instancetype)initWithDelegate:(id)delegate turboModuleManagerDelegate:(id)tmmDelegate onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad moduleRegistry:(RCTModuleRegistry *)moduleRegistry - parentInspectorTarget:(jsinspector_modern::PageTarget *)parentInspectorTarget + parentInspectorTarget:(jsinspector_modern::HostTarget *)parentInspectorTarget { if (self = [super init]) { _performanceLogger = [RCTPerformanceLogger new]; @@ -122,10 +125,17 @@ - (instancetype)initWithDelegate:(id)delegate }]; } - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(_notifyEventDispatcherObserversOfEvent_DEPRECATED:) - name:@"RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED" - object:nil]; + NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; + + [defaultCenter addObserver:self + selector:@selector(_notifyEventDispatcherObserversOfEvent_DEPRECATED:) + name:@"RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED" + object:nil]; + + [defaultCenter addObserver:self + selector:@selector(didReceiveReloadCommand) + name:RCTTriggerReloadCommandNotification + object:nil]; [self _start]; } @@ -247,6 +257,7 @@ - (void)_start RuntimeExecutor bufferedRuntimeExecutor = _reactInstance->getBufferedRuntimeExecutor(); timerManager->setRuntimeExecutor(bufferedRuntimeExecutor); + auto jsCallInvoker = make_shared(bufferedRuntimeExecutor); RCTBridgeProxy *bridgeProxy = [[RCTBridgeProxy alloc] initWithViewRegistry:_bridgeModuleDecorator.viewRegistry_DEPRECATED moduleRegistry:_bridgeModuleDecorator.moduleRegistry @@ -265,14 +276,14 @@ - (void)_start } } runtime:_reactInstance->getJavaScriptContext()]; + bridgeProxy.jsCallInvoker = jsCallInvoker; [RCTBridge setCurrentBridge:(RCTBridge *)bridgeProxy]; // Set up TurboModules - _turboModuleManager = [[RCTTurboModuleManager alloc] - initWithBridgeProxy:bridgeProxy - bridgeModuleDecorator:_bridgeModuleDecorator - delegate:self - jsInvoker:std::make_shared(bufferedRuntimeExecutor)]; + _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridgeProxy:bridgeProxy + bridgeModuleDecorator:_bridgeModuleDecorator + delegate:self + jsInvoker:jsCallInvoker]; _turboModuleManager.runtimeHandler = self; #if RCT_DEV @@ -389,6 +400,24 @@ - (void)_attachBridgelessAPIsToModule:(id)module } } +- (void)handleBundleLoadingError:(NSError *)error +{ + if (!_valid) { + return; + } + + RCTRedBox *redBox = [_turboModuleManager moduleForName:"RedBox"]; + + RCTExecuteOnMainQueue(^{ + [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidFailToLoadNotification + object:self + userInfo:@{@"error" : error}]; + [redBox showErrorMessage:[error localizedDescription]]; + + RCTFatal(error); + }); +} + - (void)_loadJSBundle:(NSURL *)sourceURL { #if RCT_DEV_MENU && __has_include() @@ -420,8 +449,7 @@ - (void)_loadJSBundle:(NSURL *)sourceURL } if (error) { - // TODO(T91461138): Properly address bundle loading errors. - RCTLogError(@"RCTInstance: Error while loading bundle: %@", error); + [strongSelf handleBundleLoadingError:error]; [strongSelf invalidate]; return; } @@ -490,4 +518,9 @@ - (void)_handleJSErrorMap:(facebook::react::MapBuffer)errorMap isFatal:errorMap.getBool(JSErrorHandlerKey::kIsFatal)]; } +- (void)didReceiveReloadCommand +{ + [self _loadJSBundle:[_bridgeModuleDecorator.bundleManager bundleURL]]; +} + @end diff --git a/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm b/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm index a6be15a7f03011..78d2e9c2a76c5f 100644 --- a/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm +++ b/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm @@ -54,7 +54,7 @@ - (instancetype)initWithDelegate:(id)delegate turboModuleManagerDelegate:(id)tmmDelegate onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad moduleRegistry:(RCTModuleRegistry *)moduleRegistry - parentInspectorTarget:(facebook::react::jsinspector_modern::PageTarget *)parentInspectorTarget + parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget { weakShim.initCount++; return self; diff --git a/packages/react-native/ReactCommon/react/utils/.clang-tidy b/packages/react-native/ReactCommon/react/utils/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/react/utils/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/react/utils/CoreFeatures.cpp b/packages/react-native/ReactCommon/react/utils/CoreFeatures.cpp index 1ae6897bfbc1cc..f29d262bd1fa1c 100644 --- a/packages/react-native/ReactCommon/react/utils/CoreFeatures.cpp +++ b/packages/react-native/ReactCommon/react/utils/CoreFeatures.cpp @@ -12,7 +12,6 @@ namespace facebook::react { bool CoreFeatures::enablePropIteratorSetter = false; bool CoreFeatures::cacheLastTextMeasurement = false; bool CoreFeatures::enableGranularScrollViewStateUpdatesIOS = false; -bool CoreFeatures::enableMountHooks = false; bool CoreFeatures::enableGranularShadowTreeStateReconciliation = false; bool CoreFeatures::enableClonelessStateProgression = false; bool CoreFeatures::excludeYogaFromRawProps = false; diff --git a/packages/react-native/ReactCommon/react/utils/CoreFeatures.h b/packages/react-native/ReactCommon/react/utils/CoreFeatures.h index 1cf5dc68d1e2df..7b9731917f580a 100644 --- a/packages/react-native/ReactCommon/react/utils/CoreFeatures.h +++ b/packages/react-native/ReactCommon/react/utils/CoreFeatures.h @@ -29,9 +29,6 @@ class CoreFeatures { // updates for all changes in scroll position. static bool enableGranularScrollViewStateUpdatesIOS; - // Report mount operations from the host platform to notify mount hooks. - static bool enableMountHooks; - // When enabled, the renderer would only fail commits when they propagate // state and the last commit that updated state changed before committing. static bool enableGranularShadowTreeStateReconciliation; diff --git a/packages/react-native/ReactCommon/react/utils/OnScopeExit.h b/packages/react-native/ReactCommon/react/utils/OnScopeExit.h new file mode 100644 index 00000000000000..ce8e907da3bdb0 --- /dev/null +++ b/packages/react-native/ReactCommon/react/utils/OnScopeExit.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace facebook::react { + +template +class OnScopeExit { + public: + explicit OnScopeExit(const Lambda&& lambda) noexcept + : lambda_(std::move(lambda)) {} + + // Non-movable + OnScopeExit(const OnScopeExit&) = delete; + OnScopeExit(OnScopeExit&&) = delete; + + // Non-copyable + OnScopeExit& operator=(const OnScopeExit&) = delete; + OnScopeExit& operator=(OnScopeExit&&) = delete; + + ~OnScopeExit() noexcept { + lambda_(); + } + + private: + Lambda lambda_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h index a0855f68433058..c5cd6e4bfa67a1 100644 --- a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h +++ b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +#pragma once + #include #include #include diff --git a/packages/react-native/ReactCommon/reactperflogger/.clang-tidy b/packages/react-native/ReactCommon/reactperflogger/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/reactperflogger/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/runtimeexecutor/.clang-tidy b/packages/react-native/ReactCommon/runtimeexecutor/.clang-tidy deleted file mode 100644 index 9f33ef5a06d828..00000000000000 --- a/packages/react-native/ReactCommon/runtimeexecutor/.clang-tidy +++ /dev/null @@ -1,6 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -InheritParentConfig: true -... diff --git a/packages/react-native/ReactCommon/yoga/.clang-tidy b/packages/react-native/ReactCommon/yoga/.clang-tidy deleted file mode 100644 index c98fd78ff64baa..00000000000000 --- a/packages/react-native/ReactCommon/yoga/.clang-tidy +++ /dev/null @@ -1,5 +0,0 @@ ---- -Checks: '> -clang-diagnostic-*, -' -... diff --git a/packages/react-native/ReactCommon/yoga/Yoga.podspec b/packages/react-native/ReactCommon/yoga/Yoga.podspec index a84876951aa67c..ec404ece39c985 100644 --- a/packages/react-native/ReactCommon/yoga/Yoga.podspec +++ b/packages/react-native/ReactCommon/yoga/Yoga.podspec @@ -32,7 +32,9 @@ Pod::Spec.new do |spec| spec.requires_arc = false spec.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' - } + }.merge!(ENV['USE_FRAMEWORKS'] != nil ? { + 'HEADER_SEARCH_PATHS' => '"$(PODS_TARGET_SRCROOT)"' + } : {}) spec.compiler_flags = [ '-fno-omit-frame-pointer', '-fexceptions', diff --git a/packages/react-native/ReactCommon/yoga/cmake/project-defaults.cmake b/packages/react-native/ReactCommon/yoga/cmake/project-defaults.cmake index c262bac8af89af..987529c549c9b8 100644 --- a/packages/react-native/ReactCommon/yoga/cmake/project-defaults.cmake +++ b/packages/react-native/ReactCommon/yoga/cmake/project-defaults.cmake @@ -33,9 +33,7 @@ add_compile_options( -fexceptions # Enable warnings and warnings as errors -Wall - -Wextra -Werror - -Wconversion # Disable RTTI $<$:-fno-rtti> # Use -O2 (prioritize speed) diff --git a/packages/react-native/ReactCommon/yoga/yoga/YGNode.cpp b/packages/react-native/ReactCommon/yoga/yoga/YGNode.cpp index 57f0473b05e8d9..a34685eee625c8 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/YGNode.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/YGNode.cpp @@ -216,12 +216,12 @@ void YGNodeSetChildren( auto owner = resolveRef(ownerRef); auto children = reinterpret_cast(childrenRefs); - if (!owner) { + if (owner == nullptr) { return; } const std::vector childrenVector = {children, children + count}; - if (childrenVector.size() == 0) { + if (childrenVector.empty()) { if (owner->getChildCount() > 0) { for (auto* child : owner->getChildren()) { child->setLayout({}); diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.cpp b/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.cpp index ccec8f187623ea..32a13c9d430664 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.cpp @@ -480,14 +480,10 @@ void layoutAbsoluteDescendants( LayoutData& layoutMarkerData, uint32_t currentDepth, uint32_t generationCount, - float currentNodeMainOffsetFromContainingBlock, - float currentNodeCrossOffsetFromContainingBlock, + float currentNodeLeftOffsetFromContainingBlock, + float currentNodeTopOffsetFromContainingBlock, float containingNodeAvailableInnerWidth, float containingNodeAvailableInnerHeight) { - const FlexDirection mainAxis = resolveDirection( - currentNode->style().flexDirection(), currentNodeDirection); - const FlexDirection crossAxis = - resolveCrossDirection(mainAxis, currentNodeDirection); for (auto child : currentNode->getChildren()) { if (child->style().display() == Display::None) { continue; @@ -516,45 +512,73 @@ void layoutAbsoluteDescendants( currentDepth, generationCount); - const bool isMainAxisRow = isRow(mainAxis); - const bool mainInsetsDefined = isMainAxisRow - ? child->style().horizontalInsetsDefined() - : child->style().verticalInsetsDefined(); - const bool crossInsetsDefined = isMainAxisRow - ? child->style().verticalInsetsDefined() - : child->style().horizontalInsetsDefined(); - - const float childMainOffsetFromParent = mainInsetsDefined - ? (child->getLayout().position(flexStartEdge(mainAxis)) - - currentNodeMainOffsetFromContainingBlock) - : child->getLayout().position(flexStartEdge(mainAxis)); - const float childCrossOffsetFromParent = crossInsetsDefined - ? (child->getLayout().position(flexStartEdge(crossAxis)) - - currentNodeCrossOffsetFromContainingBlock) - : child->getLayout().position(flexStartEdge(crossAxis)); - - child->setLayoutPosition( - childMainOffsetFromParent, flexStartEdge(mainAxis)); - child->setLayoutPosition( - childCrossOffsetFromParent, flexStartEdge(crossAxis)); - - if (needsTrailingPosition(mainAxis)) { - setChildTrailingPosition(currentNode, child, mainAxis); + /* + * At this point the child has its position set but only on its the + * parent's flexStart edge. Additionally, this position should be + * interpreted relative to the containing block of the child if it had + * insets defined. So we need to adjust the position by subtracting the + * the parents offset from the containing block. However, getting that + * offset is complicated since the two nodes can have different main/cross + * axes. + */ + const FlexDirection parentMainAxis = resolveDirection( + currentNode->style().flexDirection(), currentNodeDirection); + const FlexDirection parentCrossAxis = + resolveCrossDirection(parentMainAxis, currentNodeDirection); + + if (needsTrailingPosition(parentMainAxis)) { + const bool mainInsetsDefined = isRow(parentMainAxis) + ? child->style().horizontalInsetsDefined() + : child->style().verticalInsetsDefined(); + setChildTrailingPosition( + mainInsetsDefined ? containingNode : currentNode, + child, + parentMainAxis); } - if (needsTrailingPosition(crossAxis)) { - setChildTrailingPosition(currentNode, child, crossAxis); + if (needsTrailingPosition(parentCrossAxis)) { + const bool crossInsetsDefined = isRow(parentCrossAxis) + ? child->style().horizontalInsetsDefined() + : child->style().verticalInsetsDefined(); + setChildTrailingPosition( + crossInsetsDefined ? containingNode : currentNode, + child, + parentCrossAxis); } + + /* + * At this point we know the left and top physical edges of the child are + * set with positions that are relative to the containing block if insets + * are defined + */ + const float childLeftPosition = + child->getLayout().position(PhysicalEdge::Left); + const float childTopPosition = + child->getLayout().position(PhysicalEdge::Top); + + const float childLeftOffsetFromParent = + child->style().horizontalInsetsDefined() + ? (childLeftPosition - currentNodeLeftOffsetFromContainingBlock) + : childLeftPosition; + const float childTopOffsetFromParent = + child->style().verticalInsetsDefined() + ? (childTopPosition - currentNodeTopOffsetFromContainingBlock) + : childTopPosition; + + child->setLayoutPosition(childLeftOffsetFromParent, PhysicalEdge::Left); + child->setLayoutPosition(childTopOffsetFromParent, PhysicalEdge::Top); } else if ( child->style().positionType() == PositionType::Static && !child->alwaysFormsContainingBlock()) { const Direction childDirection = child->resolveDirection(currentNodeDirection); - const float childMainOffsetFromContainingBlock = - currentNodeMainOffsetFromContainingBlock + - child->getLayout().position(flexStartEdge(mainAxis)); - const float childCrossOffsetFromContainingBlock = - currentNodeCrossOffsetFromContainingBlock + - child->getLayout().position(flexStartEdge(crossAxis)); + // By now all descendants of the containing block that are not absolute + // will have their positions set for left and top. + const float childLeftOffsetFromContainingBlock = + currentNodeLeftOffsetFromContainingBlock + + child->getLayout().position(PhysicalEdge::Left); + const float childTopOffsetFromContainingBlock = + currentNodeTopOffsetFromContainingBlock + + child->getLayout().position(PhysicalEdge::Top); layoutAbsoluteDescendants( containingNode, @@ -564,8 +588,8 @@ void layoutAbsoluteDescendants( layoutMarkerData, currentDepth + 1, generationCount, - childMainOffsetFromContainingBlock, - childCrossOffsetFromContainingBlock, + childLeftOffsetFromContainingBlock, + childTopOffsetFromContainingBlock, containingNodeAvailableInnerWidth, containingNodeAvailableInnerHeight); } diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.h b/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.h index 3beabf9a4a0a17..ae84e6da9f2bc0 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.h +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/AbsoluteLayout.h @@ -13,16 +13,16 @@ namespace facebook::yoga { void layoutAbsoluteChild( - const yoga::Node* const containingNode, - const yoga::Node* const node, - yoga::Node* const child, - const float containingBlockWidth, - const float containingBlockHeight, - const SizingMode widthMode, - const Direction direction, + const yoga::Node* containingNode, + const yoga::Node* node, + yoga::Node* child, + float containingBlockWidth, + float containingBlockHeight, + SizingMode widthMode, + Direction direction, LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount); + uint32_t depth, + uint32_t generationCount); void layoutAbsoluteDescendants( yoga::Node* containingNode, diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp index 9b214cf587ff6d..abec51f58181a6 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp @@ -80,8 +80,8 @@ static void computeFlexBasisForChild( const float mainAxisSize = isMainAxisRow ? width : height; const float mainAxisownerSize = isMainAxisRow ? ownerWidth : ownerHeight; - float childWidth; - float childHeight; + float childWidth = YGUndefined; + float childHeight = YGUndefined; SizingMode childWidthSizingMode; SizingMode childHeightSizingMode; @@ -120,8 +120,6 @@ static void computeFlexBasisForChild( } else { // Compute the flex basis and hypothetical main size (i.e. the clamped flex // basis). - childWidth = YGUndefined; - childHeight = YGUndefined; childWidthSizingMode = SizingMode::MaxContent; childHeightSizingMode = SizingMode::MaxContent; @@ -606,7 +604,7 @@ static float distributeFreeSpaceSecondPass( -currentLineChild->resolveFlexShrink() * childFlexBasis; // Is this child able to shrink? if (flexShrinkScaledFactor != 0) { - float childSize; + float childSize = YGUndefined; if (yoga::isDefined(flexLine.layout.totalFlexShrinkScaledFactors) && flexLine.layout.totalFlexShrinkScaledFactors == 0) { @@ -650,7 +648,7 @@ static float distributeFreeSpaceSecondPass( const float marginCross = currentLineChild->style().computeMarginForAxis( crossAxis, availableInnerWidth); - float childCrossSize; + float childCrossSize = YGUndefined; float childMainSize = updatedMainSize + marginMain; SizingMode childCrossSizingMode; SizingMode childMainSizingMode = SizingMode::StretchFit; @@ -1794,13 +1792,13 @@ static void calculateLayoutImpl( size_t endIndex = 0; for (size_t i = 0; i < lineCount; i++) { const size_t startIndex = endIndex; - size_t ii; + size_t ii = startIndex; // compute the line's height and find the endIndex float lineHeight = 0; float maxAscentForCurrentLine = 0; float maxDescentForCurrentLine = 0; - for (ii = startIndex; ii < childCount; ii++) { + for (; ii < childCount; ii++) { const auto child = node->getChild(ii); if (child->style().display() == Display::None) { continue; @@ -1837,113 +1835,110 @@ static void calculateLayoutImpl( endIndex = ii; currentLead += i != 0 ? crossAxisGap : 0; - if (performLayout) { - for (ii = startIndex; ii < endIndex; ii++) { - const auto child = node->getChild(ii); - if (child->style().display() == Display::None) { - continue; - } - if (child->style().positionType() != PositionType::Absolute) { - switch (resolveChildAlignment(node, child)) { - case Align::FlexStart: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartPosition( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - break; - } - case Align::FlexEnd: { - child->setLayoutPosition( - currentLead + lineHeight - - child->style().computeFlexEndMargin( - crossAxis, direction, availableInnerWidth) - - child->getLayout().measuredDimension( - dimension(crossAxis)), - flexStartEdge(crossAxis)); - break; - } - case Align::Center: { - float childHeight = - child->getLayout().measuredDimension(dimension(crossAxis)); - - child->setLayoutPosition( - currentLead + (lineHeight - childHeight) / 2, - flexStartEdge(crossAxis)); - break; - } - case Align::Stretch: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartMargin( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - - // Remeasure child with the line height as it as been only - // measured with the owners height yet. - if (!child->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim)) { - const float childWidth = isMainAxisRow - ? (child->getLayout().measuredDimension( - Dimension::Width) + - child->style().computeMarginForAxis( - mainAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - const float childHeight = !isMainAxisRow - ? (child->getLayout().measuredDimension( - Dimension::Height) + - child->style().computeMarginForAxis( - crossAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - if (!(yoga::inexactEquals( - childWidth, - child->getLayout().measuredDimension( - Dimension::Width)) && - yoga::inexactEquals( - childHeight, - child->getLayout().measuredDimension( - Dimension::Height)))) { - calculateLayoutInternal( - child, - childWidth, - childHeight, - direction, - SizingMode::StretchFit, - SizingMode::StretchFit, - availableInnerWidth, - availableInnerHeight, - true, - LayoutPassReason::kMultilineStretch, - layoutMarkerData, - depth, - generationCount); - } + for (ii = startIndex; ii < endIndex; ii++) { + const auto child = node->getChild(ii); + if (child->style().display() == Display::None) { + continue; + } + if (child->style().positionType() != PositionType::Absolute) { + switch (resolveChildAlignment(node, child)) { + case Align::FlexStart: { + child->setLayoutPosition( + currentLead + + child->style().computeFlexStartPosition( + crossAxis, direction, availableInnerWidth), + flexStartEdge(crossAxis)); + break; + } + case Align::FlexEnd: { + child->setLayoutPosition( + currentLead + lineHeight - + child->style().computeFlexEndMargin( + crossAxis, direction, availableInnerWidth) - + child->getLayout().measuredDimension( + dimension(crossAxis)), + flexStartEdge(crossAxis)); + break; + } + case Align::Center: { + float childHeight = + child->getLayout().measuredDimension(dimension(crossAxis)); + + child->setLayoutPosition( + currentLead + (lineHeight - childHeight) / 2, + flexStartEdge(crossAxis)); + break; + } + case Align::Stretch: { + child->setLayoutPosition( + currentLead + + child->style().computeFlexStartMargin( + crossAxis, direction, availableInnerWidth), + flexStartEdge(crossAxis)); + + // Remeasure child with the line height as it as been only + // measured with the owners height yet. + if (!child->hasDefiniteLength( + dimension(crossAxis), availableInnerCrossDim)) { + const float childWidth = isMainAxisRow + ? (child->getLayout().measuredDimension(Dimension::Width) + + child->style().computeMarginForAxis( + mainAxis, availableInnerWidth)) + : leadPerLine + lineHeight; + + const float childHeight = !isMainAxisRow + ? (child->getLayout().measuredDimension(Dimension::Height) + + child->style().computeMarginForAxis( + crossAxis, availableInnerWidth)) + : leadPerLine + lineHeight; + + if (!(yoga::inexactEquals( + childWidth, + child->getLayout().measuredDimension( + Dimension::Width)) && + yoga::inexactEquals( + childHeight, + child->getLayout().measuredDimension( + Dimension::Height)))) { + calculateLayoutInternal( + child, + childWidth, + childHeight, + direction, + SizingMode::StretchFit, + SizingMode::StretchFit, + availableInnerWidth, + availableInnerHeight, + true, + LayoutPassReason::kMultilineStretch, + layoutMarkerData, + depth, + generationCount); } - break; - } - case Align::Baseline: { - child->setLayoutPosition( - currentLead + maxAscentForCurrentLine - - calculateBaseline(child) + - child->style().computeFlexStartPosition( - FlexDirection::Column, - direction, - availableInnerCrossDim), - PhysicalEdge::Top); - - break; } - case Align::Auto: - case Align::SpaceBetween: - case Align::SpaceAround: - case Align::SpaceEvenly: - break; + break; + } + case Align::Baseline: { + child->setLayoutPosition( + currentLead + maxAscentForCurrentLine - + calculateBaseline(child) + + child->style().computeFlexStartPosition( + FlexDirection::Column, + direction, + availableInnerCrossDim), + PhysicalEdge::Top); + + break; } + case Align::Auto: + case Align::SpaceBetween: + case Align::SpaceAround: + case Align::SpaceEvenly: + break; } } } + currentLead = currentLead + leadPerLine + lineHeight; } } @@ -2045,26 +2040,7 @@ static void calculateLayoutImpl( } if (performLayout) { - // STEP 10: SIZING AND POSITIONING ABSOLUTE CHILDREN - // Let the containing block layout its absolute descendants. By definition - // the containing block will not be static unless we are at the root. - if (node->style().positionType() != PositionType::Static || - node->alwaysFormsContainingBlock() || depth == 1) { - layoutAbsoluteDescendants( - node, - node, - isMainAxisRow ? sizingModeMainDim : sizingModeCrossDim, - direction, - layoutMarkerData, - depth, - generationCount, - 0.0f, - 0.0f, - availableInnerWidth, - availableInnerHeight); - } - - // STEP 11: SETTING TRAILING POSITIONS FOR CHILDREN + // STEP 10: SETTING TRAILING POSITIONS FOR CHILDREN const bool needsMainTrailingPos = needsTrailingPosition(mainAxis); const bool needsCrossTrailingPos = needsTrailingPosition(crossAxis); @@ -2087,6 +2063,24 @@ static void calculateLayoutImpl( } } } + + // STEP 11: SIZING AND POSITIONING ABSOLUTE CHILDREN + // Let the containing block layout its absolute descendants. + if (node->style().positionType() != PositionType::Static || + node->alwaysFormsContainingBlock() || depth == 1) { + layoutAbsoluteDescendants( + node, + node, + isMainAxisRow ? sizingModeMainDim : sizingModeCrossDim, + direction, + layoutMarkerData, + depth, + generationCount, + 0.0f, + 0.0f, + availableInnerWidth, + availableInnerHeight); + } } } @@ -2244,7 +2238,7 @@ bool calculateLayoutInternal( layout->nextCachedMeasurementsIndex = 0; } - CachedMeasurement* newCacheEntry; + CachedMeasurement* newCacheEntry = nullptr; if (performLayout) { // Use the single layout cache entry. newCacheEntry = &layout->cachedLayout; diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.h b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.h index 1d5a3fd7394525..5e6884ec1a49a1 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.h +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.h @@ -15,24 +15,24 @@ namespace facebook::yoga { void calculateLayout( - yoga::Node* const node, - const float ownerWidth, - const float ownerHeight, - const Direction ownerDirection); + yoga::Node* node, + float ownerWidth, + float ownerHeight, + Direction ownerDirection); bool calculateLayoutInternal( - yoga::Node* const node, - const float availableWidth, - const float availableHeight, - const Direction ownerDirection, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight, - const bool performLayout, - const LayoutPassReason reason, + yoga::Node* node, + float availableWidth, + float availableHeight, + Direction ownerDirection, + SizingMode widthSizingMode, + SizingMode heightSizingMode, + float ownerWidth, + float ownerHeight, + bool performLayout, + LayoutPassReason reason, LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount); + uint32_t depth, + uint32_t generationCount); } // namespace facebook::yoga diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.cpp b/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.cpp index 69ae351efab2dd..1fe3e486926f62 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.cpp @@ -69,7 +69,7 @@ FlexLine calculateFlexLine( if (sizeConsumedIncludingMinConstraint + flexBasisWithMinAndMaxConstraints + childMarginMainAxis + childLeadingGapMainAxis > availableInnerMainDim && - isNodeFlexWrap && itemsInFlow.size() > 0) { + isNodeFlexWrap && !itemsInFlow.empty()) { break; } diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.h b/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.h index 161a1031c36b61..0f888be50738ec 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.h +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/FlexLine.h @@ -63,7 +63,7 @@ struct FlexLine { // computedFlexBasis properly computed(To do this use // computeFlexBasisForChildren function). FlexLine calculateFlexLine( - yoga::Node* const node, + yoga::Node* node, Direction ownerDirection, float mainAxisownerSize, float availableInnerWidth, diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/PixelGrid.h b/packages/react-native/ReactCommon/yoga/yoga/algorithm/PixelGrid.h index 6bedd3ac0ecc1b..f3bf79f98a69b2 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/PixelGrid.h +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/PixelGrid.h @@ -15,15 +15,15 @@ namespace facebook::yoga { // Round a point value to the nearest physical pixel based on DPI // (pointScaleFactor) float roundValueToPixelGrid( - const double value, - const double pointScaleFactor, - const bool forceCeil, - const bool forceFloor); + double value, + double pointScaleFactor, + bool forceCeil, + bool forceFloor); // Round the layout results of a node and its subtree to the pixel grid. void roundLayoutResultsToPixelGrid( - yoga::Node* const node, - const double absoluteLeft, - const double absoluteTop); + yoga::Node* node, + double absoluteLeft, + double absoluteTop); } // namespace facebook::yoga diff --git a/packages/react-native/ReactCommon/yoga/yoga/config/Config.cpp b/packages/react-native/ReactCommon/yoga/yoga/config/Config.cpp index 607e57747065bf..881a377360e903 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/config/Config.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/config/Config.cpp @@ -20,10 +20,6 @@ bool configUpdateInvalidatesLayout( oldConfig.useWebDefaults() != newConfig.useWebDefaults(); } -Config::Config(YGLogger logger) : cloneNodeCallback_{nullptr} { - setLogger(logger); -} - void Config::setUseWebDefaults(bool useWebDefaults) { useWebDefaults_ = useWebDefaults; } diff --git a/packages/react-native/ReactCommon/yoga/yoga/config/Config.h b/packages/react-native/ReactCommon/yoga/yoga/config/Config.h index e902bd0d1b9021..4db25bd0f4d2c1 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/config/Config.h +++ b/packages/react-native/ReactCommon/yoga/yoga/config/Config.h @@ -32,7 +32,7 @@ bool configUpdateInvalidatesLayout( class YG_EXPORT Config : public ::YGConfig { public: - Config(YGLogger logger); + explicit Config(YGLogger logger) : logger_{logger} {} void setUseWebDefaults(bool useWebDefaults); bool useWebDefaults() const; @@ -67,8 +67,8 @@ class YG_EXPORT Config : public ::YGConfig { static const Config& getDefault(); private: - YGCloneNodeFunc cloneNodeCallback_; - YGLogger logger_; + YGCloneNodeFunc cloneNodeCallback_{nullptr}; + YGLogger logger_{}; bool useWebDefaults_ : 1 = false; diff --git a/packages/react-native/ReactCommon/yoga/yoga/debug/Log.h b/packages/react-native/ReactCommon/yoga/yoga/debug/Log.h index 94dc0e0cedf38b..0a932d80eb0569 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/debug/Log.h +++ b/packages/react-native/ReactCommon/yoga/yoga/debug/Log.h @@ -20,7 +20,7 @@ void log(LogLevel level, const char* format, ...) noexcept; void log( const yoga::Node* node, LogLevel level, - const char* message, + const char* format, ...) noexcept; void log( diff --git a/packages/react-native/ReactCommon/yoga/yoga/event/event.cpp b/packages/react-native/ReactCommon/yoga/yoga/event/event.cpp index b47e1fab7fd7ba..e286ded0555cef 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/event/event.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/event/event.cpp @@ -40,14 +40,14 @@ struct Node { std::function subscriber = nullptr; Node* next = nullptr; - Node(std::function&& subscriber) + explicit Node(std::function&& subscriber) : subscriber{std::move(subscriber)} {} }; std::atomic subscribers{nullptr}; Node* push(Node* newHead) { - Node* oldHead; + Node* oldHead = nullptr; do { oldHead = subscribers.load(std::memory_order_relaxed); if (newHead != nullptr) { diff --git a/packages/react-native/ReactCommon/yoga/yoga/event/event.h b/packages/react-native/ReactCommon/yoga/yoga/event/event.h index 4e96e049eab653..b4be8ab298fcf2 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/event/event.h +++ b/packages/react-native/ReactCommon/yoga/yoga/event/event.h @@ -9,8 +9,8 @@ #include -#include #include +#include #include #include @@ -46,7 +46,7 @@ struct LayoutData { measureCallbackReasonsCount; }; -const char* LayoutPassReasonToString(const LayoutPassReason value); +const char* LayoutPassReasonToString(LayoutPassReason value); struct YG_EXPORT Event { enum Type { @@ -72,7 +72,7 @@ struct YG_EXPORT Event { public: template - Data(const TypedData& data) : data_{&data} {} + explicit Data(const TypedData& data) : data_{&data} {} template const TypedData& get() const { @@ -90,7 +90,10 @@ struct YG_EXPORT Event { } private: - static void publish(YGNodeConstRef, Type, const Data&); + static void publish( + YGNodeConstRef /*node*/, + Type /*eventType*/, + const Data& /*eventData*/); }; template <> diff --git a/packages/react-native/ReactCommon/yoga/yoga/node/Node.cpp b/packages/react-native/ReactCommon/yoga/yoga/node/Node.cpp index c431940e16437d..adb63663bed9b5 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/node/Node.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/node/Node.cpp @@ -26,23 +26,23 @@ Node::Node(const yoga::Config* config) : config_{config} { } } -Node::Node(Node&& node) { - hasNewLayout_ = node.hasNewLayout_; - isReferenceBaseline_ = node.isReferenceBaseline_; - isDirty_ = node.isDirty_; - alwaysFormsContainingBlock_ = node.alwaysFormsContainingBlock_; - nodeType_ = node.nodeType_; - context_ = node.context_; - measureFunc_ = node.measureFunc_; - baselineFunc_ = node.baselineFunc_; - dirtiedFunc_ = node.dirtiedFunc_; - style_ = node.style_; - layout_ = node.layout_; - lineIndex_ = node.lineIndex_; - owner_ = node.owner_; - children_ = std::move(node.children_); - config_ = node.config_; - resolvedDimensions_ = node.resolvedDimensions_; +Node::Node(Node&& node) noexcept + : hasNewLayout_(node.hasNewLayout_), + isReferenceBaseline_(node.isReferenceBaseline_), + isDirty_(node.isDirty_), + alwaysFormsContainingBlock_(node.alwaysFormsContainingBlock_), + nodeType_(node.nodeType_), + context_(node.context_), + measureFunc_(node.measureFunc_), + baselineFunc_(node.baselineFunc_), + dirtiedFunc_(node.dirtiedFunc_), + style_(std::move(node.style_)), + layout_(node.layout_), + lineIndex_(node.lineIndex_), + owner_(node.owner_), + children_(std::move(node.children_)), + config_(node.config_), + resolvedDimensions_(node.resolvedDimensions_) { for (auto c : children_) { c->setOwner(this); } @@ -83,7 +83,7 @@ void Node::setMeasureFunc(YGMeasureFunc measureFunc) { } else { yoga::assertFatalWithNode( this, - children_.size() == 0, + children_.empty(), "Cannot set measure function: Nodes with measure functions cannot have " "children."); // TODO: t18095186 Move nodeType to opt-in function and mark appropriate @@ -122,18 +122,17 @@ void Node::setConfig(yoga::Config* config) { } void Node::setDirty(bool isDirty) { - if (isDirty == isDirty_) { + if (static_cast(isDirty) == isDirty_) { return; } isDirty_ = isDirty; - if (isDirty && dirtiedFunc_) { + if (isDirty && (dirtiedFunc_ != nullptr)) { dirtiedFunc_(this); } } bool Node::removeChild(Node* child) { - std::vector::iterator p = - std::find(children_.begin(), children_.end(), child); + auto p = std::find(children_.begin(), children_.end(), child); if (p != children_.end()) { children_.erase(p); return true; @@ -307,7 +306,7 @@ void Node::markDirtyAndPropagate() { if (!isDirty_) { setDirty(true); setLayoutComputedFlexBasis(FloatOptional()); - if (owner_) { + if (owner_ != nullptr) { owner_->markDirtyAndPropagate(); } } @@ -351,7 +350,7 @@ bool Node::isNodeFlexible() { void Node::reset() { yoga::assertFatalWithNode( this, - children_.size() == 0, + children_.empty(), "Cannot reset a node which still has children attached"); yoga::assertFatalWithNode( this, owner_ == nullptr, "Cannot reset a node still attached to a owner"); diff --git a/packages/react-native/ReactCommon/yoga/yoga/node/Node.h b/packages/react-native/ReactCommon/yoga/yoga/node/Node.h index 1eea46f8c1c51d..ec28f2db91a948 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/node/Node.h +++ b/packages/react-native/ReactCommon/yoga/yoga/node/Node.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include #include #include @@ -34,7 +34,7 @@ class YG_EXPORT Node : public ::YGNode { Node(); explicit Node(const Config* config); - Node(Node&&); + Node(Node&& node) noexcept; // Does not expose true value semantics, as children are not cloned eagerly. // Should we remove this? @@ -65,7 +65,11 @@ class YG_EXPORT Node : public ::YGNode { return measureFunc_ != nullptr; } - YGSize measure(float, MeasureMode, float, MeasureMode); + YGSize measure( + float width, + MeasureMode widthMode, + float height, + MeasureMode heightMode); bool hasBaselineFunc() const noexcept { return baselineFunc_ != nullptr; @@ -73,9 +77,9 @@ class YG_EXPORT Node : public ::YGNode { float baseline(float width, float height) const; - float dimensionWithMargin(const FlexDirection axis, const float widthSize); + float dimensionWithMargin(FlexDirection axis, float widthSize); - bool isLayoutDimensionDefined(const FlexDirection axis); + bool isLayoutDimensionDefined(FlexDirection axis); /** * Whether the node has a "definite length" along the given axis. @@ -214,7 +218,7 @@ class YG_EXPORT Node : public ::YGNode { void setDirty(bool isDirty); void setLayoutLastOwnerDirection(Direction direction); - void setLayoutComputedFlexBasis(const FloatOptional computedFlexBasis); + void setLayoutComputedFlexBasis(FloatOptional computedFlexBasis); void setLayoutComputedFlexBasisGeneration( uint32_t computedFlexBasisGeneration); void setLayoutMeasuredDimension(float measuredDimension, Dimension dimension); @@ -226,15 +230,15 @@ class YG_EXPORT Node : public ::YGNode { void setLayoutPadding(float padding, PhysicalEdge edge); void setLayoutPosition(float position, PhysicalEdge edge); void setPosition( - const Direction direction, - const float mainSize, - const float crossSize, - const float ownerWidth); + Direction direction, + float mainSize, + float crossSize, + float ownerWidth); // Other methods Style::Length resolveFlexBasisPtr() const; void resolveDimension(); - Direction resolveDirection(const Direction ownerDirection); + Direction resolveDirection(Direction ownerDirection); void clearChildren(); /// Replaces the occurrences of oldChild with newChild void replaceChild(Node* oldChild, Node* newChild); @@ -253,12 +257,12 @@ class YG_EXPORT Node : public ::YGNode { private: // Used to allow resetting the node - Node& operator=(Node&&) = default; + Node& operator=(Node&&) noexcept = default; float relativePosition( FlexDirection axis, Direction direction, - const float axisSize) const; + float axisSize) const; void useWebDefaults() { style_.setFlexDirection(FlexDirection::Row); diff --git a/packages/react-native/ReactCommon/yoga/yoga/style/SmallValueBuffer.h b/packages/react-native/ReactCommon/yoga/yoga/style/SmallValueBuffer.h index 2860a420f9ca6c..8d78a54dc974b4 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/style/SmallValueBuffer.h +++ b/packages/react-native/ReactCommon/yoga/yoga/style/SmallValueBuffer.h @@ -26,7 +26,7 @@ class SmallValueBuffer { SmallValueBuffer(const SmallValueBuffer& other) { *this = other; } - SmallValueBuffer(SmallValueBuffer&& other) = default; + SmallValueBuffer(SmallValueBuffer&& other) noexcept = default; // Add a new element to the buffer, returning the index of the element uint16_t push(uint32_t value) { @@ -116,7 +116,7 @@ class SmallValueBuffer { return *this; } - SmallValueBuffer& operator=(SmallValueBuffer&& other) = default; + SmallValueBuffer& operator=(SmallValueBuffer&& other) noexcept = default; private: struct Overflow { @@ -125,7 +125,7 @@ class SmallValueBuffer { }; uint16_t count_{0}; - std::array buffer_; + std::array buffer_{}; std::bitset wideElements_; std::unique_ptr overflow_; }; diff --git a/packages/react-native/ReactCommon/yoga/yoga/style/StyleValuePool.h b/packages/react-native/ReactCommon/yoga/yoga/style/StyleValuePool.h index f8ee93e47b3f16..3b177254447da4 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/style/StyleValuePool.h +++ b/packages/react-native/ReactCommon/yoga/yoga/style/StyleValuePool.h @@ -101,7 +101,7 @@ class StyleValuePool { static constexpr bool isIntegerPackable(float f) { constexpr uint16_t kMaxInlineAbsValue = (1 << 11) - 1; - int32_t i = static_cast(f); + auto i = static_cast(f); return static_cast(i) == f && i >= -kMaxInlineAbsValue && i <= +kMaxInlineAbsValue; } @@ -110,7 +110,7 @@ class StyleValuePool { uint16_t isNegative = value < 0 ? 1 : 0; return static_cast( (isNegative << 11) | - (static_cast(value) * (isNegative ? -1 : 1))); + (static_cast(value) * (isNegative != 0u ? -1 : 1))); } static constexpr float unpackInlineInteger(uint16_t value) { diff --git a/packages/react-native/cli.js b/packages/react-native/cli.js index 7dd4bfb76de8d5..53c7e47df57165 100755 --- a/packages/react-native/cli.js +++ b/packages/react-native/cli.js @@ -11,16 +11,33 @@ 'use strict'; const {name, version: currentVersion} = require('./package.json'); -const cli = require('@react-native-community/cli'); const chalk = require('chalk'); const {get} = require('https'); const {URL} = require('url'); +const deprecated = () => { + throw new Error( + 'react-native/cli is deprecated, please use @react-native-community/cli instead', + ); +}; + +let cli = { + bin: '/dev/null', + loadConfig: deprecated, + run: deprecated, +}; + const isNpxRuntime = process.env.npm_lifecycle_event === 'npx'; const DEFAULT_REGISTRY_HOST = process.env.npm_config_registry ?? 'https://registry.npmjs.org/'; const HEAD = '1000.0.0'; +// We're going to deprecate the `init` command proxying requests to @react-native-community/cli transparently +// on September 30th, 2024 or 0.76 (whichever arrives first). This is part of work to decouple of community CLI from React Native core. +// +// See https://github.com/react-native-community/discussions-and-proposals/blob/main/proposals/0759-react-native-frameworks.md +const CLI_DEPRECATION_DATE = new Date('2024-09-30'); + async function getLatestVersion(registryHost = DEFAULT_REGISTRY_HOST) { return new Promise((res, rej) => { const url = new URL(registryHost); @@ -39,6 +56,66 @@ async function getLatestVersion(registryHost = DEFAULT_REGISTRY_HOST) { }); } +/** + * Warn when users are using `npx react-native init`, to raise awareness of the changes from RFC 0759. + * + * Phase 1 + * + * @see https://github.com/react-native-community/discussions-and-proposals/tree/main/proposals/0759-react-native-frameworks.md + */ +function warnWhenRunningInit() { + if (process.argv[2] === 'init') { + console.warn( + `\nRunning: ${chalk.grey.bold('npx @react-native-community/cli init')}\n`, + ); + } +} + +/** + * Warn more sternly that the ability to call `npx react-native init` is going away. + * + * Phase 2 + * + * @see https://github.com/react-native-community/discussions-and-proposals/tree/main/proposals/0759-react-native-frameworks.md + */ +function warnWithDeprecationSchedule() { + if (process.argv[2] !== 'init') { + return; + } + + const daysRemaining = Math.ceil( + (CLI_DEPRECATION_DATE.getTime() - new Date().getTime()) / 86_400_000, + ); + + const emphasis = + daysRemaining < 10 + ? chalk.bgRed.white.bold + : daysRemaining < 30 + ? chalk.red.bold + : daysRemaining < 60 + ? chalk.green.bold + : chalk.blueBright.bold; + + console.warn(` +${chalk.yellow('⚠️')} The \`init\` command is deprecated. +The behavior will be changed on ${chalk.white.bold(CLI_DEPRECATION_DATE.toLocaleDateString())} ${emphasis(`(${daysRemaining} day${daysRemaining > 1 ? 's' : ''})`)}. + +- Switch to ${chalk.dim('npx @react-native-community/cli init')} for the identical behavior. +- Refer to the documentation for information about alternative tools: ${chalk.dim('https://reactnative.dev/docs/getting-started')}`); +} + +function warnWithDeprecated() { + if (process.argv[2] !== 'init') { + return; + } + + console.warn(` +${chalk.yellow('⚠')}️ The \`init\` command is deprecated. + +- Switch to ${chalk.dim('npx @react-native-community/cli init')} for the identical behavior. +- Refer to the documentation for information about alternative tools: ${chalk.dim('https://reactnative.dev/docs/getting-started')}`); +} + /** * npx react-native -> @react-native-community/cli * @@ -66,11 +143,47 @@ async function main() { // Ignore errors, since it's a nice to have warning } } - return cli.run(name); + + const isDeprecated = + CLI_DEPRECATION_DATE.getTime() <= new Date().getTime() || + currentVersion.startsWith('0.76'); + + /** + * This command now fails as it's fully deprecated. It will be entirely removed in 0.77. + * + * Phase 3 + * + * @see https://github.com/react-native-community/discussions-and-proposals/tree/main/proposals/0759-react-native-frameworks.md + */ + if (currentVersion !== HEAD && isDeprecated) { + warnWithDeprecated(); + process.exit(1); + } + + if (currentVersion.startsWith('0.75')) { + warnWithDeprecationSchedule(); + } + + warnWhenRunningInit(); + + return require('@react-native-community/cli').run(name); } if (require.main === module) { main(); +} else { + try { + cli = require('@react-native-community/cli'); + } catch (e) { + // We silence @react-native-community/cli missing as it is no + // longer a dependency + if ( + !e.code === 'MODULE_NOT_FOUND' && + /@react-native-community\/cli/.test(e.message) + ) { + throw e; + } + } } module.exports = cli; diff --git a/packages/react-native/index.js b/packages/react-native/index.js index 2dfeafbb64efd7..f087b702545fcd 100644 --- a/packages/react-native/index.js +++ b/packages/react-native/index.js @@ -27,7 +27,6 @@ import typeof Clipboard from './Libraries/Components/Clipboard/Clipboard'; import typeof DrawerLayoutAndroid from './Libraries/Components/DrawerAndroid/DrawerLayoutAndroid'; import typeof Keyboard from './Libraries/Components/Keyboard/Keyboard'; import typeof KeyboardAvoidingView from './Libraries/Components/Keyboard/KeyboardAvoidingView'; -import typeof PopupMenuAndroid from './Libraries/Components/PopupMenuAndroid/PopupMenuAndroid'; import typeof Pressable from './Libraries/Components/Pressable/Pressable'; import typeof ProgressBarAndroid from './Libraries/Components/ProgressBarAndroid/ProgressBarAndroid'; import typeof RefreshControl from './Libraries/Components/RefreshControl/RefreshControl'; @@ -135,10 +134,6 @@ module.exports = { return require('./Libraries/Components/Keyboard/KeyboardAvoidingView') .default; }, - get PopupMenuAndroid(): PopupMenuAndroid { - return require('./Libraries/Components/PopupMenuAndroid/PopupMenuAndroid') - .default; - }, get Modal(): Modal { return require('./Libraries/Modal/Modal'); }, diff --git a/packages/react-native/jest/setup.js b/packages/react-native/jest/setup.js index 86cab65f6db1ef..096623e349d338 100644 --- a/packages/react-native/jest/setup.js +++ b/packages/react-native/jest/setup.js @@ -112,17 +112,9 @@ jest Constants: {}, }, })) - .mock('../Libraries/Image/Image', () => { - const Image = mockComponent('../Libraries/Image/Image'); - Image.getSize = jest.fn(); - Image.getSizeWithHeaders = jest.fn(); - Image.prefetch = jest.fn(); - Image.prefetchWithMetadata = jest.fn(); - Image.queryCache = jest.fn(); - Image.resolveAssetSource = jest.fn(); - - return Image; - }) + .mock('../Libraries/Image/Image', () => + mockComponent('../Libraries/Image/Image'), + ) .mock('../Libraries/Text/Text', () => mockComponent('../Libraries/Text/Text', MockNativeMethods), ) @@ -261,7 +253,12 @@ jest }, ImageLoader: { getSize: jest.fn(url => Promise.resolve([320, 240])), + getSizeWithHeaders: jest.fn((url, headers) => + Promise.resolve({height: 222, width: 333}), + ), prefetchImage: jest.fn(), + prefetchImageWithMetadata: jest.fn(), + queryCache: jest.fn(), }, ImageViewManager: { getSize: jest.fn((uri, success) => diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 70efb104d59177..7047912ec6318e 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -5,7 +5,7 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/react-native" }, "homepage": "https://reactnative.dev/", @@ -23,7 +23,9 @@ "engines": { "node": ">=18" }, - "bin": "./cli.js", + "bin": { + "react-native": "cli.js" + }, "types": "types", "jest-junit": { "outputDirectory": "reports/junit", @@ -89,7 +91,7 @@ "types" ], "scripts": { - "prepack": "cp ../../README.md .", + "prepack": "node ./scripts/prepack.js", "featureflags-check": "node ./scripts/featureflags/index.js --verify-unchanged", "featureflags-update": "node ./scripts/featureflags/index.js" }, @@ -98,16 +100,16 @@ }, "dependencies": { "@jest/create-cache-key-function": "^29.6.3", - "@react-native-community/cli": "13.6.0", - "@react-native-community/cli-platform-android": "13.6.0", - "@react-native-community/cli-platform-ios": "13.6.0", - "@react-native/assets-registry": "0.74.0", - "@react-native/codegen": "0.74.0", - "@react-native/community-cli-plugin": "0.74.0", - "@react-native/gradle-plugin": "0.74.0", - "@react-native/js-polyfills": "0.74.0", - "@react-native/normalize-colors": "0.74.1", - "@react-native/virtualized-lists": "0.74.0", + "@react-native-community/cli": "14.0.0-alpha.0", + "@react-native-community/cli-platform-android": "14.0.0-alpha.0", + "@react-native-community/cli-platform-ios": "14.0.0-alpha.0", + "@react-native/assets-registry": "0.75.0-main", + "@react-native/codegen": "0.75.0-main", + "@react-native/community-cli-plugin": "0.75.0-main", + "@react-native/gradle-plugin": "0.75.0-main", + "@react-native/js-polyfills": "0.75.0-main", + "@react-native/normalize-colors": "0.75.0-main", + "@react-native/virtualized-lists": "0.75.0-main", "abort-controller": "^3.0.0", "anser": "^1.4.9", "ansi-regex": "^5.0.0", @@ -125,7 +127,7 @@ "nullthrows": "^1.1.1", "pretty-format": "^26.5.2", "promise": "^8.3.0", - "react-devtools-core": "^5.0.0", + "react-devtools-core": "^5.0.2", "react-refresh": "^0.14.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/react-native/react-native.config.js b/packages/react-native/react-native.config.js index 6a8394e8ac1823..64841ed37a7e0d 100644 --- a/packages/react-native/react-native.config.js +++ b/packages/react-native/react-native.config.js @@ -13,7 +13,6 @@ const android = require('@react-native-community/cli-platform-android'); const ios = require('@react-native-community/cli-platform-ios'); const { bundleCommand, - ramBundleCommand, startCommand, } = require('@react-native/community-cli-plugin'); @@ -49,7 +48,6 @@ module.exports = { ...ios.commands, ...android.commands, bundleCommand, - ramBundleCommand, startCommand, codegenCommand, ], diff --git a/packages/react-native/scripts/cocoapods/__tests__/codegen_utils-test.rb b/packages/react-native/scripts/cocoapods/__tests__/codegen_utils-test.rb index 194faddaa88bda..04c3c8674ee0a0 100644 --- a/packages/react-native/scripts/cocoapods/__tests__/codegen_utils-test.rb +++ b/packages/react-native/scripts/cocoapods/__tests__/codegen_utils-test.rb @@ -64,7 +64,7 @@ def testGenerateReactCodegenPodspec_whenItHasBeenAlreadyGenerated_doesNothing CodegenUtils.new().generate_react_codegen_podspec!(spec, codegen_output_dir, file_manager: FileMock) # Assert - assert_equal(Pod::UI.collected_messages, ["[Codegen] Skipping React-Codegen podspec generation."]) + assert_equal(Pod::UI.collected_messages, ["[Codegen] Skipping ReactCodegen podspec generation."]) assert_equal(Pathname.pwd_invocation_count, 0) assert_equal(Pod::Executable.executed_commands, []) assert_equal(Pod::Config.instance.installation_root.relative_path_from_invocation_count, 0) @@ -83,8 +83,8 @@ def testGenerateReactCodegenPodspec_whenItHasNotBeenAlreadyGenerated_generatesIt assert_equal(Pathname.pwd_invocation_count, 1) assert_equal(Pod::Config.instance.installation_root.relative_path_from_invocation_count, 1) assert_equal(Pod::Executable.executed_commands, [{ "command" => 'mkdir', "arguments" => ["-p", "~/app/ios/build"]}]) - assert_equal(Pod::UI.collected_messages, ["[Codegen] Generating ~/app/ios/build/React-Codegen.podspec.json"]) - assert_equal(FileMock.open_files_with_mode["~/app/ios/build/React-Codegen.podspec.json"], 'w') + assert_equal(Pod::UI.collected_messages, ["[Codegen] Generating ~/app/ios/build/ReactCodegen.podspec.json"]) + assert_equal(FileMock.open_files_with_mode["~/app/ios/build/ReactCodegen.podspec.json"], 'w') assert_equal(FileMock.open_files[0].collected_write, ['{"name":"Test Podspec"}']) assert_equal(FileMock.open_files[0].fsync_invocation_count, 1) @@ -108,7 +108,7 @@ def testGetReactCodegenSpec_whenFabricEnabledAndScriptPhases_generatesAPodspec # Assert assert_equal(podspec, get_podspec_fabric_and_script_phases("echo Test Script Phase")) - assert_equal(Pod::UI.collected_messages, ["[Codegen] Adding script_phases to React-Codegen."]) + assert_equal(Pod::UI.collected_messages, ["[Codegen] Adding script_phases to ReactCodegen."]) end def testGetReactCodegenSpec_whenUseFrameworksAndNewArch_generatesAPodspec @@ -337,7 +337,7 @@ def testUseReactCodegenDiscovery_whenParametersAreGood_executeCodegen # Arrange app_path = "~/app" computed_script = "echo TestScript" - codegen_spec = {"name" => "React-Codegen"} + codegen_spec = {"name" => "ReactCodegen"} codegen_utils_mock = CodegenUtilsMock.new( :react_codegen_script_phases => computed_script, @@ -370,7 +370,7 @@ def testUseReactCodegenDiscovery_whenParametersAreGood_executeCodegen }]) assert_equal(codegen_utils_mock.generate_react_codegen_spec_params, [{ :codegen_output_dir=>"build/generated/ios", - :react_codegen_spec=>{"name"=>"React-Codegen"} + :react_codegen_spec=>{"name"=>"ReactCodegen"} }]) assert_equal(Pod::Executable.executed_commands, [ { @@ -501,7 +501,7 @@ def test_assertCodegenFolderIsEmpty_whenItIsNotEmpty_itAborts def get_podspec_no_fabric_no_script spec = { - 'name' => "React-Codegen", + 'name' => "ReactCodegen", 'version' => "99.98.97", 'summary' => 'Temp pod for generated files for React Native', 'homepage' => 'https://facebook.com/', @@ -522,7 +522,7 @@ def get_podspec_no_fabric_no_script "\"$(PODS_ROOT)/RCT-Folly\"", "\"$(PODS_ROOT)/DoubleConversion\"", "\"$(PODS_ROOT)/fmt/include\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", "\"$(PODS_ROOT)/Headers/Private/React-Fabric\"", "\"$(PODS_ROOT)/Headers/Private/React-RCTFabric\"", "\"$(PODS_ROOT)/Headers/Private/Yoga\"", diff --git a/packages/react-native/scripts/cocoapods/__tests__/new_architecture-test.rb b/packages/react-native/scripts/cocoapods/__tests__/new_architecture-test.rb index a817fdfdedeac7..328a705b8dc758 100644 --- a/packages/react-native/scripts/cocoapods/__tests__/new_architecture-test.rb +++ b/packages/react-native/scripts/cocoapods/__tests__/new_architecture-test.rb @@ -161,7 +161,7 @@ def test_installModulesDependencies_whenNewArchEnabledAndNewArchAndNoSearchPaths { :dependency_name => "RCT-Folly", "version"=>"2024.01.01.00" }, { :dependency_name => "glog" }, { :dependency_name => "React-RCTFabric" }, - { :dependency_name => "React-Codegen" }, + { :dependency_name => "ReactCodegen" }, { :dependency_name => "RCTRequired" }, { :dependency_name => "RCTTypeSafety" }, { :dependency_name => "ReactCommon/turbomodule/bridging" }, @@ -184,7 +184,7 @@ def test_installModulesDependencies_whenNewArchDisabledAndSearchPathsAndCompiler # Arrange spec = SpecMock.new spec.compiler_flags = '' - other_flags = "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Codegen/React_Codegen.framework/Headers\"" + other_flags = "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCodegen/ReactCodegen.framework/Headers\"" spec.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => other_flags } @@ -203,7 +203,7 @@ def test_installModulesDependencies_whenNewArchDisabledAndSearchPathsAndCompiler { :dependency_name => "RCT-Folly", "version"=>"2024.01.01.00" }, { :dependency_name => "glog" }, { :dependency_name => "React-RCTFabric" }, - { :dependency_name => "React-Codegen" }, + { :dependency_name => "ReactCodegen" }, { :dependency_name => "RCTRequired" }, { :dependency_name => "RCTTypeSafety" }, { :dependency_name => "ReactCommon/turbomodule/bridging" }, @@ -419,10 +419,10 @@ def test_newArchEnabled_whenRCTNewArchEnabledIsSetTo0_returnFalse assert_false(is_enabled) end - def test_newArchEnabled_whenRCTNewArchEnabledIsNotSet_returnFalse + def test_newArchEnabled_whenRCTNewArchEnabledIsNotSet_returnTrue ENV["RCT_NEW_ARCH_ENABLED"] = nil is_enabled = NewArchitectureHelper.new_arch_enabled - assert_false(is_enabled) + assert_true(is_enabled) end diff --git a/packages/react-native/scripts/cocoapods/__tests__/utils-test.rb b/packages/react-native/scripts/cocoapods/__tests__/utils-test.rb index 2b25929fe32d62..d5089aae641939 100644 --- a/packages/react-native/scripts/cocoapods/__tests__/utils-test.rb +++ b/packages/react-native/scripts/cocoapods/__tests__/utils-test.rb @@ -764,7 +764,7 @@ def test_updateSearchPaths_whenUseFrameworks_addsSearchPaths first_target = prepare_target("FirstTarget") second_target = prepare_target("SecondTarget", nil, [ DependencyMock.new("RCT-Folly"), - DependencyMock.new("React-Codegen"), + DependencyMock.new("ReactCodegen"), DependencyMock.new("ReactCommon"), DependencyMock.new("React-RCTFabric"), DependencyMock.new("React-ImageManager"), @@ -798,7 +798,7 @@ def test_updateSearchPaths_whenUseFrameworks_addsSearchPaths if pod_name == "SecondTarget" target_installation_result.native_target.build_configurations.each do |config| received_search_path = config.build_settings["HEADER_SEARCH_PATHS"] - expected_Search_path = "$(inherited) \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/fmt/include\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Codegen/React_Codegen.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCommon/ReactCommon.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCommon/ReactCommon.framework/Headers/react/nativemodule/core\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-RCTFabric/RCTFabric.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers/react/renderer/components/view/platform/cxx\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-FabricImage/React_FabricImage.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Graphics/React_graphics.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Graphics/React_graphics.framework/Headers/react/renderer/graphics/platform/ios\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers/react/renderer/imagemanager/platform/ios\"" + expected_Search_path = "$(inherited) \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/fmt/include\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCodegen/ReactCodegen.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCommon/ReactCommon.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCommon/ReactCommon.framework/Headers/react/nativemodule/core\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-RCTFabric/RCTFabric.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers/react/renderer/components/view/platform/cxx\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-FabricImage/React_FabricImage.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Graphics/React_graphics.framework/Headers\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Graphics/React_graphics.framework/Headers/react/renderer/graphics/platform/ios\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_Fabric.framework/Headers/react/renderer/imagemanager/platform/ios\"" assert_equal(received_search_path, expected_Search_path) end else diff --git a/packages/react-native/scripts/cocoapods/codegen_utils.rb b/packages/react-native/scripts/cocoapods/codegen_utils.rb index ebdc01e9fef7ee..6669f729bbde3f 100644 --- a/packages/react-native/scripts/cocoapods/codegen_utils.rb +++ b/packages/react-native/scripts/cocoapods/codegen_utils.rb @@ -43,7 +43,7 @@ def generate_react_codegen_podspec!(spec, codegen_output_dir, file_manager: File # This podspec file should only be create once in the session/pod install. # This happens when multiple targets are calling use_react_native!. if @@REACT_CODEGEN_PODSPEC_GENERATED - Pod::UI.puts "[Codegen] Skipping React-Codegen podspec generation." + Pod::UI.puts "[Codegen] Skipping ReactCodegen podspec generation." return end @@ -51,7 +51,7 @@ def generate_react_codegen_podspec!(spec, codegen_output_dir, file_manager: File output_dir = "#{relative_installation_root}/#{codegen_output_dir}" Pod::Executable.execute_command("mkdir", ["-p", output_dir]); - podspec_path = file_manager.join(output_dir, 'React-Codegen.podspec.json') + podspec_path = file_manager.join(output_dir, 'ReactCodegen.podspec.json') Pod::UI.puts "[Codegen] Generating #{podspec_path}" file_manager.open(podspec_path, 'w') do |f| @@ -62,7 +62,7 @@ def generate_react_codegen_podspec!(spec, codegen_output_dir, file_manager: File @@REACT_CODEGEN_PODSPEC_GENERATED = true end - # It generates the podspec object that represents the `React-Codegen.podspec` file + # It generates the podspec object that represents the `ReactCodegen.podspec` file # # Parameters # - package_json_file: the path to the `package.json`, required to extract the proper React Native version @@ -81,7 +81,7 @@ def get_react_codegen_spec(package_json_file, folly_version: get_folly_config()[ "\"$(PODS_ROOT)/RCT-Folly\"", "\"$(PODS_ROOT)/DoubleConversion\"", "\"$(PODS_ROOT)/fmt/include\"", - "\"${PODS_ROOT}/Headers/Public/React-Codegen/react/renderer/components\"", + "\"${PODS_ROOT}/Headers/Public/ReactCodegen/react/renderer/components\"", "\"$(PODS_ROOT)/Headers/Private/React-Fabric\"", "\"$(PODS_ROOT)/Headers/Private/React-RCTFabric\"", "\"$(PODS_ROOT)/Headers/Private/Yoga\"", @@ -108,7 +108,7 @@ def get_react_codegen_spec(package_json_file, folly_version: get_folly_config()[ end spec = { - 'name' => "React-Codegen", + 'name' => "ReactCodegen", 'version' => version, 'summary' => 'Temp pod for generated files for React Native', 'homepage' => 'https://facebook.com/', @@ -156,7 +156,7 @@ def get_react_codegen_spec(package_json_file, folly_version: get_folly_config()[ end if script_phases - Pod::UI.puts "[Codegen] Adding script_phases to React-Codegen." + Pod::UI.puts "[Codegen] Adding script_phases to ReactCodegen." spec[:'script_phases'] = script_phases end @@ -298,7 +298,7 @@ def use_react_native_codegen_discovery!( Pod::UI.warn '[Codegen] warn: using experimental new codegen integration' relative_installation_root = Pod::Config.instance.installation_root.relative_path_from(Pathname.pwd) - # Generate React-Codegen podspec here to add the script phases. + # Generate ReactCodegen podspec here to add the script phases. script_phases = codegen_utils.get_react_codegen_script_phases( app_path, :fabric_enabled => fabric_enabled, diff --git a/packages/react-native/scripts/cocoapods/new_architecture.rb b/packages/react-native/scripts/cocoapods/new_architecture.rb index ebf0d418a7ecbb..2f3212a2ec411e 100644 --- a/packages/react-native/scripts/cocoapods/new_architecture.rb +++ b/packages/react-native/scripts/cocoapods/new_architecture.rb @@ -114,7 +114,7 @@ def self.install_modules_dependencies(spec, new_arch_enabled, folly_version = ge ReactNativePodsUtils.add_flag_to_map_with_inheritance(current_config, "OTHER_CPLUSPLUSFLAGS", self.computeFlags(new_arch_enabled)) spec.dependency "React-RCTFabric" # This is for Fabric Component - spec.dependency "React-Codegen" + spec.dependency "ReactCodegen" spec.dependency "RCTRequired" spec.dependency "RCTTypeSafety" @@ -186,6 +186,6 @@ def self.compute_new_arch_enabled(new_arch_enabled, react_native_version) end def self.new_arch_enabled - return ENV["RCT_NEW_ARCH_ENABLED"] == "1" + return ENV["RCT_NEW_ARCH_ENABLED"] == nil || ENV["RCT_NEW_ARCH_ENABLED"] == "1" end end diff --git a/packages/react-native/scripts/cocoapods/utils.rb b/packages/react-native/scripts/cocoapods/utils.rb index 6df005cee4fc1e..ffe6a70c7e95ca 100644 --- a/packages/react-native/scripts/cocoapods/utils.rb +++ b/packages/react-native/scripts/cocoapods/utils.rb @@ -529,9 +529,9 @@ def self.set_rctfolly_search_paths(target_installation_result) end def self.set_codegen_search_paths(target_installation_result) - header_search_paths = ReactNativePodsUtils.create_header_search_path_for_frameworks("PODS_CONFIGURATION_BUILD_DIR", "React-Codegen", "React_Codegen", []) + header_search_paths = ReactNativePodsUtils.create_header_search_path_for_frameworks("PODS_CONFIGURATION_BUILD_DIR", "ReactCodegen", "ReactCodegen", []) .map { |search_path| "\"#{search_path}\"" } - ReactNativePodsUtils.update_header_paths_if_depends_on(target_installation_result, "React-Codegen", header_search_paths) + ReactNativePodsUtils.update_header_paths_if_depends_on(target_installation_result, "ReactCodegen", header_search_paths) end def self.set_reactcommon_searchpaths(target_installation_result) @@ -564,7 +564,7 @@ def self.react_native_pods "RCTRequired", "RCTTypeSafety", "React", - "React-Codegen", + "ReactCodegen", "React-Core", "React-CoreModules", "React-Fabric", diff --git a/packages/react-native/scripts/codegen/generate-artifacts-executor.js b/packages/react-native/scripts/codegen/generate-artifacts-executor.js index 92434047d5a6a5..df3c1e6ac0306d 100644 --- a/packages/react-native/scripts/codegen/generate-artifacts-executor.js +++ b/packages/react-native/scripts/codegen/generate-artifacts-executor.js @@ -34,18 +34,19 @@ const REACT_NATIVE_REPOSITORY_ROOT = path.join( ); const REACT_NATIVE_PACKAGE_ROOT_FOLDER = path.join(__dirname, '..', '..'); const CODEGEN_REPO_PATH = `${REACT_NATIVE_REPOSITORY_ROOT}/packages/react-native-codegen`; +const RNCORE_CONFIGS = { + ios: path.join(REACT_NATIVE_PACKAGE_ROOT_FOLDER, 'ReactCommon'), + android: path.join( + REACT_NATIVE_PACKAGE_ROOT_FOLDER, + 'ReactAndroid', + 'build', + 'generated', + 'source', + 'codegen', + ), +}; const CORE_LIBRARIES_WITH_OUTPUT_FOLDER = { - rncore: { - ios: path.join(REACT_NATIVE_PACKAGE_ROOT_FOLDER, 'ReactCommon'), - android: path.join( - REACT_NATIVE_PACKAGE_ROOT_FOLDER, - 'ReactAndroid', - 'build', - 'generated', - 'source', - 'codegen', - ), - }, + rncore: RNCORE_CONFIGS, FBReactNativeSpec: { ios: null, android: path.join( @@ -283,11 +284,7 @@ function findLibrariesFromReactNativeConfig(projectRoot) { return []; } - return extractLibrariesFromJSON( - configFile, - configFile.name, - codegenConfigFileDir, - ); + return extractLibrariesFromJSON(configFile, codegenConfigFileDir); }); } @@ -418,20 +415,47 @@ function generateSchemaInfo(library, platform) { }; } -function generateCode(outputPath, schemaInfo, includesGeneratedCode, platform) { - const tmpDir = fs.mkdtempSync( - path.join(os.tmpdir(), schemaInfo.library.config.name), +function shouldSkipGenerationForRncore(schemaInfo, platform) { + if (platform !== 'ios' || schemaInfo.library.config.name !== 'rncore') { + return false; + } + const rncoreOutputPath = path.join( + RNCORE_CONFIGS.ios, + 'react', + 'renderer', + 'components', + 'rncore', + ); + const rncoreAbsolutePath = path.resolve(rncoreOutputPath); + return ( + rncoreAbsolutePath.includes('node_modules') && + fs.existsSync(rncoreAbsolutePath) && + fs.readdirSync(rncoreAbsolutePath).length > 0 ); +} + +function generateCode(outputPath, schemaInfo, includesGeneratedCode, platform) { + if (shouldSkipGenerationForRncore(schemaInfo, platform)) { + console.log( + '[Codegen - rncore] Skipping iOS code generation for rncore as it has been generated already.', + ); + return; + } + + const libraryName = schemaInfo.library.config.name; + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), libraryName)); const tmpOutputDir = path.join(tmpDir, 'out'); fs.mkdirSync(tmpOutputDir, {recursive: true}); - console.log(`[Codegen] Generating Native Code for ${platform}`); + console.log( + `[Codegen] Generating Native Code for ${libraryName} - ${platform}`, + ); const useLocalIncludePaths = includesGeneratedCode; generateSpecsCLIExecutor.generateSpecFromInMemorySchema( platform, schemaInfo.schema, tmpOutputDir, - schemaInfo.library.config.name, + libraryName, 'com.facebook.fbreact.specs', schemaInfo.library.config.type, useLocalIncludePaths, @@ -439,13 +463,9 @@ function generateCode(outputPath, schemaInfo, includesGeneratedCode, platform) { // Finally, copy artifacts to the final output directory. const outputDir = - reactNativeCoreLibraryOutputPath( - schemaInfo.library.config.name, - platform, - ) ?? outputPath; + reactNativeCoreLibraryOutputPath(libraryName, platform) ?? outputPath; fs.mkdirSync(outputDir, {recursive: true}); - // TODO: Fix this. This will not work on Windows. - execSync(`cp -R ${tmpOutputDir}/* "${outputDir}"`); + fs.cpSync(tmpOutputDir, outputDir, {recursive: true}); console.log(`[Codegen] Generated artifacts: ${outputDir}`); } @@ -598,6 +618,22 @@ function cleanupEmptyFilesAndFolders(filepath) { } } +function generateRNCoreComponentsIOS(projectRoot /*: string */) /*: void*/ { + const ios = 'ios'; + buildCodegenIfNeeded(); + const pkgJson = readPkgJsonInDirectory(projectRoot); + const rncoreLib = findProjectRootLibraries(pkgJson, projectRoot).filter( + library => library.config.name === 'rncore', + )[0]; + if (!rncoreLib) { + throw new Error( + "[Codegen] Can't find rncore library. Failed to generate rncore artifacts", + ); + } + const rncoreSchemaInfo = generateSchemaInfo(rncoreLib, ios); + generateCode('', rncoreSchemaInfo, false, ios); +} + // Execute /** @@ -691,7 +727,8 @@ function execute(projectRoot, targetPlatform, baseOutputPath) { } module.exports = { - execute: execute, + execute, + generateRNCoreComponentsIOS, // exported for testing purposes only: _extractLibrariesFromJSON: extractLibrariesFromJSON, _cleanupEmptyFilesAndFolders: cleanupEmptyFilesAndFolders, diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index ef91f0f6e352c5..bec7fcf7f23477 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -8,103 +8,118 @@ * @format */ +/* eslint sort-keys: 'error' */ + import type {FeatureFlagDefinitions} from './types'; -const definitions: FeatureFlagDefinitions = { +// These flags are only used in tests for the feature flags system +const testDefinitions: FeatureFlagDefinitions = { common: { - // This is only used in unit tests for the feature flags system. commonTestFlag: { + defaultValue: false, description: 'Common flag for testing. Do NOT modify.', + }, + }, + jsOnly: { + jsOnlyTestFlag: { defaultValue: false, + description: 'JS-only flag for testing. Do NOT modify.', }, + }, +}; + +const definitions: FeatureFlagDefinitions = { + common: { + ...testDefinitions.common, + batchRenderingUpdatesInEventLoop: { + defaultValue: false, + description: + 'When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop.', + }, enableBackgroundExecutor: { + defaultValue: false, description: 'Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used).', - defaultValue: false, }, - useModernRuntimeScheduler: { + enableCustomDrawOrderFabric: { + defaultValue: false, description: - 'When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread.', + 'When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture).', + }, + enableFixForClippedSubviewsCrash: { defaultValue: false, + description: + 'Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix', }, enableMicrotasks: { + defaultValue: false, description: 'Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution).', - defaultValue: false, }, - batchRenderingUpdatesInEventLoop: { - description: - 'When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop.', + enableMountHooksAndroid: { defaultValue: false, - }, - enableSpannableBuildingUnification: { description: - 'Uses new, deduplicated logic for constructing Android Spannables from text fragments', - defaultValue: false, + 'Enables the notification of mount operations to mount hooks on Android.', }, - enableCustomDrawOrderFabric: { - description: - 'When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture).', + enableSpannableBuildingUnification: { defaultValue: false, - }, - enableFixForClippedSubviewsCrash: { description: - 'Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix', - defaultValue: false, + 'Uses new, deduplicated logic for constructing Android Spannables from text fragments', }, inspectorEnableCxxInspectorPackagerConnection: { + defaultValue: false, description: 'Flag determining if the C++ implementation of InspectorPackagerConnection should be used instead of the per-platform one. This flag is global and should not be changed across React Host lifetimes.', - defaultValue: false, }, inspectorEnableModernCDPRegistry: { + defaultValue: false, description: 'Flag determining if the modern CDP backend should be enabled. This flag is global and should not be changed across React Host lifetimes.', + }, + useModernRuntimeScheduler: { defaultValue: false, + description: + 'When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread.', }, }, jsOnly: { - // This is only used in unit tests for the feature flags system. - jsOnlyTestFlag: { - description: 'JS-only flag for testing. Do NOT modify.', - defaultValue: false, - }, + ...testDefinitions.jsOnly, - isLayoutAnimationEnabled: { - description: - 'Function used to enable / disabled Layout Animations in React Native.', - defaultValue: true, - }, animatedShouldDebounceQueueFlush: { + defaultValue: false, description: 'Enables an experimental flush-queue debouncing in Animated.js.', - defaultValue: false, }, animatedShouldUseSingleOp: { + defaultValue: false, description: 'Enables an experimental mega-operation for Animated.js that replaces many calls to native with a single call into native, to reduce JSI/JNI traffic.', - defaultValue: false, }, enableAccessToHostTreeInFabric: { + defaultValue: false, description: 'Enables access to the host tree in Fabric using DOM-compatible APIs.', - defaultValue: false, + }, + isLayoutAnimationEnabled: { + defaultValue: true, + description: + 'Function used to enable / disabled Layout Animations in React Native.', }, shouldUseAnimatedObjectForTransform: { + defaultValue: false, description: 'Enables use of AnimatedObject for animating transform values.', - defaultValue: false, - }, - shouldUseSetNativePropsInFabric: { - description: 'Enables use of setNativeProps in JS driven animations.', - defaultValue: true, }, shouldUseRemoveClippedSubviewsAsDefaultOnIOS: { + defaultValue: false, description: 'removeClippedSubviews prop will be used as the default in FlatList on iOS to match Android', - defaultValue: false, + }, + shouldUseSetNativePropsInFabric: { + defaultValue: true, + description: 'Enables use of setNativeProps in JS driven animations.', }, }, }; diff --git a/packages/react-native/scripts/featureflags/generateFiles.js b/packages/react-native/scripts/featureflags/generateFiles.js index f03df2163e6496..8f155b1350aeb5 100644 --- a/packages/react-native/scripts/featureflags/generateFiles.js +++ b/packages/react-native/scripts/featureflags/generateFiles.js @@ -14,6 +14,7 @@ import generateAndroidModules from './generateAndroidModules'; import generateCommonCxxModules from './generateCommonCxxModules'; import generateJavaScriptModules from './generateJavaScriptModules'; import fs from 'fs'; +import path from 'path'; export default function generateFiles( generatorConfig: GeneratorConfig, @@ -65,6 +66,7 @@ export default function generateFiles( } for (const [modulePath, moduleContents] of Object.entries(generatedFiles)) { - fs.writeFileSync(modulePath, moduleContents, 'utf8'); + fs.mkdirSync(path.dirname(modulePath), {recursive: true}); + fs.writeFileSync(modulePath, moduleContents, {encoding: 'utf8'}); } } diff --git a/packages/react-native/scripts/featureflags/generateJavaScriptModules.js b/packages/react-native/scripts/featureflags/generateJavaScriptModules.js index 4fc7d30e15530a..f005295478297a 100644 --- a/packages/react-native/scripts/featureflags/generateJavaScriptModules.js +++ b/packages/react-native/scripts/featureflags/generateJavaScriptModules.js @@ -25,7 +25,7 @@ export default function generateCommonCxxModules( return { [path.join(jsPath, 'ReactNativeFeatureFlags.js')]: ReactNativeFeatureFlagsJS(featureFlagDefinitions), - [path.join(jsPath, 'NativeReactNativeFeatureFlags.js')]: + [path.join(jsPath, 'specs', 'NativeReactNativeFeatureFlags.js')]: NativeReactNativeFeatureFlagsJS(featureFlagDefinitions), [path.join(commonNativeModuleCxxPath, 'NativeReactNativeFeatureFlags.h')]: NativeReactNativeFeatureFlagsH(featureFlagDefinitions), diff --git a/packages/react-native/scripts/featureflags/templates/common-cxx/ReactNativeFeatureFlags.h-template.js b/packages/react-native/scripts/featureflags/templates/common-cxx/ReactNativeFeatureFlags.h-template.js index 5e6e896560e637..4397942cc45c6f 100644 --- a/packages/react-native/scripts/featureflags/templates/common-cxx/ReactNativeFeatureFlags.h-template.js +++ b/packages/react-native/scripts/featureflags/templates/common-cxx/ReactNativeFeatureFlags.h-template.js @@ -31,6 +31,10 @@ ${DO_NOT_MODIFY_COMMENT} #include #include +#ifndef RN_EXPORT +#define RN_EXPORT __attribute__((visibility("default"))) +#endif + namespace facebook::react { /** @@ -47,7 +51,7 @@ ${Object.entries(definitions.common) ` /** * ${flagConfig.description} */ - static ${getCxxTypeFromDefaultValue(flagConfig.defaultValue)} ${flagName}();`, + RN_EXPORT static ${getCxxTypeFromDefaultValue(flagConfig.defaultValue)} ${flagName}();`, ) .join('\n\n')} @@ -69,7 +73,7 @@ ${Object.entries(definitions.common) * std::make_unique()); * \`\`\` */ - static void override( + RN_EXPORT static void override( std::unique_ptr provider); /** @@ -84,7 +88,7 @@ ${Object.entries(definitions.common) * call \`dangerouslyReset\` after destroying the runtime and \`override\` again * before initializing the new one. */ - static void dangerouslyReset(); + RN_EXPORT static void dangerouslyReset(); private: ReactNativeFeatureFlags() = delete; diff --git a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.cpp-template.js b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.cpp-template.js index 13a28a72cecbb9..74be22c0dc43bd 100644 --- a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.cpp-template.js +++ b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.cpp-template.js @@ -28,7 +28,9 @@ ${DO_NOT_MODIFY_COMMENT} #include "NativeReactNativeFeatureFlags.h" #include +#ifdef RN_DISABLE_OSS_PLUGIN_HEADER #include "Plugins.h" +#endif std::shared_ptr NativeReactNativeFeatureFlagsModuleProvider( diff --git a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.h-template.js b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.h-template.js index 492639ed9d3d26..0b2e7e97c791b2 100644 --- a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.h-template.js +++ b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.h-template.js @@ -27,14 +27,19 @@ ${DO_NOT_MODIFY_COMMENT} #pragma once +#if __has_include("rncoreJSI.h") // Cmake headers on Android +#include "rncoreJSI.h" +#elif __has_include("FBReactNativeSpecJSI.h") // CocoaPod headers on Apple +#include "FBReactNativeSpecJSI.h" +#else #include +#endif namespace facebook::react { class NativeReactNativeFeatureFlags : public NativeReactNativeFeatureFlagsCxxSpec< - NativeReactNativeFeatureFlags>, - std::enable_shared_from_this { + NativeReactNativeFeatureFlags> { public: NativeReactNativeFeatureFlags(std::shared_ptr jsInvoker); diff --git a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.js-template.js b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.js-template.js index 9c9e557879dbe1..0d6a1ca64515a9 100644 --- a/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.js-template.js +++ b/packages/react-native/scripts/featureflags/templates/js/NativeReactNativeFeatureFlags.js-template.js @@ -26,9 +26,9 @@ export default function (definitions: FeatureFlagDefinitions): string { ${DO_NOT_MODIFY_COMMENT} -import type {TurboModule} from '../../../Libraries/TurboModule/RCTExport'; +import type {TurboModule} from '../../../../Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from '../../../Libraries/TurboModule/TurboModuleRegistry'; +import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboModuleRegistry'; export interface Spec extends TurboModule { ${Object.entries(definitions.common) diff --git a/packages/react-native/scripts/prepack.js b/packages/react-native/scripts/prepack.js new file mode 100644 index 00000000000000..694e891117dd62 --- /dev/null +++ b/packages/react-native/scripts/prepack.js @@ -0,0 +1,25 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + * @oncall react_native + */ + +const { + generateRNCoreComponentsIOS, +} = require('./codegen/generate-artifacts-executor'); +const fs = require('fs'); + +function main() { + console.info('[Prepack] Copying README.md'); + fs.copyFileSync('../../README.md', './README.md'); + generateRNCoreComponentsIOS('.'); +} + +if (require.main === module) { + main(); +} diff --git a/packages/react-native/scripts/react_native_pods.rb b/packages/react-native/scripts/react_native_pods.rb index 0943e9029e9dc5..e60920404de575 100644 --- a/packages/react-native/scripts/react_native_pods.rb +++ b/packages/react-native/scripts/react_native_pods.rb @@ -125,6 +125,8 @@ def use_react_native! ( pod 'React-debug', :path => "#{prefix}/ReactCommon/react/debug" pod 'React-utils', :path => "#{prefix}/ReactCommon/react/utils" pod 'React-featureflags', :path => "#{prefix}/ReactCommon/react/featureflags" + pod 'React-featureflagsnativemodule', :path => "#{prefix}/ReactCommon/react/nativemodule/featureflags" + pod 'React-microtasksnativemodule', :path => "#{prefix}/ReactCommon/react/nativemodule/microtasks" pod 'React-Mapbuffer', :path => "#{prefix}/ReactCommon" pod 'React-jserrorhandler', :path => "#{prefix}/ReactCommon/jserrorhandler" pod 'React-nativeconfig', :path => "#{prefix}/ReactCommon" @@ -169,7 +171,7 @@ def use_react_native! ( :folly_version => folly_config[:version] ) - pod 'React-Codegen', :path => $CODEGEN_OUTPUT_DIR, :modular_headers => true + pod 'ReactCodegen', :path => $CODEGEN_OUTPUT_DIR, :modular_headers => true # Always need fabric to access the RCTSurfacePresenterBridgeAdapter which allow to enable the RuntimeScheduler # If the New Arch is turned off, we will use the Old Renderer, though. @@ -286,7 +288,7 @@ def react_native_post_install( ReactNativePodsUtils.set_use_hermes_build_setting(installer, hermes_enabled) ReactNativePodsUtils.set_node_modules_user_settings(installer, react_native_path) ReactNativePodsUtils.set_ccache_compiler_and_linker_build_settings(installer, react_native_path, ccache_enabled) - ReactNativePodsUtils.apply_xcode_15_patch(installer) + ReactNativePodsUtils.apply_xcode_15_patch(installer) ReactNativePodsUtils.updateOSDeploymentTarget(installer) ReactNativePodsUtils.set_dynamic_frameworks_flags(installer) ReactNativePodsUtils.add_ndebug_flag_to_pods_in_release(installer) diff --git a/packages/react-native/sdks/hermes-engine/hermes-engine.podspec b/packages/react-native/sdks/hermes-engine/hermes-engine.podspec index 335004f1e87e3d..32d71f78fd7ada 100644 --- a/packages/react-native/sdks/hermes-engine/hermes-engine.podspec +++ b/packages/react-native/sdks/hermes-engine/hermes-engine.podspec @@ -79,6 +79,12 @@ Pod::Spec.new do |spec| ss.header_dir = 'hermes' end + spec.subspec 'cdp' do |ss| + ss.source_files = '' + ss.public_header_files = 'API/hermes/cdp/*.h' + ss.header_dir = 'hermes/cdp' + end + spec.subspec 'inspector' do |ss| ss.source_files = '' ss.public_header_files = 'API/hermes/inspector/*.h' diff --git a/packages/react-native/sdks/hermes-engine/hermes-utils.rb b/packages/react-native/sdks/hermes-engine/hermes-utils.rb index 8c2f4f6c665a83..c0c7613192ebd8 100644 --- a/packages/react-native/sdks/hermes-engine/hermes-utils.rb +++ b/packages/react-native/sdks/hermes-engine/hermes-utils.rb @@ -7,6 +7,7 @@ require 'rexml/document' HERMES_GITHUB_URL = "https://github.com/facebook/hermes.git" +ENV_BUILD_FROM_SOURCE = "RCT_BUILD_HERMES_FROM_SOURCE" module HermesEngineSourceType LOCAL_PREBUILT_TARBALL = :local_prebuilt_tarball @@ -30,7 +31,7 @@ def HermesEngineSourceType.isFromSource(source_type) # - To use a specific tarball, install the dependencies with: # `HERMES_ENGINE_TARBALL_PATH= bundle exec pod install` # - To force a build from source, install the dependencies with: -# `BUILD_FROM_SOURCE=true bundle exec pod install` +# `RCT_BUILD_HERMES_FROM_SOURCE=true bundle exec pod install` # If none of the two are provided, Cocoapods will check whether there is a tarball for the current version # (either release or nightly). If not, it will fall back to building from source (the latest commit on main). # @@ -85,11 +86,11 @@ def hermes_commit_envvar_defined() end def force_build_from_tag(react_native_path) - return ENV['BUILD_FROM_SOURCE'] === 'true' && File.exist?(hermestag_file(react_native_path)) + return ENV[ENV_BUILD_FROM_SOURCE] === 'true' && File.exist?(hermestag_file(react_native_path)) end def force_build_from_main(react_native_path) - return ENV['BUILD_FROM_SOURCE'] === 'true' && !File.exist?(hermestag_file(react_native_path)) + return ENV[ENV_BUILD_FROM_SOURCE] === 'true' && !File.exist?(hermestag_file(react_native_path)) end def release_artifact_exists(version) diff --git a/packages/react-native/sdks/hermes-engine/utils/build-apple-framework.sh b/packages/react-native/sdks/hermes-engine/utils/build-apple-framework.sh index a4fe7d79024cb4..d3af54bb9cedb9 100755 --- a/packages/react-native/sdks/hermes-engine/utils/build-apple-framework.sh +++ b/packages/react-native/sdks/hermes-engine/utils/build-apple-framework.sh @@ -135,6 +135,9 @@ function build_apple_framework { mkdir -p destroot/include/hermes cp API/hermes/*.h destroot/include/hermes + mkdir -p destroot/include/hermes/cdp + cp API/hermes/cdp/*.h destroot/include/hermes/cdp + mkdir -p destroot/include/hermes/inspector cp API/hermes/inspector/*.h destroot/include/hermes/inspector @@ -162,6 +165,9 @@ function prepare_dest_root_for_ci { mkdir -p destroot/include/hermes cp API/hermes/*.h destroot/include/hermes + mkdir -p destroot/include/hermes/cdp + cp API/hermes/cdp/*.h destroot/include/hermes/cdp + mkdir -p destroot/include/hermes/inspector cp API/hermes/inspector/*.h destroot/include/hermes/inspector diff --git a/packages/react-native/src/.npmignore b/packages/react-native/src/.npmignore new file mode 100644 index 00000000000000..c912533dd7d2dd --- /dev/null +++ b/packages/react-native/src/.npmignore @@ -0,0 +1 @@ +__tests__ diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 214dc80c030845..3d68cd7572a3d8 100644 --- a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<7c83d5613c3be517efe48378e6356e79>> + * @generated SignedSource<> * @flow strict-local */ @@ -27,13 +27,13 @@ import { export type ReactNativeFeatureFlagsJsOnly = { jsOnlyTestFlag: Getter, - isLayoutAnimationEnabled: Getter, animatedShouldDebounceQueueFlush: Getter, animatedShouldUseSingleOp: Getter, enableAccessToHostTreeInFabric: Getter, + isLayoutAnimationEnabled: Getter, shouldUseAnimatedObjectForTransform: Getter, - shouldUseSetNativePropsInFabric: Getter, shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter, + shouldUseSetNativePropsInFabric: Getter, }; export type ReactNativeFeatureFlagsJsOnlyOverrides = Partial; @@ -41,15 +41,16 @@ export type ReactNativeFeatureFlagsJsOnlyOverrides = Partial, - enableBackgroundExecutor: Getter, - useModernRuntimeScheduler: Getter, - enableMicrotasks: Getter, batchRenderingUpdatesInEventLoop: Getter, - enableSpannableBuildingUnification: Getter, + enableBackgroundExecutor: Getter, enableCustomDrawOrderFabric: Getter, enableFixForClippedSubviewsCrash: Getter, + enableMicrotasks: Getter, + enableMountHooksAndroid: Getter, + enableSpannableBuildingUnification: Getter, inspectorEnableCxxInspectorPackagerConnection: Getter, inspectorEnableModernCDPRegistry: Getter, + useModernRuntimeScheduler: Getter, } /** @@ -57,11 +58,6 @@ export type ReactNativeFeatureFlags = { */ export const jsOnlyTestFlag: Getter = createJavaScriptFlagGetter('jsOnlyTestFlag', false); -/** - * Function used to enable / disabled Layout Animations in React Native. - */ -export const isLayoutAnimationEnabled: Getter = createJavaScriptFlagGetter('isLayoutAnimationEnabled', true); - /** * Enables an experimental flush-queue debouncing in Animated.js. */ @@ -78,52 +74,57 @@ export const animatedShouldUseSingleOp: Getter = createJavaScriptFlagGe export const enableAccessToHostTreeInFabric: Getter = createJavaScriptFlagGetter('enableAccessToHostTreeInFabric', false); /** - * Enables use of AnimatedObject for animating transform values. + * Function used to enable / disabled Layout Animations in React Native. */ -export const shouldUseAnimatedObjectForTransform: Getter = createJavaScriptFlagGetter('shouldUseAnimatedObjectForTransform', false); +export const isLayoutAnimationEnabled: Getter = createJavaScriptFlagGetter('isLayoutAnimationEnabled', true); /** - * Enables use of setNativeProps in JS driven animations. + * Enables use of AnimatedObject for animating transform values. */ -export const shouldUseSetNativePropsInFabric: Getter = createJavaScriptFlagGetter('shouldUseSetNativePropsInFabric', true); +export const shouldUseAnimatedObjectForTransform: Getter = createJavaScriptFlagGetter('shouldUseAnimatedObjectForTransform', false); /** * removeClippedSubviews prop will be used as the default in FlatList on iOS to match Android */ export const shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter = createJavaScriptFlagGetter('shouldUseRemoveClippedSubviewsAsDefaultOnIOS', false); +/** + * Enables use of setNativeProps in JS driven animations. + */ +export const shouldUseSetNativePropsInFabric: Getter = createJavaScriptFlagGetter('shouldUseSetNativePropsInFabric', true); + /** * Common flag for testing. Do NOT modify. */ export const commonTestFlag: Getter = createNativeFlagGetter('commonTestFlag', false); +/** + * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. + */ +export const batchRenderingUpdatesInEventLoop: Getter = createNativeFlagGetter('batchRenderingUpdatesInEventLoop', false); /** * Enables the use of a background executor to compute layout and commit updates on Fabric (this system is deprecated and should not be used). */ export const enableBackgroundExecutor: Getter = createNativeFlagGetter('enableBackgroundExecutor', false); /** - * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). */ -export const useModernRuntimeScheduler: Getter = createNativeFlagGetter('useModernRuntimeScheduler', false); +export const enableCustomDrawOrderFabric: Getter = createNativeFlagGetter('enableCustomDrawOrderFabric', false); +/** + * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix + */ +export const enableFixForClippedSubviewsCrash: Getter = createNativeFlagGetter('enableFixForClippedSubviewsCrash', false); /** * Enables the use of microtasks in Hermes (scheduling) and RuntimeScheduler (execution). */ export const enableMicrotasks: Getter = createNativeFlagGetter('enableMicrotasks', false); /** - * When enabled, the RuntimeScheduler processing the event loop will batch all rendering updates and dispatch them together at the end of each iteration of the loop. + * Enables the notification of mount operations to mount hooks on Android. */ -export const batchRenderingUpdatesInEventLoop: Getter = createNativeFlagGetter('batchRenderingUpdatesInEventLoop', false); +export const enableMountHooksAndroid: Getter = createNativeFlagGetter('enableMountHooksAndroid', false); /** * Uses new, deduplicated logic for constructing Android Spannables from text fragments */ export const enableSpannableBuildingUnification: Getter = createNativeFlagGetter('enableSpannableBuildingUnification', false); -/** - * When enabled, Fabric will use customDrawOrder in ReactViewGroup (similar to old architecture). - */ -export const enableCustomDrawOrderFabric: Getter = createNativeFlagGetter('enableCustomDrawOrderFabric', false); -/** - * Attempt at fixing a crash related to subview clipping on Android. This is a kill switch for the fix - */ -export const enableFixForClippedSubviewsCrash: Getter = createNativeFlagGetter('enableFixForClippedSubviewsCrash', false); /** * Flag determining if the C++ implementation of InspectorPackagerConnection should be used instead of the per-platform one. This flag is global and should not be changed across React Host lifetimes. */ @@ -132,6 +133,10 @@ export const inspectorEnableCxxInspectorPackagerConnection: Getter = cr * Flag determining if the modern CDP backend should be enabled. This flag is global and should not be changed across React Host lifetimes. */ export const inspectorEnableModernCDPRegistry: Getter = createNativeFlagGetter('inspectorEnableModernCDPRegistry', false); +/** + * When enabled, it uses the modern fork of RuntimeScheduler that allows scheduling tasks with priorities from any thread. + */ +export const useModernRuntimeScheduler: Getter = createNativeFlagGetter('useModernRuntimeScheduler', false); /** * Overrides the feature flags with the provided methods. diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlagsBase.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlagsBase.js index a0d7be5da25cd2..61d8266b9551a8 100644 --- a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlagsBase.js +++ b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlagsBase.js @@ -13,7 +13,7 @@ import type { ReactNativeFeatureFlagsJsOnlyOverrides, } from './ReactNativeFeatureFlags'; -import NativeReactNativeFeatureFlags from './NativeReactNativeFeatureFlags'; +import NativeReactNativeFeatureFlags from './specs/NativeReactNativeFeatureFlags'; const accessedFeatureFlags: Set = new Set(); let overrides: ?ReactNativeFeatureFlagsJsOnlyOverrides; @@ -29,7 +29,6 @@ function createGetter( return () => { if (cachedValue == null) { - accessedFeatureFlags.add(configName); cachedValue = customValueGetter() ?? defaultValue; } return cachedValue; @@ -44,7 +43,10 @@ export function createJavaScriptFlagGetter< ): Getter> { return createGetter( configName, - () => overrides?.[configName]?.(), + () => { + accessedFeatureFlags.add(configName); + return overrides?.[configName]?.(); + }, defaultValue, ); } @@ -57,7 +59,13 @@ export function createNativeFlagGetter>( ): Getter>> { return createGetter( configName, - () => NativeReactNativeFeatureFlags?.[configName]?.(), + () => { + const valueFromNative = NativeReactNativeFeatureFlags?.[configName]?.(); + if (valueFromNative == null) { + logUnavailableNativeModuleError(configName); + } + return valueFromNative; + }, defaultValue, ); } @@ -82,3 +90,14 @@ export function setOverrides( overrides = newOverrides; } + +const reportedConfigNames: Set = new Set(); + +function logUnavailableNativeModuleError(configName: string): void { + if (!reportedConfigNames.has(configName)) { + reportedConfigNames.add(configName); + console.error( + `Could not access feature flag '${configName}' because native module method was not available`, + ); + } +} diff --git a/packages/react-native/src/private/featureflags/__tests__/ReactNativeFeatureFlags-test.js b/packages/react-native/src/private/featureflags/__tests__/ReactNativeFeatureFlags-test.js index 13264b6974bcf2..0d69a1afc3a9ba 100644 --- a/packages/react-native/src/private/featureflags/__tests__/ReactNativeFeatureFlags-test.js +++ b/packages/react-native/src/private/featureflags/__tests__/ReactNativeFeatureFlags-test.js @@ -12,17 +12,39 @@ describe('ReactNativeFeatureFlags', () => { beforeEach(() => { jest.resetModules(); + jest.restoreAllMocks(); + jest.spyOn(console, 'error').mockImplementation(() => {}); }); - it('should provide default values for common flags if the native module is NOT available', () => { + it('should provide default values for common flags and log an error if the native module is NOT available', () => { const ReactNativeFeatureFlags = require('../ReactNativeFeatureFlags'); expect(ReactNativeFeatureFlags.commonTestFlag()).toBe(false); + + expect(console.error).toHaveBeenCalledTimes(1); + expect(console.error).toHaveBeenCalledWith( + "Could not access feature flag 'commonTestFlag' because native module method was not available", + ); + }); + + it('should provide default values for common flags and log an error if the method in the native module is NOT available', () => { + jest.doMock('../specs/NativeReactNativeFeatureFlags', () => ({ + __esModule: true, + default: {}, + })); + + const ReactNativeFeatureFlags = require('../ReactNativeFeatureFlags'); + expect(ReactNativeFeatureFlags.commonTestFlag()).toBe(false); + + expect(console.error).toHaveBeenCalledTimes(1); + expect(console.error).toHaveBeenCalledWith( + "Could not access feature flag 'commonTestFlag' because native module method was not available", + ); }); it('should access and cache common flags from the native module if it is available', () => { const commonTestFlagFn = jest.fn(() => true); - jest.doMock('../NativeReactNativeFeatureFlags', () => ({ + jest.doMock('../specs/NativeReactNativeFeatureFlags', () => ({ __esModule: true, default: { commonTestFlag: commonTestFlagFn, @@ -62,20 +84,34 @@ describe('ReactNativeFeatureFlags', () => { expect(jsOnlyTestFlagFn).toHaveBeenCalledTimes(1); }); - it('should throw an error if any of the flags has been accessed before overridding', () => { + it('should throw an error if any of the JS flags has been accessed before overridding', () => { const ReactNativeFeatureFlags = require('../ReactNativeFeatureFlags'); - ReactNativeFeatureFlags.commonTestFlag(); + ReactNativeFeatureFlags.jsOnlyTestFlag(); expect(() => ReactNativeFeatureFlags.override({ jsOnlyTestFlag: () => true, }), ).toThrow( - 'Feature flags were accessed before being overridden: commonTestFlag', + 'Feature flags were accessed before being overridden: jsOnlyTestFlag', ); }); + it('should NOT throw an error if any of the common flags has been accessed before overridding', () => { + const ReactNativeFeatureFlags = require('../ReactNativeFeatureFlags'); + + ReactNativeFeatureFlags.commonTestFlag(); + + expect(() => { + ReactNativeFeatureFlags.override({ + jsOnlyTestFlag: () => true, + }); + }).not.toThrow(); + + expect(ReactNativeFeatureFlags.jsOnlyTestFlag()).toBe(true); + }); + it('should throw an error when trying to set overrides twice', () => { const ReactNativeFeatureFlags = require('../ReactNativeFeatureFlags'); diff --git a/packages/react-native/src/private/featureflags/NativeReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js similarity index 81% rename from packages/react-native/src/private/featureflags/NativeReactNativeFeatureFlags.js rename to packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js index 93243673eba9d2..24c095337f8174 100644 --- a/packages/react-native/src/private/featureflags/NativeReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<8509d5ee87efb5aa8da7efcd2085d0a2>> + * @generated SignedSource<<8fcd655a9837ad155fd71efe8b05e3d0>> * @flow strict-local */ @@ -18,21 +18,22 @@ * yarn featureflags-update */ -import type {TurboModule} from '../../../Libraries/TurboModule/RCTExport'; +import type {TurboModule} from '../../../../Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from '../../../Libraries/TurboModule/TurboModuleRegistry'; +import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboModuleRegistry'; export interface Spec extends TurboModule { +commonTestFlag?: () => boolean; - +enableBackgroundExecutor?: () => boolean; - +useModernRuntimeScheduler?: () => boolean; - +enableMicrotasks?: () => boolean; +batchRenderingUpdatesInEventLoop?: () => boolean; - +enableSpannableBuildingUnification?: () => boolean; + +enableBackgroundExecutor?: () => boolean; +enableCustomDrawOrderFabric?: () => boolean; +enableFixForClippedSubviewsCrash?: () => boolean; + +enableMicrotasks?: () => boolean; + +enableMountHooksAndroid?: () => boolean; + +enableSpannableBuildingUnification?: () => boolean; +inspectorEnableCxxInspectorPackagerConnection?: () => boolean; +inspectorEnableModernCDPRegistry?: () => boolean; + +useModernRuntimeScheduler?: () => boolean; } const NativeReactNativeFeatureFlags: ?Spec = TurboModuleRegistry.get( diff --git a/packages/react-native/src/private/specs/modules/NativeBlobModule.js b/packages/react-native/src/private/specs/modules/NativeBlobModule.js index f04198990b2217..f751d2e2634021 100644 --- a/packages/react-native/src/private/specs/modules/NativeBlobModule.js +++ b/packages/react-native/src/private/specs/modules/NativeBlobModule.js @@ -12,8 +12,10 @@ import type {TurboModule} from '../../../../Libraries/TurboModule/RCTExport'; import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboModuleRegistry'; +export type Constants = {|BLOB_URI_SCHEME: ?string, BLOB_URI_HOST: ?string|}; + export interface Spec extends TurboModule { - +getConstants: () => {|BLOB_URI_SCHEME: ?string, BLOB_URI_HOST: ?string|}; + +getConstants: () => Constants; +addNetworkingHandler: () => void; +addWebSocketHandler: (id: number) => void; +removeWebSocketHandler: (id: number) => void; @@ -29,7 +31,7 @@ let NativeBlobModule = null; if (NativeModule != null) { NativeBlobModule = { - getConstants(): {|BLOB_URI_SCHEME: ?string, BLOB_URI_HOST: ?string|} { + getConstants(): Constants { if (constants == null) { constants = NativeModule.getConstants(); } diff --git a/packages/react-native/src/private/specs/modules/NativePushNotificationManagerIOS.js b/packages/react-native/src/private/specs/modules/NativePushNotificationManagerIOS.js index 01eeeaf35cd430..52e5fc8f17f3bb 100644 --- a/packages/react-native/src/private/specs/modules/NativePushNotificationManagerIOS.js +++ b/packages/react-native/src/private/specs/modules/NativePushNotificationManagerIOS.js @@ -55,10 +55,6 @@ type Notification = {| * getScheduledLocalNotifications or getDeliveredNotifications. */ +soundName?: ?string, - /** DEPRECATED. This was used for iOS's legacy UILocalNotification. */ - +alertAction?: ?string, - /** DEPRECATED. Use `fireDate` or `fireIntervalSeconds` instead. */ - +repeatInterval?: ?string, |}; export interface Spec extends TurboModule { diff --git a/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyElement.js b/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyElement.js index 46fb34c1e8f555..e1b58a294fae5d 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyElement.js +++ b/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyElement.js @@ -151,9 +151,8 @@ export default class ReadOnlyElement extends ReadOnlyNode { const node = getShadowNode(this); if (node != null) { - const scrollPosition = nullthrows(getFabricUIManager()).getScrollPosition( - node, - ); + const scrollPosition = + nullthrows(getFabricUIManager()).getScrollPosition(node); if (scrollPosition != null) { return scrollPosition[0]; } @@ -166,9 +165,8 @@ export default class ReadOnlyElement extends ReadOnlyNode { const node = getShadowNode(this); if (node != null) { - const scrollPosition = nullthrows(getFabricUIManager()).getScrollPosition( - node, - ); + const scrollPosition = + nullthrows(getFabricUIManager()).getScrollPosition(node); if (scrollPosition != null) { return scrollPosition[1]; } diff --git a/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyNode.js b/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyNode.js index 2eb5d742ff2cc3..2c29c2d105af85 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyNode.js +++ b/packages/react-native/src/private/webapis/dom/nodes/ReadOnlyNode.js @@ -125,9 +125,8 @@ export default class ReadOnlyNode { return null; } - const parentInstanceHandle = nullthrows(getFabricUIManager()).getParentNode( - shadowNode, - ); + const parentInstanceHandle = + nullthrows(getFabricUIManager()).getParentNode(shadowNode); if (parentInstanceHandle == null) { return null; @@ -323,9 +322,8 @@ export function getChildNodes( return []; } - const childNodeInstanceHandles = nullthrows( - getFabricUIManager(), - ).getChildNodes(shadowNode); + const childNodeInstanceHandles = + nullthrows(getFabricUIManager()).getChildNodes(shadowNode); return childNodeInstanceHandles .map(instanceHandle => getPublicInstanceFromInternalInstanceHandle(instanceHandle), diff --git a/packages/react-native/src/private/webapis/microtasks/specs/NativeMicrotasks.js b/packages/react-native/src/private/webapis/microtasks/specs/NativeMicrotasks.js new file mode 100644 index 00000000000000..5fa44e54803d0d --- /dev/null +++ b/packages/react-native/src/private/webapis/microtasks/specs/NativeMicrotasks.js @@ -0,0 +1,19 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import type {TurboModule} from '../../../../../Libraries/TurboModule/RCTExport'; + +import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/TurboModuleRegistry'; + +export interface Spec extends TurboModule { + +queueMicrotask: (callback: () => mixed) => void; +} + +export default (TurboModuleRegistry.get('NativeMicrotasksCxx'): ?Spec); diff --git a/packages/react-native/src/private/webapis/performance/EventCounts.js b/packages/react-native/src/private/webapis/performance/EventCounts.js index 27ece857093b23..682ef5557072b5 100644 --- a/packages/react-native/src/private/webapis/performance/EventCounts.js +++ b/packages/react-native/src/private/webapis/performance/EventCounts.js @@ -8,8 +8,8 @@ * @format */ -import NativePerformanceObserver from './NativePerformanceObserver'; import {warnNoNativePerformanceObserver} from './PerformanceObserver'; +import NativePerformanceObserver from './specs/NativePerformanceObserver'; type EventCountsForEachCallbackType = | (() => void) diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index 92befaae912372..dbadef33aa4723 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -12,13 +12,15 @@ import type {HighResTimeStamp, PerformanceEntryType} from './PerformanceEntry'; import type {PerformanceEntryList} from './PerformanceObserver'; +import type { + PerformanceMarkOptions, + PerformanceMeasureOptions, +} from './UserTiming'; import warnOnce from '../../../../Libraries/Utilities/warnOnce'; import EventCounts from './EventCounts'; import MemoryInfo from './MemoryInfo'; -import NativePerformance from './NativePerformance'; -import NativePerformanceObserver from './NativePerformanceObserver'; -import {ALWAYS_LOGGED_ENTRY_TYPES, PerformanceEntry} from './PerformanceEntry'; +import {ALWAYS_LOGGED_ENTRY_TYPES} from './PerformanceEntry'; import {warnNoNativePerformanceObserver} from './PerformanceObserver'; import { performanceEntryTypeToRaw, @@ -26,22 +28,17 @@ import { } from './RawPerformanceEntry'; import {RawPerformanceEntryTypeValues} from './RawPerformanceEntry'; import ReactNativeStartupTiming from './ReactNativeStartupTiming'; - -type DetailType = mixed; - -export type PerformanceMarkOptions = { - detail?: DetailType, - startTime?: HighResTimeStamp, -}; +import NativePerformance from './specs/NativePerformance'; +import NativePerformanceObserver from './specs/NativePerformanceObserver'; +import {PerformanceMark, PerformanceMeasure} from './UserTiming'; declare var global: { // This value is defined directly via JSI, if available. +nativePerformanceNow?: ?() => number, }; -const getCurrentTimeStamp: () => HighResTimeStamp = global.nativePerformanceNow - ? global.nativePerformanceNow - : () => Date.now(); +const getCurrentTimeStamp: () => HighResTimeStamp = + NativePerformance?.now ?? global.nativePerformanceNow ?? (() => Date.now()); // We want some of the performance entry types to be always logged, // even if they are not currently observed - this is either to be able to @@ -54,49 +51,6 @@ if (NativePerformanceObserver?.setIsBuffered) { ); } -export class PerformanceMark extends PerformanceEntry { - detail: DetailType; - - constructor(markName: string, markOptions?: PerformanceMarkOptions) { - super({ - name: markName, - entryType: 'mark', - startTime: markOptions?.startTime ?? getCurrentTimeStamp(), - duration: 0, - }); - - if (markOptions) { - this.detail = markOptions.detail; - } - } -} - -export type TimeStampOrName = HighResTimeStamp | string; - -export type PerformanceMeasureOptions = { - detail?: DetailType, - start?: TimeStampOrName, - end?: TimeStampOrName, - duration?: HighResTimeStamp, -}; - -export class PerformanceMeasure extends PerformanceEntry { - detail: DetailType; - - constructor(measureName: string, measureOptions?: PerformanceMeasureOptions) { - super({ - name: measureName, - entryType: 'measure', - startTime: 0, - duration: measureOptions?.duration ?? 0, - }); - - if (measureOptions) { - this.detail = measureOptions.detail; - } - } -} - function warnNoNativePerformance() { warnOnce( 'missing-native-performance', diff --git a/packages/react-native/src/private/webapis/performance/PerformanceObserver.js b/packages/react-native/src/private/webapis/performance/PerformanceObserver.js index c8caee14662fbd..4a37d3e4f159c5 100644 --- a/packages/react-native/src/private/webapis/performance/PerformanceObserver.js +++ b/packages/react-native/src/private/webapis/performance/PerformanceObserver.js @@ -11,7 +11,6 @@ import type {HighResTimeStamp, PerformanceEntryType} from './PerformanceEntry'; import warnOnce from '../../../../Libraries/Utilities/warnOnce'; -import NativePerformanceObserver from './NativePerformanceObserver'; import {PerformanceEntry} from './PerformanceEntry'; import PerformanceEventTiming from './PerformanceEventTiming'; import { @@ -19,6 +18,7 @@ import { rawToPerformanceEntry, rawToPerformanceEntryType, } from './RawPerformanceEntry'; +import NativePerformanceObserver from './specs/NativePerformanceObserver'; export type PerformanceEntryList = $ReadOnlyArray; diff --git a/packages/react-native/src/private/webapis/performance/RawPerformanceEntry.js b/packages/react-native/src/private/webapis/performance/RawPerformanceEntry.js index 767a8bdd61795f..e1ef5a5c2b8a41 100644 --- a/packages/react-native/src/private/webapis/performance/RawPerformanceEntry.js +++ b/packages/react-native/src/private/webapis/performance/RawPerformanceEntry.js @@ -8,11 +8,11 @@ * @flow strict */ +import type {PerformanceEntryType} from './PerformanceEntry'; import type { RawPerformanceEntry, RawPerformanceEntryType, -} from './NativePerformanceObserver'; -import type {PerformanceEntryType} from './PerformanceEntry'; +} from './specs/NativePerformanceObserver'; import {PerformanceEntry} from './PerformanceEntry'; import PerformanceEventTiming from './PerformanceEventTiming'; diff --git a/packages/react-native/src/private/webapis/performance/UserTiming.js b/packages/react-native/src/private/webapis/performance/UserTiming.js new file mode 100644 index 00000000000000..2380e71731e833 --- /dev/null +++ b/packages/react-native/src/private/webapis/performance/UserTiming.js @@ -0,0 +1,63 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @flow strict + */ + +import type {HighResTimeStamp} from './PerformanceEntry'; + +import {PerformanceEntry} from './PerformanceEntry'; + +type DetailType = mixed; + +export type PerformanceMarkOptions = { + detail?: DetailType, + startTime?: HighResTimeStamp, +}; + +export type TimeStampOrName = HighResTimeStamp | string; + +export type PerformanceMeasureOptions = { + detail?: DetailType, + start?: TimeStampOrName, + end?: TimeStampOrName, + duration?: HighResTimeStamp, +}; + +export class PerformanceMark extends PerformanceEntry { + detail: DetailType; + + constructor(markName: string, markOptions?: PerformanceMarkOptions) { + super({ + name: markName, + entryType: 'mark', + startTime: markOptions?.startTime ?? performance.now(), + duration: 0, + }); + + if (markOptions) { + this.detail = markOptions.detail; + } + } +} + +export class PerformanceMeasure extends PerformanceEntry { + detail: DetailType; + + constructor(measureName: string, measureOptions?: PerformanceMeasureOptions) { + super({ + name: measureName, + entryType: 'measure', + startTime: 0, + duration: measureOptions?.duration ?? 0, + }); + + if (measureOptions) { + this.detail = measureOptions.detail; + } + } +} diff --git a/packages/react-native/src/private/webapis/performance/__tests__/EventCounts-test.js b/packages/react-native/src/private/webapis/performance/__tests__/EventCounts-test.js index 7be1b9c1fd8c45..953349f9fe7c43 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/EventCounts-test.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/EventCounts-test.js @@ -12,12 +12,12 @@ import {RawPerformanceEntryTypeValues} from '../RawPerformanceEntry'; // NOTE: Jest mocks of transitive dependencies don't appear to work with // ES6 module imports, therefore forced to use commonjs style imports here. -const NativePerformanceObserver = require('../NativePerformanceObserver'); const Performance = require('../Performance').default; +const NativePerformanceObserver = require('../specs/NativePerformanceObserver'); jest.mock( - '../NativePerformanceObserver', - () => require('../__mocks__/NativePerformanceObserver').default, + '../specs/NativePerformanceObserver', + () => require('../specs/__mocks__/NativePerformanceObserver').default, ); describe('EventCounts', () => { diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js index a5e85831ae3a5f..bb637df30d9075 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js @@ -11,13 +11,13 @@ const Performance = require('../Performance').default; jest.mock( - '../NativePerformance', - () => require('../__mocks__/NativePerformance').default, + '../specs/NativePerformance', + () => require('../specs/__mocks__/NativePerformance').default, ); jest.mock( - '../NativePerformanceObserver', - () => require('../__mocks__/NativePerformanceObserver').default, + '../specs/NativePerformanceObserver', + () => require('../specs/__mocks__/NativePerformanceObserver').default, ); describe('Performance', () => { diff --git a/packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js b/packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js index a6e6a37be9ff62..cf46dcbfd0e2d8 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js @@ -12,12 +12,12 @@ import {RawPerformanceEntryTypeValues} from '../RawPerformanceEntry'; // NOTE: Jest mocks of transitive dependencies don't appear to work with // ES6 module imports, therefore forced to use commonjs style imports here. -const NativePerformanceObserver = require('../NativePerformanceObserver'); const PerformanceObserver = require('../PerformanceObserver').default; +const NativePerformanceObserver = require('../specs/NativePerformanceObserver'); jest.mock( - '../NativePerformanceObserver', - () => require('../__mocks__/NativePerformanceObserver').default, + '../specs/NativePerformanceObserver', + () => require('../specs/__mocks__/NativePerformanceObserver').default, ); describe('PerformanceObserver', () => { diff --git a/packages/react-native/src/private/webapis/performance/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js similarity index 79% rename from packages/react-native/src/private/webapis/performance/NativePerformance.js rename to packages/react-native/src/private/webapis/performance/specs/NativePerformance.js index ac8d410af92dfe..b05f2e74e4e1e6 100644 --- a/packages/react-native/src/private/webapis/performance/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js @@ -8,15 +8,16 @@ * @format */ -import type {TurboModule} from '../../../../Libraries/TurboModule/RCTExport'; +import type {TurboModule} from '../../../../../Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboModuleRegistry'; +import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/TurboModuleRegistry'; export type NativeMemoryInfo = {[key: string]: ?number}; export type ReactNativeStartupTiming = {[key: string]: ?number}; export interface Spec extends TurboModule { + +now?: () => number; +mark: (name: string, startTime: number) => void; +measure: ( name: string, diff --git a/packages/react-native/src/private/webapis/performance/NativePerformanceObserver.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformanceObserver.js similarity index 90% rename from packages/react-native/src/private/webapis/performance/NativePerformanceObserver.js rename to packages/react-native/src/private/webapis/performance/specs/NativePerformanceObserver.js index 3881872fcca468..af2e2c3a68ce6b 100644 --- a/packages/react-native/src/private/webapis/performance/NativePerformanceObserver.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformanceObserver.js @@ -8,9 +8,9 @@ * @format */ -import type {TurboModule} from '../../../../Libraries/TurboModule/RCTExport'; +import type {TurboModule} from '../../../../../Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboModuleRegistry'; +import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/TurboModuleRegistry'; export type RawPerformanceEntryType = number; diff --git a/packages/react-native/src/private/webapis/performance/__mocks__/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformance.js similarity index 95% rename from packages/react-native/src/private/webapis/performance/__mocks__/NativePerformance.js rename to packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformance.js index ee5eed6e6b0157..b1e7072584fbf8 100644 --- a/packages/react-native/src/private/webapis/performance/__mocks__/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformance.js @@ -14,8 +14,8 @@ import type { Spec as NativePerformance, } from '../NativePerformance'; +import {RawPerformanceEntryTypeValues} from '../../RawPerformanceEntry'; import NativePerformanceObserver from '../NativePerformanceObserver'; -import {RawPerformanceEntryTypeValues} from '../RawPerformanceEntry'; const marks: Map = new Map(); diff --git a/packages/react-native/src/private/webapis/performance/__mocks__/NativePerformanceObserver.js b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceObserver.js similarity index 97% rename from packages/react-native/src/private/webapis/performance/__mocks__/NativePerformanceObserver.js rename to packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceObserver.js index dd0fd1acb7f537..9e71ab98692922 100644 --- a/packages/react-native/src/private/webapis/performance/__mocks__/NativePerformanceObserver.js +++ b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceObserver.js @@ -15,7 +15,7 @@ import type { Spec as NativePerformanceObserver, } from '../NativePerformanceObserver'; -import {RawPerformanceEntryTypeValues} from '../RawPerformanceEntry'; +import {RawPerformanceEntryTypeValues} from '../../RawPerformanceEntry'; const reportingType: Set = new Set(); const isAlwaysLogged: Set = new Set(); diff --git a/packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceMock-test.js b/packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceMock-test.js similarity index 96% rename from packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceMock-test.js rename to packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceMock-test.js index 679dad39dfc5e5..1d700ce9e5fd7e 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceMock-test.js +++ b/packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceMock-test.js @@ -9,7 +9,7 @@ */ const NativePerformanceMock = require('../__mocks__/NativePerformance').default; -const PerformanceObserver = require('../PerformanceObserver').default; +const PerformanceObserver = require('../../PerformanceObserver').default; describe('NativePerformanceMock', () => { jest.mock( diff --git a/packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceObserverMock-test.js b/packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceObserverMock-test.js similarity index 97% rename from packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceObserverMock-test.js rename to packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceObserverMock-test.js index a4d8a575d74e3f..7b5c62a362a8da 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/NativePerformanceObserverMock-test.js +++ b/packages/react-native/src/private/webapis/performance/specs/__tests__/NativePerformanceObserverMock-test.js @@ -9,7 +9,7 @@ */ import NativePerformanceObserverMock from '../__mocks__/NativePerformanceObserver'; -import {RawPerformanceEntryTypeValues} from '../RawPerformanceEntry'; +import {RawPerformanceEntryTypeValues} from '../../RawPerformanceEntry'; describe('NativePerformanceObserver', () => { it('correctly starts and stops listening to entries in a nominal scenario', async () => { diff --git a/packages/react-native/template/android/gradle-wrapper.jar b/packages/react-native/template/android/gradle-wrapper.jar deleted file mode 100644 index d64cd4917707c1..00000000000000 Binary files a/packages/react-native/template/android/gradle-wrapper.jar and /dev/null differ diff --git a/packages/react-native/template/android/gradle-wrapper.properties b/packages/react-native/template/android/gradle-wrapper.properties deleted file mode 100644 index e6aba2515d5428..00000000000000 --- a/packages/react-native/template/android/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-all.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/packages/react-native/template/android/gradle.properties b/packages/react-native/template/android/gradle.properties index a46a5b90fad015..99fc223edf55fb 100644 --- a/packages/react-native/template/android/gradle.properties +++ b/packages/react-native/template/android/gradle.properties @@ -34,7 +34,7 @@ reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # 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=false +newArchEnabled=true # Use this property to enable or disable the Hermes JS engine. # If set to false, you will be using JSC instead. diff --git a/packages/react-native/template/package.json b/packages/react-native/template/package.json index 232831747e774e..47fd4a9e6f2aea 100644 --- a/packages/react-native/template/package.json +++ b/packages/react-native/template/package.json @@ -17,10 +17,10 @@ "@babel/core": "^7.20.0", "@babel/preset-env": "^7.20.0", "@babel/runtime": "^7.20.0", - "@react-native/babel-preset": "0.74.0", - "@react-native/eslint-config": "0.74.0", - "@react-native/metro-config": "0.74.0", - "@react-native/typescript-config": "0.74.0", + "@react-native/babel-preset": "0.75.0-main", + "@react-native/eslint-config": "0.75.0-main", + "@react-native/metro-config": "0.75.0-main", + "@react-native/typescript-config": "0.75.0-main", "@types/react": "^18.2.6", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.6.3", diff --git a/packages/react-native/third-party-podspecs/RCT-Folly.podspec b/packages/react-native/third-party-podspecs/RCT-Folly.podspec index eb2d9b4ed8cb85..ccc10a5b47ccef 100644 --- a/packages/react-native/third-party-podspecs/RCT-Folly.podspec +++ b/packages/react-native/third-party-podspecs/RCT-Folly.podspec @@ -81,6 +81,7 @@ Pod::Spec.new do |spec| 'folly/system/*.h', spec.libraries = "c++abi" # NOTE Apple-only: Keep c++abi here due to https://github.com/react-native-community/releases/issues/251 spec.pod_target_xcconfig = { "USE_HEADERMAP" => "NO", + "DEFINES_MODULE" => "YES", "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)\" \"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/fmt/include\"", # In dynamic framework (use_frameworks!) mode, ignore the unused and undefined boost symbols when generating the library. diff --git a/packages/react-native/types/__typetests__/index.tsx b/packages/react-native/types/__typetests__/index.tsx index a7f8250e25d0ab..80a615b036c418 100644 --- a/packages/react-native/types/__typetests__/index.tsx +++ b/packages/react-native/types/__typetests__/index.tsx @@ -411,7 +411,9 @@ class CustomView extends React.Component { } } -class Welcome extends React.Component & {color: string}> { +class Welcome extends React.Component< + ElementProps & {color: string; bgColor?: null | undefined | string} +> { rootViewRef = React.useRef(null); customViewRef = React.useRef(null); @@ -436,12 +438,18 @@ class Welcome extends React.Component & {color: string}> { } render() { - const {color, ...props} = this.props; + const {color, bgColor, ...props} = this.props; return ( + style={[ + [styles.container], + undefined, + null, + false, + bgColor && {backgroundColor: bgColor}, + ]}> Welcome to React Native To get started, edit index.ios.js @@ -1267,12 +1275,18 @@ export class ImageTest extends React.Component { } }); + const promise1: Promise = Image.getSize(uri).then(({width, height}) => + console.log(width, height), + ); Image.getSize(uri, (width, height) => console.log(width, height)); Image.getSize( uri, (width, height) => console.log(width, height), error => console.error(error), ); + const promise2: Promise = Image.getSizeWithHeaders(uri, headers).then( + ({width, height}) => console.log(width, height), + ); Image.getSizeWithHeaders(uri, headers, (width, height) => console.log(width, height), ); diff --git a/packages/react-native/types/index.d.ts b/packages/react-native/types/index.d.ts index b23e2e0a2ff267..5aeec0685ed009 100644 --- a/packages/react-native/types/index.d.ts +++ b/packages/react-native/types/index.d.ts @@ -103,6 +103,7 @@ export * from '../Libraries/Components/View/View'; export * from '../Libraries/Components/View/ViewAccessibility'; export * from '../Libraries/Components/View/ViewPropTypes'; export * from '../Libraries/Components/Button'; +export * from '../Libraries/Core/registerCallableModule'; export * from '../Libraries/DevToolsSettings/DevToolsSettingsManager'; export * from '../Libraries/EventEmitter/NativeEventEmitter'; export * from '../Libraries/EventEmitter/RCTDeviceEventEmitter'; diff --git a/packages/react-native/types/modules/globals.d.ts b/packages/react-native/types/modules/globals.d.ts index 51272890300db7..e22b936f3403d7 100644 --- a/packages/react-native/types/modules/globals.d.ts +++ b/packages/react-native/types/modules/globals.d.ts @@ -132,6 +132,10 @@ declare interface Headers { get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; + entries(): IterableIterator<[string, string]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; } declare var Headers: { diff --git a/packages/rn-tester-e2e/package.json b/packages/rn-tester-e2e/package.json index ef06a7f8fe1b87..6d1dfdb3af457c 100644 --- a/packages/rn-tester-e2e/package.json +++ b/packages/rn-tester-e2e/package.json @@ -1,13 +1,13 @@ { "name": "@react-native/tester-e2e", "private": true, - "version": "0.0.1", + "version": "0.75.0-main", "license": "MIT", "description": "React Native E2E tester app.", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/rn-tester-e2e", "repository": { "type": "git", - "url": "git@github.com:facebook/react-native.git", + "url": "git+ssh://git@github.com/facebook/react-native.git", "directory": "packages/rn-tester-e2e" }, "scripts": { diff --git a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec index 2e4eb0613d9f41..fd9f314c6d6ad8 100644 --- a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec +++ b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.author = "Meta Platforms, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/my-native-view.git", :tag => "#{s.version}" } s.pod_target_xcconfig = { - "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Codegen/React_Codegen.framework/Headers\"", + "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/ReactCodegen/ReactCodegen.framework/Headers\"", "CLANG_CXX_LANGUAGE_STANDARD" => "c++20" } diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp index abec005d02e00b..0bbc831d838156 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp @@ -184,7 +184,6 @@ void NativeCxxModuleExample::emitCustomDeviceEvent( // Test emitting device events (RCTDeviceEventEmitter.emit) from C++ // TurboModule with arbitrary arguments emitDeviceEvent( - rt, eventName.utf8(rt).c_str(), [](jsi::Runtime& rt, std::vector& args) { args.emplace_back(jsi::Value(true)); diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h index 9017ab9f7b6153..327744b0c17a42 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h @@ -7,8 +7,8 @@ #pragma once -#if __has_include() // CocoaPod headers on Apple -#include +#if __has_include() // CocoaPod headers on Apple +#include #elif __has_include("AppSpecsJSI.h") // Cmake headers on Android #include "AppSpecsJSI.h" #else // BUCK headers diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index 66e57f4f87b2d6..1f0abbe738264b 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -20,7 +20,6 @@ PODS: - RCT-Folly (= 2024.01.01.00) - RCTRequired - RCTTypeSafety - - React-Codegen - React-Core - React-debug - React-Fabric @@ -31,6 +30,7 @@ PODS: - React-RCTFabric - React-rendererdebug - React-utils + - ReactCodegen - ReactCommon/turbomodule/bridging - ReactCommon/turbomodule/core - Yoga @@ -41,7 +41,6 @@ PODS: - RCT-Folly (= 2024.01.01.00) - RCTRequired - RCTTypeSafety - - React-Codegen - React-Core - React-debug - React-Fabric @@ -52,6 +51,7 @@ PODS: - React-RCTFabric - React-rendererdebug - React-utils + - ReactCodegen - ReactCommon/turbomodule/bridging - ReactCommon/turbomodule/core - Yoga @@ -92,26 +92,6 @@ PODS: - React-RCTText (= 1000.0.0) - React-RCTVibration (= 1000.0.0) - React-callinvoker (1000.0.0) - - React-Codegen (1000.0.0): - - DoubleConversion - - glog - - hermes-engine - - RCT-Folly - - RCTRequired - - RCTTypeSafety - - React-Core - - React-debug - - React-Fabric - - React-FabricImage - - React-featureflags - - React-graphics - - React-jsi - - React-jsiexecutor - - React-NativeModulesApple - - React-rendererdebug - - React-utils - - ReactCommon/turbomodule/bridging - - ReactCommon/turbomodule/core - React-Core (1000.0.0): - glog - hermes-engine @@ -372,13 +352,13 @@ PODS: - fmt (= 9.1.0) - RCT-Folly (= 2024.01.01.00) - RCTTypeSafety (= 1000.0.0) - - React-Codegen - React-Core/CoreModulesHeaders (= 1000.0.0) - React-jsi (= 1000.0.0) - React-jsinspector - React-NativeModulesApple - React-RCTBlob - React-RCTImage (= 1000.0.0) + - ReactCodegen - ReactCommon - SocketRocket (= 0.7.0) - React-cxxreact (1000.0.0): @@ -952,8 +932,9 @@ PODS: - React-cxxreact (= 1000.0.0) - React-jsi - React-jsiexecutor (= 1000.0.0) - - React-jsinspector (= 1000.0.0) + - React-jsinspector - React-perflogger (= 1000.0.0) + - React-runtimeexecutor - React-ImageManager (1000.0.0): - glog - RCT-Folly/Fabric @@ -988,8 +969,11 @@ PODS: - React-jsinspector (1000.0.0): - DoubleConversion - glog + - hermes-engine - RCT-Folly (= 2024.01.01.00) - React-featureflags + - React-jsi + - React-runtimeexecutor (= 1000.0.0) - React-jsitracing (1000.0.0): - React-jsi - React-logger (1000.0.0): @@ -1015,10 +999,10 @@ PODS: - React-RCTAnimation (1000.0.0): - RCT-Folly (= 2024.01.01.00) - RCTTypeSafety - - React-Codegen - React-Core/RCTAnimationHeaders - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - React-RCTAppDelegate (1000.0.0): - RCT-Folly (= 2024.01.01.00) @@ -1041,19 +1025,20 @@ PODS: - React-RuntimeHermes - React-runtimescheduler - React-utils + - ReactCodegen - ReactCommon - React-RCTBlob (1000.0.0): - DoubleConversion - fmt (= 9.1.0) - hermes-engine - RCT-Folly (= 2024.01.01.00) - - React-Codegen - React-Core/RCTBlobHeaders - React-Core/RCTWebSocket - React-jsi - React-jsinspector - React-NativeModulesApple - React-RCTNetwork + - ReactCodegen - ReactCommon - React-RCTFabric (1000.0.0): - glog @@ -1063,6 +1048,7 @@ PODS: - React-debug - React-Fabric - React-FabricImage + - React-featureflags - React-graphics - React-ImageManager - React-jsi @@ -1077,41 +1063,41 @@ PODS: - React-RCTImage (1000.0.0): - RCT-Folly (= 2024.01.01.00) - RCTTypeSafety - - React-Codegen - React-Core/RCTImageHeaders - React-jsi - React-NativeModulesApple - React-RCTNetwork + - ReactCodegen - ReactCommon - React-RCTLinking (1000.0.0): - - React-Codegen - React-Core/RCTLinkingHeaders (= 1000.0.0) - React-jsi (= 1000.0.0) - React-NativeModulesApple + - ReactCodegen - ReactCommon - ReactCommon/turbomodule/core (= 1000.0.0) - React-RCTNetwork (1000.0.0): - RCT-Folly (= 2024.01.01.00) - RCTTypeSafety - - React-Codegen - React-Core/RCTNetworkHeaders - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - React-RCTPushNotification (1000.0.0): - RCTTypeSafety - - React-Codegen - React-Core/RCTPushNotificationHeaders - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - React-RCTSettings (1000.0.0): - RCT-Folly (= 2024.01.01.00) - RCTTypeSafety - - React-Codegen - React-Core/RCTSettingsHeaders - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - React-RCTTest (1000.0.0): - RCT-Folly (= 2024.01.01.00) @@ -1124,10 +1110,10 @@ PODS: - Yoga - React-RCTVibration (1000.0.0): - RCT-Folly (= 2024.01.01.00) - - React-Codegen - React-Core/RCTVibrationHeaders - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - React-rendererdebug (1000.0.0): - DoubleConversion @@ -1172,7 +1158,9 @@ PODS: - hermes-engine - RCT-Folly/Fabric (= 2024.01.01.00) - React-featureflags + - React-hermes - React-jsi + - React-jsinspector - React-jsitracing - React-nativeconfig - React-RuntimeCore @@ -1191,21 +1179,42 @@ PODS: - React-utils - React-utils (1000.0.0): - glog + - hermes-engine - RCT-Folly (= 2024.01.01.00) - React-debug + - React-jsi (= 1000.0.0) + - ReactCodegen (1000.0.0): + - DoubleConversion + - glog + - hermes-engine + - RCT-Folly + - RCTRequired + - RCTTypeSafety + - React-Core + - React-debug + - React-Fabric + - React-FabricImage + - React-featureflags + - React-graphics + - React-jsi + - React-jsiexecutor + - React-NativeModulesApple + - React-rendererdebug + - React-utils + - ReactCommon/turbomodule/bridging + - ReactCommon/turbomodule/core - ReactCommon (1000.0.0): - - React-logger (= 1000.0.0) - ReactCommon/turbomodule (= 1000.0.0) - ReactCommon-Samples (1000.0.0): - DoubleConversion - fmt (= 9.1.0) - hermes-engine - RCT-Folly - - React-Codegen - React-Core - React-cxxreact - React-jsi - React-NativeModulesApple + - ReactCodegen - ReactCommon - ReactCommon/turbomodule (1000.0.0): - DoubleConversion @@ -1243,6 +1252,7 @@ PODS: - React-jsi (= 1000.0.0) - React-logger (= 1000.0.0) - React-perflogger (= 1000.0.0) + - React-utils (= 1000.0.0) - ScreenshotManager (0.0.1): - DoubleConversion - glog @@ -1250,7 +1260,6 @@ PODS: - RCT-Folly (= 2024.01.01.00) - RCTRequired - RCTTypeSafety - - React-Codegen - React-Core - React-debug - React-Fabric @@ -1261,6 +1270,7 @@ PODS: - React-RCTFabric - React-rendererdebug - React-utils + - ReactCodegen - ReactCommon/turbomodule/bridging - ReactCommon/turbomodule/core - Yoga @@ -1284,7 +1294,6 @@ DEPENDENCIES: - RCTTypeSafety (from `../react-native/Libraries/TypeSafety`) - React (from `../react-native/`) - React-callinvoker (from `../react-native/ReactCommon/callinvoker`) - - React-Codegen (from `build/generated/ios`) - React-Core (from `../react-native/`) - React-Core/RCTWebSocket (from `../react-native/`) - React-CoreModules (from `../react-native/React/CoreModules`) @@ -1327,6 +1336,7 @@ DEPENDENCIES: - React-RuntimeHermes (from `../react-native/ReactCommon/react/runtime`) - React-runtimescheduler (from `../react-native/ReactCommon/react/renderer/runtimescheduler`) - React-utils (from `../react-native/ReactCommon/react/utils`) + - ReactCodegen (from `build/generated/ios`) - ReactCommon-Samples (from `../react-native/ReactCommon/react/nativemodule/samples`) - ReactCommon/turbomodule/core (from `../react-native/ReactCommon`) - ScreenshotManager (from `NativeModuleExample`) @@ -1367,8 +1377,6 @@ EXTERNAL SOURCES: :path: "../react-native/" React-callinvoker: :path: "../react-native/ReactCommon/callinvoker" - React-Codegen: - :path: build/generated/ios React-Core: :path: "../react-native/" React-CoreModules: @@ -1451,6 +1459,8 @@ EXTERNAL SOURCES: :path: "../react-native/ReactCommon/react/renderer/runtimescheduler" React-utils: :path: "../react-native/ReactCommon/react/utils" + ReactCodegen: + :path: build/generated/ios ReactCommon: :path: "../react-native/ReactCommon" ReactCommon-Samples: @@ -1466,9 +1476,9 @@ SPEC CHECKSUMS: FBLazyVector: f4492a543c5a8fa1502d3a5867e3f7252497cfe8 fmt: 4c2741a687cc09f0634a2e2c72a838b99f1ff120 glog: c5d68082e772fa1c511173d6b30a9de2c05a69a2 - hermes-engine: b6ed6780e02b97c31d4d84407f579e3523177780 - MyNativeView: 08e59984e995c857953374e22082d058be3cb945 - NativeCxxModuleExample: 51569707f2da9a460d1ebf74a29d02f0a86c549e + hermes-engine: a1af2c958bf22d19bff4df14e977c77fb469d48f + MyNativeView: 34e8a4347e7fae110d5878e10740224ebbf881a6 + NativeCxxModuleExample: 64d8720a77e8c9ff9383f9a98af7045c510092c0 OCMock: 9491e4bec59e0b267d52a9184ff5605995e74be8 RCT-Folly: 045d6ecaa59d826c5736dfba0b2f4083ff8d79df RCTDeprecation: 3808e36294137f9ee5668f4df2e73dc079cd1dcf @@ -1476,53 +1486,53 @@ SPEC CHECKSUMS: RCTTypeSafety: 5f57d4ae5dfafc85a0f575d756c909b584722c52 React: cb6dc75e09f32aeddb4d8fb58a394a67219a92fe React-callinvoker: bae59cbd6affd712bbfc703839dad868ff35069d - React-Codegen: b66fa3765bc7a786e88e56ff92459a41dec00b0f React-Core: 738c8db837b21aae813479f2eb284d5507a5c256 - React-CoreModules: 0b94c427e958c1b7ce268d03aa39a1f424d76901 + React-CoreModules: 7647d54882adb778c614ac0053865ef1f92eb211 React-cxxreact: dadc89738f0089c3e2b85f36de940a088759b20d - React-debug: 4097205dd5ff0ada516e7df5b6721a9464a6f20b - React-Fabric: a3214cc064ca25e029aff0a42e2beb8c87b71861 - React-FabricImage: 6daf9bcd047ac1c424cfd7cae298089f8d495761 - React-featureflags: 36f601a77af59dca45877a298c804883dd04f8d0 - React-graphics: 8d54d923bef33e9f423d06c4fd51431f917a4b2f - React-hermes: 14e7007ebbfcc9f674c9c4f3ac768aa587b6da79 - React-ImageManager: 44304168f3ec4733a0191dadee7b1711291272f4 - React-jserrorhandler: 2809ae4d87fb880d2c18be72bcaed114e79f3993 + React-debug: 296b501a90c41f83961f58c6d96a01330d499da5 + React-Fabric: 1875e77c86078dfc0f116806f2de976d0df6da77 + React-FabricImage: da62cc5089fe6bdaa6ec0ab6ccca75c7d679065d + React-featureflags: 23f83a12963770bf3cff300e8990678192436b36 + React-graphics: 7e646eb47b666d2cb4e148ec4afcecc4253f1736 + React-hermes: 65dd94615e5cb47f0f2f7510231f80c65abf338c + React-ImageManager: 716592dcbe11a4960e1eb3d82adb264ee15b5f6d + React-jserrorhandler: 13a0cce4e1e445d2ace089dc6122fb85411a11b3 React-jsi: b7645527d3f77afdea4365488e47dbc5b293177f React-jsiexecutor: 42eeb6b4e73e1b50caa3940ad0189171723c6b29 - React-jsinspector: 363ee50f69cb39cc2ee4eef0705f2fc4a33f83f3 - React-jsitracing: 46474207a88a3978c08e191d9cf33a6457722d65 + React-jsinspector: 8c41e3113f94f08385a730aff19eb16af810c82d + React-jsitracing: dd08057dd5b74119cb406beb42028da85ed5b8a5 React-logger: 8486d7a1d32b972414b1d34a93470ee2562c6ee2 - React-Mapbuffer: 9d18546228182de42aae8cb047baa5e14886a922 - React-nativeconfig: a5a38eee09c6a57824489bf9005d46d2e3fbb78b - React-NativeModulesApple: ff03b94214a1628f920b43bb64964860fc227f9f + React-Mapbuffer: fd0d0306c1c4326be5f18a61e978d32a66b20a85 + React-nativeconfig: 40a2c848083ef4065c163c854e1c82b5f9e9db84 + React-NativeModulesApple: 48f0205edc54b8a1c24328f2deeb74b4f1570418 React-perflogger: 70d009f755dd10002183454cdf5ad9b22de4a1d7 React-RCTActionSheet: 943bd5f540f3af1e5a149c13c4de81858edf718a - React-RCTAnimation: 07583f0ebfa7154f0e696a75c32a8f8b180fc8c5 - React-RCTAppDelegate: 60cfe221df61de818f6e6b200ff55b4346e6ea7c - React-RCTBlob: 2dbf6931deac47ff5d3910e4c81cdd856ea239d6 - React-RCTFabric: e613b7e4aec23114ee6999295ca97b3f0508ee0f - React-RCTImage: 8f46d82257827c2332bc4108fddef1a840f440a7 - React-RCTLinking: efa67827466e50e07c5471447c12e474cbc5e336 - React-RCTNetwork: a80529d2d90f79caa5e31d49e840735a10d6d91a - React-RCTPushNotification: c34ef3969207da3ddc777f36a252f99754b89e2d - React-RCTSettings: 39ca10f68da0ec88a63c33152d43c222c8c38119 + React-RCTAnimation: 4d88a95a05dbb9a5cbc9a55e08f1a79364aeb206 + React-RCTAppDelegate: 560ef776e8bc5b4b478a839ac34ec3726e3dcb5c + React-RCTBlob: 74c2fa0adba3a2e4ebbc4f9fc4ec3c3691b93854 + React-RCTFabric: d5b371f6fabd59163270b60d42e6149457bb8212 + React-RCTImage: 2413fa5ca25235b878fb2694115b26b176280f31 + React-RCTLinking: 7c821b30c5b4401037ed3da63f9580ac42b9e02e + React-RCTNetwork: a556f5005d28d99df0b577d9ef8b28f29c0ff498 + React-RCTPushNotification: c0871d7ebfd7832a5763b571f68b936772654ed3 + React-RCTSettings: 25141964d76155f25dd993b87345656a29dd0d24 React-RCTTest: 3b9f62c66c3814ccace402441597160aefc9e812 React-RCTText: d9925903524a7b179cf7803162a98038e0bfb4fd - React-RCTVibration: 33bef249bc4a637ed91bf1cf0d94d9329381dc7b - React-rendererdebug: bc0f2a1816a4607e85ed603170a413c44c1d2635 - React-rncore: 79f594bc32c96203ab607bd9868ec76caa2f290c - React-RuntimeApple: 504b50d20ddf82de9c2c527c6b5a09119e03b737 - React-RuntimeCore: 9dc8d98bc09b0797c2dca7a30be5e8f84ecf5746 + React-RCTVibration: 63e015aa41be5e956440ebe8b8796f56ddd1acc8 + React-rendererdebug: 0abbd75e947eeae23542f3bf7491b048ae063141 + React-rncore: e903b3d2819a25674403c548ec103f34bf02ba2b + React-RuntimeApple: b43ad6a5d60157f37ff3139e4dfb0cd6340e9be6 + React-RuntimeCore: 7cfdac312222d7260d8ba9604686fbb4aa4f8a13 React-runtimeexecutor: e1c32bc249dd3cf3919cb4664fd8dc84ef70cff7 - React-RuntimeHermes: b1f60690c9ed90d448f1325355f72c662c02e49a - React-runtimescheduler: 0df238ee8e88e1b8874d332856ee7d36870be4ad - React-utils: 00c57742056c9c90e58b1a8cd06ca50d30528d6f - ReactCommon: 4148a8bfb8bbfdbea8f517f98cadeeb0f30c8de8 - ReactCommon-Samples: 5d703e2b5e1c8ddb812e7b7cace5a8effbcc6438 - ScreenshotManager: 823189e19d4e6f7d4792fe1db6b037df7efc2fab + React-RuntimeHermes: b19a99a600c6e1e33d7796cb91a5c76f92bd3407 + React-runtimescheduler: d5fecf52a345c1e557499ee86c864089c2a01fb8 + React-utils: f5525c0072f467cf2f25bdd8dbbf0835f6384972 + ReactCodegen: 23192ed6132b7eb93d61cc2ee8e21a816b361a37 + ReactCommon: 9ee429c89520684edefef7f68d5fa55e7f3478cc + ReactCommon-Samples: e2bf03c8237c461fa36bda8e4638368fa82b633c + ScreenshotManager: 2c0ba89924202a5717df5e9ded68536e68df64c7 SocketRocket: abac6f5de4d4d62d24e11868d7a2f427e0ef940d - Yoga: 53e99e2a727b8498ea9e8aed8d917b808c9ff2ea + Yoga: f58ba5e0ac1e7eb3ef4caedcf80c5aa39985b039 PODFILE CHECKSUM: 60b84dd598fc04e9ed84dbc82e2cb3b99b1d7adf diff --git a/packages/rn-tester/RNTester/AppDelegate.mm b/packages/rn-tester/RNTester/AppDelegate.mm index fcb6360c7242b5..eacc13101b2c61 100644 --- a/packages/rn-tester/RNTester/AppDelegate.mm +++ b/packages/rn-tester/RNTester/AppDelegate.mm @@ -9,10 +9,12 @@ #import +#import #import #import #import #import +#import #import #import @@ -83,10 +85,12 @@ - (void)loadSourceForBridge:(RCTBridge *)bridge if (name == std::string([@"SampleTurboCxxModule" UTF8String])) { return std::make_shared(jsInvoker); } + if (name == facebook::react::NativeCxxModuleExample::kModuleName) { return std::make_shared(jsInvoker); } - return nullptr; + + return [super getTurboModule:name jsInvoker:jsInvoker]; } // Required for the remoteNotificationsRegistered event. diff --git a/packages/rn-tester/RNTester/NativeExampleViews/FlexibleSizeExampleView.mm b/packages/rn-tester/RNTester/NativeExampleViews/FlexibleSizeExampleView.mm index 489c3a91e33659..c01c39a4f5a2b6 100644 --- a/packages/rn-tester/RNTester/NativeExampleViews/FlexibleSizeExampleView.mm +++ b/packages/rn-tester/RNTester/NativeExampleViews/FlexibleSizeExampleView.mm @@ -46,9 +46,8 @@ - (instancetype)initWithFrame:(CGRect)frame AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; - _resizableRootView = [[RCTRootView alloc] initWithBridge:appDelegate.bridge - moduleName:@"RootViewSizeFlexibilityExampleApp" - initialProperties:@{}]; + _resizableRootView = + (RCTRootView *)[appDelegate.rootViewFactory viewWithModuleName:@"RootViewSizeFlexibilityExampleApp"]; [_resizableRootView setSizeFlexibility:RCTRootViewSizeFlexibilityHeight]; diff --git a/packages/rn-tester/RNTester/NativeExampleViews/UpdatePropertiesExampleView.mm b/packages/rn-tester/RNTester/NativeExampleViews/UpdatePropertiesExampleView.mm index 9689203576c2cd..5682d7ddead216 100644 --- a/packages/rn-tester/RNTester/NativeExampleViews/UpdatePropertiesExampleView.mm +++ b/packages/rn-tester/RNTester/NativeExampleViews/UpdatePropertiesExampleView.mm @@ -41,9 +41,8 @@ - (instancetype)initWithFrame:(CGRect)frame AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; - _rootView = [[RCTRootView alloc] initWithBridge:appDelegate.bridge - moduleName:@"SetPropertiesExampleApp" - initialProperties:@{@"color" : @"beige"}]; + _rootView = (RCTRootView *)[appDelegate.rootViewFactory viewWithModuleName:@"SetPropertiesExampleApp" + initialProperties:@{@"color" : @"beige"}]; _button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [_button setTitle:@"Native Button" forState:UIControlStateNormal]; diff --git a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj index edfdf6aa584cb7..4e7c3b9024ae7f 100644 --- a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj +++ b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj @@ -7,7 +7,7 @@ objects = { /* Begin PBXBuildFile section */ - 00915AE8006CF5DB156153DD /* Pods_RNTester.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F9DA138FE541ED31A6C589D7 /* Pods_RNTester.framework */; }; + 08E25EBE4A584CD7B70FBB1E /* libPods-RNTester.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D74056A5352F0925816E50E0 /* libPods-RNTester.a */; }; 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 2DDEF0101F84BF7B00DBDF73 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2DDEF00F1F84BF7B00DBDF73 /* Images.xcassets */; }; 383889DA23A7398900D06C3E /* RCTConvert_UIColorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 383889D923A7398900D06C3E /* RCTConvert_UIColorTests.m */; }; @@ -15,8 +15,9 @@ 5C60EB1C226440DB0018C04F /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C60EB1B226440DB0018C04F /* AppDelegate.mm */; }; 8145AE06241172D900A3F8DA /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8145AE05241172D900A3F8DA /* LaunchScreen.storyboard */; }; 832F45BB2A8A6E1F0097B4E6 /* SwiftTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 832F45BA2A8A6E1F0097B4E6 /* SwiftTest.swift */; }; - 836E54623F6567BB812F3F6A /* Pods_RNTesterUnitTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B5084412F9118F6F7FA99DA /* Pods_RNTesterUnitTests.framework */; }; + BEB82277FE76227A15DED9EF /* libPods-RNTesterIntegrationTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 77E101C7D8E22A8E70EE76DF /* libPods-RNTesterIntegrationTests.a */; }; CD10C7A5290BD4EB0033E1ED /* RCTEventEmitterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = CD10C7A4290BD4EB0033E1ED /* RCTEventEmitterTests.m */; }; + D626973C1F0D4ABDE2F9028A /* libPods-RNTesterUnitTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D8DE57E3292D41E28251988A /* libPods-RNTesterUnitTests.a */; }; E62F11832A5C6580000BF1C8 /* FlexibleSizeExampleView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 27F441E81BEBE5030039B79C /* FlexibleSizeExampleView.mm */; }; E62F11842A5C6584000BF1C8 /* UpdatePropertiesExampleView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 272E6B3C1BEA849E001FCF37 /* UpdatePropertiesExampleView.mm */; }; E7C1241A22BEC44B00DA25C0 /* RNTesterIntegrationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = E7C1241922BEC44B00DA25C0 /* RNTesterIntegrationTests.m */; }; @@ -55,7 +56,6 @@ E7DB216422B2F3EC005AC45F /* RCTUIManagerScenarioTests.m in Sources */ = {isa = PBXBuildFile; fileRef = E7DB215F22B2F3EC005AC45F /* RCTUIManagerScenarioTests.m */; }; E7DB216722B2F69F005AC45F /* JavaScriptCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7DB213022B2C649005AC45F /* JavaScriptCore.framework */; }; E7DB218C22B41FCD005AC45F /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7DB218B22B41FCD005AC45F /* XCTest.framework */; }; - FA45ED19FFAECF4CFEFE0DC7 /* Pods_RNTesterIntegrationTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87E71F82CA94BF2D3CA3110A /* Pods_RNTesterIntegrationTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -88,18 +88,19 @@ 2DDEF00F1F84BF7B00DBDF73 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = RNTester/Images.xcassets; sourceTree = ""; }; 359825B9A5AE4A3F4AA612DD /* Pods-RNTesterUnitTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTesterUnitTests.debug.xcconfig"; path = "Target Support Files/Pods-RNTesterUnitTests/Pods-RNTesterUnitTests.debug.xcconfig"; sourceTree = ""; }; 383889D923A7398900D06C3E /* RCTConvert_UIColorTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTConvert_UIColorTests.m; sourceTree = ""; }; - 3B5084412F9118F6F7FA99DA /* Pods_RNTesterUnitTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RNTesterUnitTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3D2AFAF41D646CF80089D1A3 /* legacy_image@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "legacy_image@2x.png"; path = "RNTester/legacy_image@2x.png"; sourceTree = ""; }; 5C60EB1B226440DB0018C04F /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = RNTester/AppDelegate.mm; sourceTree = ""; }; 66C3087F2D5BF762FE9E6422 /* Pods-RNTesterIntegrationTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTesterIntegrationTests.debug.xcconfig"; path = "Target Support Files/Pods-RNTesterIntegrationTests/Pods-RNTesterIntegrationTests.debug.xcconfig"; sourceTree = ""; }; + 77E101C7D8E22A8E70EE76DF /* libPods-RNTesterIntegrationTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RNTesterIntegrationTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 7CDA7A212644C6BB8C0D00D8 /* Pods-RNTesterIntegrationTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTesterIntegrationTests.release.xcconfig"; path = "Target Support Files/Pods-RNTesterIntegrationTests/Pods-RNTesterIntegrationTests.release.xcconfig"; sourceTree = ""; }; 8145AE05241172D900A3F8DA /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = RNTester/LaunchScreen.storyboard; sourceTree = ""; }; 832F45BA2A8A6E1F0097B4E6 /* SwiftTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SwiftTest.swift; path = RNTester/SwiftTest.swift; sourceTree = ""; }; - 87E71F82CA94BF2D3CA3110A /* Pods_RNTesterIntegrationTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RNTesterIntegrationTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 8BFB9C61D7BDE894E24BF24F /* Pods-RNTesterUnitTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTesterUnitTests.release.xcconfig"; path = "Target Support Files/Pods-RNTesterUnitTests/Pods-RNTesterUnitTests.release.xcconfig"; sourceTree = ""; }; 9B8542B8C590B51BD0588751 /* Pods-RNTester.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTester.release.xcconfig"; path = "Target Support Files/Pods-RNTester/Pods-RNTester.release.xcconfig"; sourceTree = ""; }; AC474BFB29BBD4A1002BDAED /* RNTester.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; name = RNTester.xctestplan; path = RNTester/RNTester.xctestplan; sourceTree = ""; }; CD10C7A4290BD4EB0033E1ED /* RCTEventEmitterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTEventEmitterTests.m; sourceTree = ""; }; + D74056A5352F0925816E50E0 /* libPods-RNTester.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RNTester.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + D8DE57E3292D41E28251988A /* libPods-RNTesterUnitTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RNTesterUnitTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; E771AEEA22B44E3100EA1189 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = RNTester/Info.plist; sourceTree = ""; }; E7C1241922BEC44B00DA25C0 /* RNTesterIntegrationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNTesterIntegrationTests.m; sourceTree = ""; }; E7DB209F22B2BA84005AC45F /* RNTesterUnitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RNTesterUnitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -161,7 +162,6 @@ E7DB215E22B2F3EC005AC45F /* RCTLoggingTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTLoggingTests.m; sourceTree = ""; }; E7DB215F22B2F3EC005AC45F /* RCTUIManagerScenarioTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTUIManagerScenarioTests.m; sourceTree = ""; }; E7DB218B22B41FCD005AC45F /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = XCTest.framework; sourceTree = DEVELOPER_DIR; }; - F9DA138FE541ED31A6C589D7 /* Pods_RNTester.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RNTester.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -169,7 +169,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 00915AE8006CF5DB156153DD /* Pods_RNTester.framework in Frameworks */, + 08E25EBE4A584CD7B70FBB1E /* libPods-RNTester.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -178,7 +178,7 @@ buildActionMask = 2147483647; files = ( E7DB213122B2C649005AC45F /* JavaScriptCore.framework in Frameworks */, - 836E54623F6567BB812F3F6A /* Pods_RNTesterUnitTests.framework in Frameworks */, + D626973C1F0D4ABDE2F9028A /* libPods-RNTesterUnitTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -188,7 +188,7 @@ files = ( E7DB218C22B41FCD005AC45F /* XCTest.framework in Frameworks */, E7DB216722B2F69F005AC45F /* JavaScriptCore.framework in Frameworks */, - FA45ED19FFAECF4CFEFE0DC7 /* Pods_RNTesterIntegrationTests.framework in Frameworks */, + BEB82277FE76227A15DED9EF /* libPods-RNTesterIntegrationTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -258,9 +258,9 @@ E7DB211822B2BD53005AC45F /* libReact-RCTText.a */, E7DB211A22B2BD53005AC45F /* libReact-RCTVibration.a */, E7DB212222B2BD53005AC45F /* libyoga.a */, - F9DA138FE541ED31A6C589D7 /* Pods_RNTester.framework */, - 87E71F82CA94BF2D3CA3110A /* Pods_RNTesterIntegrationTests.framework */, - 3B5084412F9118F6F7FA99DA /* Pods_RNTesterUnitTests.framework */, + D74056A5352F0925816E50E0 /* libPods-RNTester.a */, + 77E101C7D8E22A8E70EE76DF /* libPods-RNTesterIntegrationTests.a */, + D8DE57E3292D41E28251988A /* libPods-RNTesterUnitTests.a */, ); name = Frameworks; sourceTree = ""; diff --git a/packages/rn-tester/android/app/build.gradle.kts b/packages/rn-tester/android/app/build.gradle.kts index 5ad05a044325fd..e2c69a64985e34 100644 --- a/packages/rn-tester/android/app/build.gradle.kts +++ b/packages/rn-tester/android/app/build.gradle.kts @@ -151,6 +151,7 @@ android { dependencies { // Build React Native from source implementation(project(":packages:react-native:ReactAndroid")) + implementation(project(":packages:react-native-popup-menu-android:android")) // Consume Hermes as built from source only for the Hermes variant. "hermesImplementation"(project(":packages:react-native:ReactAndroid:hermes-engine")) diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.kt b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.kt index 33b2373fd46c27..01756aea982108 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.kt +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.kt @@ -25,6 +25,7 @@ import com.facebook.react.defaults.DefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.module.model.ReactModuleInfo import com.facebook.react.module.model.ReactModuleInfoProvider +import com.facebook.react.popupmenu.PopupMenuPackage import com.facebook.react.shell.MainReactPackage import com.facebook.react.uiapp.component.MyLegacyViewManager import com.facebook.react.uiapp.component.MyNativeViewManager @@ -44,6 +45,7 @@ class RNTesterApplication : Application(), ReactApplication { public override fun getPackages(): List { return listOf( MainReactPackage(), + PopupMenuPackage(), object : TurboReactPackage() { override fun getModule( name: String, diff --git a/packages/rn-tester/js/RNTesterAppShared.js b/packages/rn-tester/js/RNTesterAppShared.js index 131a838b976477..87cb6b69dfe47a 100644 --- a/packages/rn-tester/js/RNTesterAppShared.js +++ b/packages/rn-tester/js/RNTesterAppShared.js @@ -217,8 +217,8 @@ const RNTesterApp = ({ activeModuleTitle != null ? activeModuleTitle : screen === Screens.COMPONENTS - ? 'Components' - : 'APIs'; + ? 'Components' + : 'APIs'; const activeExampleList = screen === Screens.COMPONENTS ? examplesList.components : examplesList.apis; diff --git a/packages/rn-tester/js/assets/bottom-nav-apis-icon-active.png b/packages/rn-tester/js/assets/bottom-nav-apis-icon-dark.png similarity index 100% rename from packages/rn-tester/js/assets/bottom-nav-apis-icon-active.png rename to packages/rn-tester/js/assets/bottom-nav-apis-icon-dark.png diff --git a/packages/rn-tester/js/assets/bottom-nav-apis-icon-inactive.png b/packages/rn-tester/js/assets/bottom-nav-apis-icon-light.png similarity index 100% rename from packages/rn-tester/js/assets/bottom-nav-apis-icon-inactive.png rename to packages/rn-tester/js/assets/bottom-nav-apis-icon-light.png diff --git a/packages/rn-tester/js/assets/bottom-nav-components-icon-active.png b/packages/rn-tester/js/assets/bottom-nav-components-icon-dark.png similarity index 100% rename from packages/rn-tester/js/assets/bottom-nav-components-icon-active.png rename to packages/rn-tester/js/assets/bottom-nav-components-icon-dark.png diff --git a/packages/rn-tester/js/assets/bottom-nav-components-icon-inactive.png b/packages/rn-tester/js/assets/bottom-nav-components-icon-light.png similarity index 100% rename from packages/rn-tester/js/assets/bottom-nav-components-icon-inactive.png rename to packages/rn-tester/js/assets/bottom-nav-components-icon-light.png diff --git a/packages/rn-tester/js/components/RNTesterNavbar.js b/packages/rn-tester/js/components/RNTesterNavbar.js index 8b49ab157c47be..a0817d8d62e3b0 100644 --- a/packages/rn-tester/js/components/RNTesterNavbar.js +++ b/packages/rn-tester/js/components/RNTesterNavbar.js @@ -37,7 +37,12 @@ const NavbarButton = ({ style={iconStyle} source={isActive ? activeImage : inactiveImage} /> - + {label} @@ -57,8 +62,8 @@ const ComponentTab = ({ testID="components-tab" label="Components" handlePress={() => handleNavBarPress({screen: 'components'})} - activeImage={require('./../assets/bottom-nav-components-icon-active.png')} - inactiveImage={require('./../assets/bottom-nav-components-icon-inactive.png')} + activeImage={theme.NavBarComponentsActiveIcon} + inactiveImage={theme.NavBarComponentsInactiveIcon} isActive={isComponentActive} theme={theme} iconStyle={styles.componentIcon} @@ -78,8 +83,8 @@ const APITab = ({ testID="apis-tab" label="APIs" handlePress={() => handleNavBarPress({screen: 'apis'})} - activeImage={require('./../assets/bottom-nav-apis-icon-active.png')} - inactiveImage={require('./../assets/bottom-nav-apis-icon-inactive.png')} + activeImage={theme.NavBarAPIsActiveIcon} + inactiveImage={theme.NavBarAPIsInactiveIcon} isActive={isAPIActive} theme={theme} iconStyle={styles.apiIcon} @@ -157,12 +162,6 @@ const styles = StyleSheet.create({ height: 20, alignSelf: 'center', }, - activeText: { - color: '#5E5F62', - }, - inactiveText: { - color: '#B1B4BA', - }, activeBar: { borderTopWidth: 2, borderColor: '#005DFF', diff --git a/packages/rn-tester/js/components/RNTesterTheme.js b/packages/rn-tester/js/components/RNTesterTheme.js index a94c7c54787b51..6c7858e17c57d0 100644 --- a/packages/rn-tester/js/components/RNTesterTheme.js +++ b/packages/rn-tester/js/components/RNTesterTheme.js @@ -8,6 +8,7 @@ * @format */ +import type {ImageSource} from 'react-native/Libraries/Image/ImageSource'; import type {ColorValue} from 'react-native/Libraries/StyleSheet/StyleSheet'; import * as React from 'react'; @@ -42,6 +43,13 @@ export type RNTesterTheme = { ToolbarColor: ColorValue, BackgroundColor: ColorValue, BorderColor: ColorValue, + + NavBarLabelActiveColor: ColorValue, + NavBarLabelInactiveColor: ColorValue, + NavBarComponentsActiveIcon: ImageSource, + NavBarComponentsInactiveIcon: ImageSource, + NavBarAPIsActiveIcon: ImageSource, + NavBarAPIsInactiveIcon: ImageSource, ... }; @@ -75,6 +83,13 @@ export const RNTesterLightTheme = { ToolbarColor: '#e9eaedff', BackgroundColor: '#f3f8ffff', BorderColor: '#005dffff', + + NavBarLabelActiveColor: '#5e5f62ff', + NavBarLabelInactiveColor: '#b1b4baff', + NavBarComponentsActiveIcon: require('./../assets/bottom-nav-components-icon-dark.png'), + NavBarComponentsInactiveIcon: require('./../assets/bottom-nav-components-icon-light.png'), + NavBarAPIsActiveIcon: require('./../assets/bottom-nav-apis-icon-dark.png'), + NavBarAPIsInactiveIcon: require('./../assets/bottom-nav-apis-icon-light.png'), }; export const RNTesterDarkTheme = { @@ -107,6 +122,13 @@ export const RNTesterDarkTheme = { ToolbarColor: '#3c3c43ff', BackgroundColor: '#0c0700ff', BorderColor: '#005dffff', + + NavBarLabelActiveColor: '#b1b4baff', + NavBarLabelInactiveColor: '#5e5f62ff', + NavBarComponentsActiveIcon: require('./../assets/bottom-nav-components-icon-light.png'), + NavBarComponentsInactiveIcon: require('./../assets/bottom-nav-components-icon-dark.png'), + NavBarAPIsActiveIcon: require('./../assets/bottom-nav-apis-icon-light.png'), + NavBarAPIsInactiveIcon: require('./../assets/bottom-nav-apis-icon-dark.png'), }; export const themes = {light: RNTesterLightTheme, dark: RNTesterDarkTheme}; diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js index f6d9126c67bba3..bd14a80134039c 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js @@ -645,8 +645,8 @@ class NestedCheckBox extends React.Component< checkbox2 && this.state.checkbox3 ? true : checkbox2 || this.state.checkbox3 - ? 'mixed' - : false, + ? 'mixed' + : false, }); }; @@ -659,8 +659,8 @@ class NestedCheckBox extends React.Component< this.state.checkbox2 && checkbox3 ? true : this.state.checkbox2 || checkbox3 - ? 'mixed' - : false, + ? 'mixed' + : false, }); }; @@ -680,8 +680,8 @@ class NestedCheckBox extends React.Component< this.state.checkbox1 === 'mixed' ? mixedCheckboxImageSource : this.state.checkbox1 - ? checkImageSource - : uncheckImageSource + ? checkImageSource + : uncheckImageSource } /> Meat diff --git a/packages/rn-tester/js/examples/Alert/AlertExample.js b/packages/rn-tester/js/examples/Alert/AlertExample.js index 22d058e2c99b41..895c9529faddbd 100644 --- a/packages/rn-tester/js/examples/Alert/AlertExample.js +++ b/packages/rn-tester/js/examples/Alert/AlertExample.js @@ -227,7 +227,9 @@ const AlertWithStylesPreferred = () => { }; const PromptOptions = () => { - const [promptValue, setPromptValue] = React.useState(''); + const [promptValue, setPromptValue] = React.useState< + string | {login: string, password: string}, + >(''); const customButtons = [ { @@ -243,7 +245,8 @@ const PromptOptions = () => { return ( - Prompt value: {promptValue} + Prompt value: + {JSON.stringify(promptValue, null, 2)} ( {props.themeName} - {Object.keys(theme).map(key => ( - - - - - {key} - - - {typeof theme[key] === 'string' - ? theme[key] - : JSON.stringify(theme[key])} - - - - ))} + {Object.keys(theme).map( + key => + typeof theme[key] === 'string' && ( + + + + + {key} + + + {theme[key]} + + + + ), + )} ); }} diff --git a/packages/rn-tester/js/examples/Cursor/CursorExample.js b/packages/rn-tester/js/examples/Cursor/CursorExample.js new file mode 100644 index 00000000000000..77936112305aff --- /dev/null +++ b/packages/rn-tester/js/examples/Cursor/CursorExample.js @@ -0,0 +1,124 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +'use strict'; + +const React = require('react'); +const {StyleSheet, Text, View} = require('react-native'); + +const styles = StyleSheet.create({ + invisibleBox: { + width: 100, + height: 100, + }, + box: { + width: 100, + height: 100, + borderWidth: 2, + }, + circle: { + width: 100, + height: 100, + borderWidth: 2, + borderRadius: 100, + }, + halfcircle: { + width: 100, + height: 100, + borderWidth: 2, + borderTopStartRadius: 100, + borderBottomStartRadius: 100, + }, + solid: { + backgroundColor: 'blue', + }, + pointer: { + cursor: 'pointer', + }, + row: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 10, + }, + centerContent: { + justifyContent: 'center', + alignItems: 'center', + }, +}); + +function CursorExampleAuto() { + return ( + + + + + + + + + ); +} + +function CursorExamplePointer() { + return ( + + + + + + + + + ); +} + +function CursorExamplePointer() { + return ( + + + + + + + + + ); +} + +function CursorExampleViewFlattening() { + return ( + + + pointer + + + ); +} + +exports.title = 'Cursor'; +exports.category = 'UI'; +exports.description = + 'Demonstrates setting a cursor, which affects the appearance when a pointer is over the View.'; +exports.examples = [ + { + title: 'Default', + description: "Cursor: 'auto' or no cursor set ", + render: CursorExampleAuto, + }, + { + title: 'Pointer', + description: 'cursor: pointer', + render: CursorExamplePointer, + }, + { + title: 'View flattening', + description: 'Views with a cursor do not get flattened', + render: CursorExampleViewFlattening, + }, +]; diff --git a/packages/rn-tester/js/examples/Performance/PerformanceComparisonExample.js b/packages/rn-tester/js/examples/Performance/PerformanceComparisonExample.js index 896b8defbb8568..fb0ac33a9cd023 100644 --- a/packages/rn-tester/js/examples/Performance/PerformanceComparisonExample.js +++ b/packages/rn-tester/js/examples/Performance/PerformanceComparisonExample.js @@ -84,8 +84,8 @@ function PerfExampleWrapper(props: { {loadExample === SHOW_BAD_EXAMPLE ? badExampleContents : loadExample === SHOW_GOOD_EXAMPLE - ? goodExampleContents - : null} + ? goodExampleContents + : null} diff --git a/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js b/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js index 2437e8509cb211..c8f4bd6baccdeb 100644 --- a/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js +++ b/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js @@ -297,8 +297,8 @@ function VariantColorsExample() { Platform.OS === 'ios' ? DynamicColorIOS({light: 'red', dark: 'blue'}) : Platform.OS === 'android' - ? PlatformColor('?attr/colorAccent') - : 'red', + ? PlatformColor('?attr/colorAccent') + : 'red', }} /> diff --git a/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js b/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js index 2b35119e662ed8..3934c0f4f08307 100644 --- a/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js +++ b/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js @@ -10,11 +10,12 @@ 'use strict'; +import type {PopupMenuAndroidInstance} from '@react-native/popup-menu-android'; import type {Node} from 'react'; -import type {PopupMenuAndroidInstance} from 'react-native/Libraries/Components/PopupMenuAndroid/PopupMenuAndroid'; +import PopupMenuAndroid from '@react-native/popup-menu-android'; import * as React from 'react'; -import {Button, PopupMenuAndroid, StyleSheet, Text, View} from 'react-native'; +import {Button, StyleSheet, Text, View} from 'react-native'; type Fruit = 'Apple' | 'Pear' | 'Banana' | 'Orange' | 'Kiwi'; diff --git a/packages/rn-tester/js/examples/Pressable/PressableExample.js b/packages/rn-tester/js/examples/Pressable/PressableExample.js index 5266d69bb41376..6dfe4be3031ed3 100644 --- a/packages/rn-tester/js/examples/Pressable/PressableExample.js +++ b/packages/rn-tester/js/examples/Pressable/PressableExample.js @@ -244,8 +244,8 @@ function PressableNativeMethods() { {status == null ? 'Missing Ref!' : status === true - ? 'Native Methods Exist' - : 'Native Methods Missing!'} + ? 'Native Methods Exist' + : 'Native Methods Missing!'} diff --git a/packages/rn-tester/js/examples/Touchable/TouchableExample.js b/packages/rn-tester/js/examples/Touchable/TouchableExample.js index 4f978e9d5993d8..7827437cca1c03 100644 --- a/packages/rn-tester/js/examples/Touchable/TouchableExample.js +++ b/packages/rn-tester/js/examples/Touchable/TouchableExample.js @@ -321,8 +321,8 @@ function TouchableNativeMethodChecker< {status == null ? 'Missing Ref!' : status === true - ? 'Native Methods Exist' - : 'Native Methods Missing!'} + ? 'Native Methods Exist' + : 'Native Methods Missing!'} ); diff --git a/packages/rn-tester/js/utils/RNTesterList.ios.js b/packages/rn-tester/js/utils/RNTesterList.ios.js index fa0587ccd1454c..4dbcabd8b3f728 100644 --- a/packages/rn-tester/js/utils/RNTesterList.ios.js +++ b/packages/rn-tester/js/utils/RNTesterList.ios.js @@ -195,6 +195,10 @@ const APIs: Array = ([ key: 'CrashExample', module: require('../examples/Crash/CrashExample'), }, + { + key: 'CursorExample', + module: require('../examples/Cursor/CursorExample'), + }, { key: 'DevSettings', module: require('../examples/DevSettings/DevSettingsExample'), diff --git a/packages/rn-tester/metro.config.js b/packages/rn-tester/metro.config.js index 3c41387cc19b65..87b72ad0f6c214 100644 --- a/packages/rn-tester/metro.config.js +++ b/packages/rn-tester/metro.config.js @@ -30,6 +30,7 @@ const config = { path.resolve(__dirname, '../polyfills'), path.resolve(__dirname, '../react-native'), path.resolve(__dirname, '../virtualized-lists'), + path.resolve(__dirname, '../react-native-popup-menu-android'), ], resolver: { blockList: [/..\/react-native\/sdks\/hermes/], diff --git a/packages/rn-tester/package.json b/packages/rn-tester/package.json index d63abf26aab14e..b9141d86c34304 100644 --- a/packages/rn-tester/package.json +++ b/packages/rn-tester/package.json @@ -1,12 +1,12 @@ { "name": "@react-native/tester", - "version": "0.0.1", + "version": "0.75.0-main", "private": true, "description": "React Native tester app.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/rn-tester" }, "engines": { @@ -25,7 +25,8 @@ "dependencies": { "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", - "nullthrows": "^1.1.1" + "nullthrows": "^1.1.1", + "@react-native/popup-menu-android": "0.75.0-main" }, "peerDependencies": { "react": "18.2.0", diff --git a/packages/typescript-config/package.json b/packages/typescript-config/package.json index 0ca29efbb837a5..810837974b2ff5 100644 --- a/packages/typescript-config/package.json +++ b/packages/typescript-config/package.json @@ -1,11 +1,11 @@ { "name": "@react-native/typescript-config", - "version": "0.74.0", + "version": "0.75.0-main", "description": "Default TypeScript configuration for React Native apps", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/facebook/react-native.git", + "url": "git+https://github.com/facebook/react-native.git", "directory": "packages/typescript-config" }, "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/typescript-config#readme", diff --git a/packages/virtualized-lists/Lists/VirtualizedListCellRenderer.js b/packages/virtualized-lists/Lists/VirtualizedListCellRenderer.js index afe3eea7ad4bc9..d67f19884bdedc 100644 --- a/packages/virtualized-lists/Lists/VirtualizedListCellRenderer.js +++ b/packages/virtualized-lists/Lists/VirtualizedListCellRenderer.js @@ -203,8 +203,8 @@ export default class CellRenderer extends React.Component< ? [styles.rowReverse, inversionStyle] : [styles.columnReverse, inversionStyle] : horizontal - ? [styles.row, inversionStyle] - : inversionStyle; + ? [styles.row, inversionStyle] + : inversionStyle; const result = !CellRendererComponent ? ( ); - return leadingSeparator || separator ? ( - - {inverted === false ? leadingSeparator : separator} + const RenderSeparator = leadingSeparator || separator; + const firstSeparator = inverted === false ? leadingSeparator : separator; + const secondSeparator = inverted === false ? separator : leadingSeparator; + + return ( + <> + {RenderSeparator ? firstSeparator : null} {element} - {inverted === false ? separator : leadingSeparator} - - ) : ( - element + {RenderSeparator ? secondSeparator : null} + ); } diff --git a/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js b/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js index 774a2473556bc1..8feafd86b6486f 100644 --- a/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js +++ b/packages/virtualized-lists/Lists/__tests__/VirtualizedList-test.js @@ -11,9 +11,12 @@ 'use strict'; import VirtualizedList from '../VirtualizedList'; +import {format} from 'node:util'; import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; +jest.useFakeTimers(); + describe('VirtualizedList', () => { it('renders simple list', () => { const component = ReactTestRenderer.create( @@ -69,11 +72,12 @@ describe('VirtualizedList', () => { it('throws if no renderItem or ListItemComponent', () => { // Silence the React error boundary warning; we expect an uncaught error. const consoleError = console.error; - jest.spyOn(console, 'error').mockImplementation(message => { - if (message.startsWith('The above error occurred in the ')) { + jest.spyOn(console, 'error').mockImplementation((...args) => { + const message = format(...args); + if (message.includes('The above error occurred in the ')) { return; } - consoleError(message); + consoleError(...args); }); const componentFactory = () => diff --git a/packages/virtualized-lists/Lists/__tests__/__snapshots__/VirtualizedSectionList-test.js.snap b/packages/virtualized-lists/Lists/__tests__/__snapshots__/VirtualizedSectionList-test.js.snap index 8a01cb58500c54..8de2c76b838233 100644 --- a/packages/virtualized-lists/Lists/__tests__/__snapshots__/VirtualizedSectionList-test.js.snap +++ b/packages/virtualized-lists/Lists/__tests__/__snapshots__/VirtualizedSectionList-test.js.snap @@ -252,80 +252,76 @@ exports[`VirtualizedSectionList handles separators correctly 1`] = ` onLayout={[Function]} style={null} > - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - + - + } + /> - - - - + + - - - - + + - - - - + + - - - - + + { - if (packageManifest.private) { - return; - } - - const desc = `${packageManifest.name} (${packageRelativePathFromRoot})`; - process.stdout.write( - `${desc} ${chalk.dim('.').repeat(Math.max(0, 72 - desc.length))} `, - ); - execSync( - `npm publish --registry ${VERDACCIO_SERVER_URL} --access public`, - { - cwd: packageAbsolutePath, - stdio: verbose ? 'inherit' : [process.stderr], - }, - ); - process.stdout.write(chalk.reset.inverse.bold.green(' DONE ') + '\n'); - }, - ); + const packages = await getPackages({ + includeReactNative: false, + includePrivate: false, + }); + + for (const {path: packagePath, packageJson} of Object.values(packages)) { + const desc = `${packageJson.name} (${path.relative( + REPO_ROOT, + packagePath, + )})`; + process.stdout.write( + `${desc} ${chalk.dim('.').repeat(Math.max(0, 72 - desc.length))} `, + ); + execSync( + `npm publish --registry ${VERDACCIO_SERVER_URL} --access public`, + { + cwd: packagePath, + stdio: verbose ? 'inherit' : [process.stderr], + }, + ); + process.stdout.write(chalk.reset.inverse.bold.green(' DONE ') + '\n'); + } console.log('\nDone ✅'); console.log('Running react-native init without install'); @@ -114,53 +121,48 @@ async function initNewProjectFromSource( --directory ${directory} \ --template ${templatePath} \ --verbose \ - --skip-install \ - --yarn-config-options npmRegistryServer="${VERDACCIO_SERVER_URL}"`, + --pm npm \ + --skip-install`, { // Avoid loading packages/react-native/react-native.config.js cwd: REPO_ROOT, - stdio: verbose ? 'inherit' : [process.stderr], + stdio: 'inherit', }, ); console.log('\nDone ✅'); console.log('Installing project dependencies'); - await runYarnUsingProxy(directory); + await installProjectUsingProxy(directory); console.log('Done ✅'); } catch (e) { console.log('Failed ❌'); throw e; } finally { console.log(`Cleanup: Killing Verdaccio process (PID: ${verdaccioPid})`); - execSync(`kill -9 ${verdaccioPid}`); - console.log('Done ✅'); - + try { + execSync(`kill -9 ${verdaccioPid}`); + console.log('Done ✅'); + } catch { + console.warn('Failed to kill Verdaccio process'); + } console.log('Cleanup: Removing Verdaccio storage directory'); execSync(`rm -rf ${VERDACCIO_STORAGE_PATH}`); console.log('Done ✅'); - - // TODO(huntie): Fix memory leak from `spawn` in `setupVerdaccio` (above - // kill command does not wait for kill success). - process.exit(0); } } -async function runYarnUsingProxy(cwd /*: string */) { +async function installProjectUsingProxy(cwd /*: string */) { const execOptions = { cwd, stdio: 'inherit', }; - execSync( - `yarn config set npmRegistryServer "${VERDACCIO_SERVER_URL}"`, - execOptions, - ); - execSync( - 'yarn config set unsafeHttpWhitelist --json \'["localhost"]\'', - execOptions, - ); // TODO(huntie): Review pre-existing retry limit - const success = await retry('yarn', execOptions, 3, 500, ['install']); + const success = await retry('npm', execOptions, 3, 500, [ + 'install', + '--registry', + VERDACCIO_SERVER_URL, + ]); if (!success) { throw new Error('Failed to install project dependencies'); diff --git a/scripts/e2e/run-ci-e2e-tests.js b/scripts/e2e/run-ci-e2e-tests.js index d76d7a1b6673be..ad3f6d16612668 100644 --- a/scripts/e2e/run-ci-e2e-tests.js +++ b/scripts/e2e/run-ci-e2e-tests.js @@ -22,7 +22,7 @@ */ const {REACT_NATIVE_PACKAGE_DIR, REPO_ROOT, SCRIPTS_DIR} = require('../consts'); -const forEachPackage = require('../monorepo/for-each-package'); +const {getPackages} = require('../utils/monorepo'); const tryExecNTimes = require('./utils/try-n-times'); const {setupVerdaccio} = require('./utils/verdaccio'); const {execFileSync, spawn} = require('child_process'); @@ -47,275 +47,282 @@ function describe(message /*: string */) { echo(`\n\n>>>>> ${message}\n\n\n`); } -try { - if (argv.android) { - describe('Compile Android binaries'); +async function main() { + try { + if (argv.android) { + describe('Compile Android binaries'); + if ( + exec( + './gradlew publishAllToMavenTempLocal -Pjobs=1 -Dorg.gradle.jvmargs="-Xmx512m -XX:+HeapDumpOnOutOfMemoryError"', + ).code + ) { + throw new Error('Failed to compile Android binaries'); + } + } + + describe('Create react-native package'); if ( exec( - './gradlew publishAllToMavenTempLocal -Pjobs=1 -Dorg.gradle.jvmargs="-Xmx512m -XX:+HeapDumpOnOutOfMemoryError"', + 'node ./scripts/releases/set-rn-version.js --to-version 1000.0.0 --build-type dry-run', ).code ) { - throw new Error('Failed to compile Android binaries'); + throw new Error( + 'Failed to set version and update package.json ready for release', + ); } - } - describe('Create react-native package'); - if ( - exec( - 'node ./scripts/releases/set-rn-version.js --to-version 1000.0.0 --build-type dry-run', - ).code - ) { - throw new Error( - 'Failed to set version and update package.json ready for release', - ); - } - - if (exec('npm pack', {cwd: REACT_NATIVE_PACKAGE_DIR}).code) { - throw new Error('Failed to pack react-native'); - } + if (exec('npm pack', {cwd: REACT_NATIVE_PACKAGE_DIR}).code) { + throw new Error('Failed to pack react-native'); + } - const REACT_NATIVE_PACKAGE = path.join( - REACT_NATIVE_PACKAGE_DIR, - 'react-native-*.tgz', - ); + const REACT_NATIVE_PACKAGE = path.join( + REACT_NATIVE_PACKAGE_DIR, + 'react-native-*.tgz', + ); - describe('Set up Verdaccio'); - VERDACCIO_PID = setupVerdaccio(); + describe('Set up Verdaccio'); + VERDACCIO_PID = setupVerdaccio(); - describe('Build and publish packages'); - exec('node ./scripts/build/build.js', {cwd: REPO_ROOT}); + describe('Build and publish packages'); + exec('node ./scripts/build/build.js', {cwd: REPO_ROOT}); - forEachPackage( - (packageAbsolutePath, packageRelativePathFromRoot, packageManifest) => { - if (packageManifest.private) { - return; - } + const packages = await getPackages({ + includeReactNative: false, + includePrivate: false, + }); + for (const {path: packageAbsolutePath} of Object.values(packages)) { exec( 'npm publish --registry http://localhost:4873 --yes --access public', {cwd: packageAbsolutePath}, ); - }, - ); - - describe('Scaffold a basic React Native app from template'); - execFileSync('rsync', [ - '-a', - `${REPO_ROOT}/packages/react-native/template`, - REACT_NATIVE_TEMP_DIR, - ]); - cd(REACT_NATIVE_APP_DIR); - - mv('_bundle', '.bundle'); - mv('_eslintrc.js', '.eslintrc.js'); - mv('_prettierrc.js', '.prettierrc.js'); - mv('_watchmanconfig', '.watchmanconfig'); - fs.writeFileSync('.npmrc', 'registry=http://localhost:4873'); - - describe('Install React Native package'); - exec(`npm install ${REACT_NATIVE_PACKAGE}`); - - describe('Install node_modules'); - if ( - tryExecNTimes( - () => { - return exec('npm install').code; - }, - numberOfRetries, - () => exec('sleep 10s'), - ) - ) { - throw new Error( - 'Failed to execute npm install. Most common reason is npm registry connectivity, try again', - ); - } - exec('rm -rf ./node_modules/react-native/template'); - - if (argv.android) { - describe('Install end-to-end framework'); - if ( - tryExecNTimes( - () => - exec( - 'yarn add --dev appium@1.11.1 mocha@2.4.5 wd@1.11.1 colors@1.0.3 pretty-data2@0.40.1', - {silent: true}, - ).code, - numberOfRetries, - ) - ) { - throw new Error( - 'Failed to install appium. Most common reason is npm registry connectivity, try again.', - ); - } - cp(`${SCRIPTS_DIR}/android-e2e-test.js`, 'android-e2e-test.js'); - cd('android'); - describe('Download Maven deps'); - exec('./gradlew :app:copyDownloadableDepsToLibs'); - cd('..'); - - describe('Generate key'); - exec('rm android/app/debug.keystore'); - if ( - exec( - 'keytool -genkey -v -keystore android/app/debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"', - ).code - ) { - throw new Error('Key could not be generated'); } - // $FlowFixMe[incompatible-type] - describe(`Start appium server, ${APPIUM_PID}`); - const appiumProcess = spawn('node', ['./node_modules/.bin/appium']); - APPIUM_PID = appiumProcess.pid; + describe('Scaffold a basic React Native app from template'); + execFileSync('rsync', [ + '-a', + `${REPO_ROOT}/packages/react-native/template`, + REACT_NATIVE_TEMP_DIR, + ]); + cd(REACT_NATIVE_APP_DIR); - describe('Build the app'); - if (exec('react-native run-android').code) { - throw new Error('Could not execute react-native run-android'); - } + mv('_bundle', '.bundle'); + mv('_eslintrc.js', '.eslintrc.js'); + mv('_prettierrc.js', '.prettierrc.js'); + mv('_watchmanconfig', '.watchmanconfig'); + fs.writeFileSync('.npmrc', 'registry=http://localhost:4873'); - // $FlowFixMe[incompatible-type] - describe(`Start Metro, ${SERVER_PID}`); - // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn - const packagerProcess = spawn('yarn', ['start', '--max-workers 1']); - SERVER_PID = packagerProcess.pid; - // wait a bit to allow packager to startup - exec('sleep 15s'); - describe('Test: Android end-to-end test'); + describe('Install React Native package'); + exec(`npm install ${REACT_NATIVE_PACKAGE}`); + + describe('Install node_modules'); if ( tryExecNTimes( () => { - return exec('node node_modules/.bin/_mocha android-e2e-test.js').code; + return exec('npm install').code; }, numberOfRetries, () => exec('sleep 10s'), ) ) { throw new Error( - 'Failed to run Android end-to-end tests. Most likely the code is broken.', + 'Failed to execute npm install. Most common reason is npm registry connectivity, try again', ); } - } + exec('rm -rf ./node_modules/react-native/template'); - if (argv.ios) { - cd('ios'); - // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn - const packagerEnv = Object.create(process.env); - // $FlowFixMe[prop-missing] - packagerEnv.REACT_NATIVE_MAX_WORKERS = 1; - describe('Start Metro'); - const packagerProcess = spawn('yarn', ['start'], { - stdio: 'inherit', - env: packagerEnv, - }); - SERVER_PID = packagerProcess.pid; - exec('sleep 15s'); - // prepare cache to reduce chances of possible red screen "Can't find variable __fbBatchedBridge..." - exec( - 'response=$(curl --write-out %{http_code} --silent --output /dev/null localhost:8081/index.bundle?platform=ios&dev=true)', - ); - echo(`Metro is running, ${SERVER_PID}`); + if (argv.android) { + describe('Install end-to-end framework'); + if ( + tryExecNTimes( + () => + exec( + 'yarn add --dev appium@1.11.1 mocha@2.4.5 wd@1.11.1 colors@1.0.3 pretty-data2@0.40.1', + {silent: true}, + ).code, + numberOfRetries, + ) + ) { + throw new Error( + 'Failed to install appium. Most common reason is npm registry connectivity, try again.', + ); + } + cp(`${SCRIPTS_DIR}/android-e2e-test.js`, 'android-e2e-test.js'); + cd('android'); + describe('Download Maven deps'); + exec('./gradlew :app:copyDownloadableDepsToLibs'); + cd('..'); - describe('Install CocoaPod dependencies'); - exec('bundle exec pod install'); + describe('Generate key'); + exec('rm android/app/debug.keystore'); + if ( + exec( + 'keytool -genkey -v -keystore android/app/debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"', + ).code + ) { + throw new Error('Key could not be generated'); + } - describe('Test: iOS end-to-end test'); - if ( - // TODO: Get target OS and simulator from .tests.env - tryExecNTimes( - () => { - return exec( - [ - 'xcodebuild', - '-workspace', - '"HelloWorld.xcworkspace"', - '-destination', - '"platform=iOS Simulator,name=iPhone 8,OS=13.3"', - '-scheme', - '"HelloWorld"', - '-sdk', - 'iphonesimulator', - '-UseModernBuildSystem=NO', - 'test', - ].join(' ') + - ' | ' + - [ - 'xcbeautify', - '--report', - 'junit', - '--reportPath', - '"~/react-native/reports/junit/iOS-e2e/results.xml"', - ].join(' ') + - ' && exit ${PIPESTATUS[0]}', - ).code; - }, - numberOfRetries, - () => exec('sleep 10s'), - ) - ) { - throw new Error( - 'Failed to run iOS end-to-end tests. Most likely the code is broken.', - ); - } - cd('..'); - } + // $FlowFixMe[incompatible-type] + describe(`Start appium server, ${APPIUM_PID}`); + const appiumProcess = spawn('node', ['./node_modules/.bin/appium']); + APPIUM_PID = appiumProcess.pid; - if (argv.js) { - // Check the packager produces a bundle (doesn't throw an error) - describe('Test: Verify packager can generate an Android bundle'); - if ( - exec( - 'yarn react-native bundle --verbose --entry-file index.js --platform android --dev true --bundle-output android-bundle.js --max-workers 1', - ).code - ) { - throw new Error('Could not build Android bundle'); + describe('Build the app'); + if (exec('react-native run-android').code) { + throw new Error('Could not execute react-native run-android'); + } + + // $FlowFixMe[incompatible-type] + describe(`Start Metro, ${SERVER_PID}`); + // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn + const packagerProcess = spawn('yarn', ['start', '--max-workers 1']); + SERVER_PID = packagerProcess.pid; + // wait a bit to allow packager to startup + exec('sleep 15s'); + describe('Test: Android end-to-end test'); + if ( + tryExecNTimes( + () => { + return exec('node node_modules/.bin/_mocha android-e2e-test.js') + .code; + }, + numberOfRetries, + () => exec('sleep 10s'), + ) + ) { + throw new Error( + 'Failed to run Android end-to-end tests. Most likely the code is broken.', + ); + } } - describe('Test: Verify packager can generate an iOS bundle'); - if ( + if (argv.ios) { + cd('ios'); + // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn + const packagerEnv = Object.create(process.env); + // $FlowFixMe[prop-missing] + packagerEnv.REACT_NATIVE_MAX_WORKERS = 1; + describe('Start Metro'); + const packagerProcess = spawn('yarn', ['start'], { + stdio: 'inherit', + env: packagerEnv, + }); + SERVER_PID = packagerProcess.pid; + exec('sleep 15s'); + // prepare cache to reduce chances of possible red screen "Can't find variable __fbBatchedBridge..." exec( - 'yarn react-native bundle --entry-file index.js --platform ios --dev true --bundle-output ios-bundle.js --max-workers 1', - ).code - ) { - throw new Error('Could not build iOS bundle'); - } + 'response=$(curl --write-out %{http_code} --silent --output /dev/null localhost:8081/index.bundle?platform=ios&dev=true)', + ); + echo(`Metro is running, ${SERVER_PID}`); - describe('Test: TypeScript typechecking'); - if (exec('yarn tsc').code) { - throw new Error('Typechecking errors were found'); - } + describe('Install CocoaPod dependencies'); + exec('bundle exec pod install'); - describe('Test: Jest tests'); - if (exec('yarn test').code) { - throw new Error('Jest tests failed'); + describe('Test: iOS end-to-end test'); + if ( + // TODO: Get target OS and simulator from .tests.env + tryExecNTimes( + () => { + return exec( + [ + 'xcodebuild', + '-workspace', + '"HelloWorld.xcworkspace"', + '-destination', + '"platform=iOS Simulator,name=iPhone 8,OS=13.3"', + '-scheme', + '"HelloWorld"', + '-sdk', + 'iphonesimulator', + '-UseModernBuildSystem=NO', + 'test', + ].join(' ') + + ' | ' + + [ + 'xcbeautify', + '--report', + 'junit', + '--reportPath', + '"~/react-native/reports/junit/iOS-e2e/results.xml"', + ].join(' ') + + ' && exit ${PIPESTATUS[0]}', + ).code; + }, + numberOfRetries, + () => exec('sleep 10s'), + ) + ) { + throw new Error( + 'Failed to run iOS end-to-end tests. Most likely the code is broken.', + ); + } + cd('..'); } - // TODO: ESLint infinitely hangs when running in the environment created by - // this script, but not projects generated by `react-native init`. - /* + if (argv.js) { + // Check the packager produces a bundle (doesn't throw an error) + describe('Test: Verify packager can generate an Android bundle'); + if ( + exec( + 'yarn react-native bundle --verbose --entry-file index.js --platform android --dev true --bundle-output android-bundle.js --max-workers 1', + ).code + ) { + throw new Error('Could not build Android bundle'); + } + + describe('Test: Verify packager can generate an iOS bundle'); + if ( + exec( + 'yarn react-native bundle --entry-file index.js --platform ios --dev true --bundle-output ios-bundle.js --max-workers 1', + ).code + ) { + throw new Error('Could not build iOS bundle'); + } + + describe('Test: TypeScript typechecking'); + if (exec('yarn tsc').code) { + throw new Error('Typechecking errors were found'); + } + + describe('Test: Jest tests'); + if (exec('yarn test').code) { + throw new Error('Jest tests failed'); + } + + // TODO: ESLint infinitely hangs when running in the environment created by + // this script, but not projects generated by `react-native init`. + /* describe('Test: ESLint/Prettier linting and formatting'); if (exec('yarn lint').code) { echo('linting errors were found'); exitCode = 1; throw Error(exitCode); }*/ + } + exitCode = 0; + } finally { + describe('Clean up'); + if (SERVER_PID) { + echo(`Killing packager ${SERVER_PID}`); + exec(`kill -9 ${SERVER_PID}`); + // this is quite drastic but packager starts a daemon that we can't kill by killing the parent process + // it will be fixed in April (quote David Aurelio), so until then we will kill the zombie by the port number + exec("lsof -i tcp:8081 | awk 'NR!=1 {print $2}' | xargs kill"); + } + if (APPIUM_PID) { + echo(`Killing appium ${APPIUM_PID}`); + exec(`kill -9 ${APPIUM_PID}`); + } + if (VERDACCIO_PID) { + echo(`Killing verdaccio ${VERDACCIO_PID}`); + exec(`kill -9 ${VERDACCIO_PID}`); + } } - exitCode = 0; -} finally { - describe('Clean up'); - if (SERVER_PID) { - echo(`Killing packager ${SERVER_PID}`); - exec(`kill -9 ${SERVER_PID}`); - // this is quite drastic but packager starts a daemon that we can't kill by killing the parent process - // it will be fixed in April (quote David Aurelio), so until then we will kill the zombie by the port number - exec("lsof -i tcp:8081 | awk 'NR!=1 {print $2}' | xargs kill"); - } - if (APPIUM_PID) { - echo(`Killing appium ${APPIUM_PID}`); - exec(`kill -9 ${APPIUM_PID}`); - } - if (VERDACCIO_PID) { - echo(`Killing verdaccio ${VERDACCIO_PID}`); - exec(`kill -9 ${VERDACCIO_PID}`); - } + exit(exitCode); +} + +if (require.main === module) { + // eslint-disable-next-line no-void + void main(); } -exit(exitCode); diff --git a/scripts/monorepo/__tests__/bump-package-version-test.js b/scripts/monorepo/__tests__/bump-package-version-test.js index 1481e5ac4083fa..00dcccb7359d2e 100644 --- a/scripts/monorepo/__tests__/bump-package-version-test.js +++ b/scripts/monorepo/__tests__/bump-package-version-test.js @@ -16,8 +16,6 @@ jest.mock('fs', () => ({ readFileSync: jest.fn(() => '{}'), })); -jest.mock('../for-each-package', () => callback => {}); - describe('bumpPackageVersionTest', () => { it('updates patch version of the package', () => { const mockedPackageLocation = '~/packages/assets'; diff --git a/scripts/monorepo/__tests__/for-each-package-test.js b/scripts/monorepo/__tests__/for-each-package-test.js deleted file mode 100644 index c3154d61940702..00000000000000 --- a/scripts/monorepo/__tests__/for-each-package-test.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -const forEachPackage = require('../for-each-package'); -const {readdirSync, readFileSync} = require('fs'); -const path = require('path'); - -jest.mock('fs', () => ({ - readdirSync: jest.fn(), - readFileSync: jest.fn(), -})); - -describe('forEachPackage', () => { - it('executes callback call with parameters', () => { - const callback = jest.fn(); - const mockedPackageManifest = '{"name": "my-new-package"}'; - const mockedParsedPackageManifest = JSON.parse(mockedPackageManifest); - const mockedPackageName = 'my-new-package'; - - readdirSync.mockImplementationOnce(() => [ - {name: mockedPackageName, isDirectory: () => true}, - ]); - readFileSync.mockImplementationOnce(() => mockedPackageManifest); - - forEachPackage(callback); - - expect(callback).toHaveBeenCalledWith( - path.join(__dirname, '..', '..', '..', 'packages', mockedPackageName), - path.join('packages', mockedPackageName), - mockedParsedPackageManifest, - ); - }); - - it('filters react-native folder by default', () => { - const callback = jest.fn(); - readdirSync.mockImplementationOnce(() => [ - {name: 'react-native', isDirectory: () => true}, - ]); - - forEachPackage(callback); - - expect(callback).not.toHaveBeenCalled(); - }); - - it('includes react-native, if such option is provided', () => { - const callback = jest.fn(); - const mockedPackageManifest = '{"name": "react-native"}'; - const mockedParsedPackageManifest = JSON.parse(mockedPackageManifest); - const mockedPackageName = 'react-native'; - - readdirSync.mockImplementationOnce(() => [ - {name: 'react-native', isDirectory: () => true}, - ]); - readFileSync.mockImplementationOnce(() => mockedPackageManifest); - - forEachPackage(callback, {includeReactNative: true}); - - expect(callback).toHaveBeenCalledWith( - path.join(__dirname, '..', '..', '..', 'packages', mockedPackageName), - path.join('packages', mockedPackageName), - mockedParsedPackageManifest, - ); - }); -}); diff --git a/scripts/monorepo/align-package-versions.js b/scripts/monorepo/align-package-versions.js index d4ca5fc36b6cf4..b30d4088b3f9a3 100644 --- a/scripts/monorepo/align-package-versions.js +++ b/scripts/monorepo/align-package-versions.js @@ -4,10 +4,16 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @flow * @format + * @oncall react_native */ -const forEachPackage = require('./for-each-package'); +/*:: +import type {PackageJson} from '../utils/monorepo'; +*/ + +const {getPackages} = require('../utils/monorepo'); const {readFileSync, writeFileSync} = require('fs'); const path = require('path'); @@ -19,12 +25,13 @@ const TEMPLATE_LOCATION = path.join( 'template', ); -const readJSONFile = pathToFile => JSON.parse(readFileSync(pathToFile)); +const readJSONFile = (pathToFile /*: string */) /*: PackageJson */ => + JSON.parse(readFileSync(pathToFile, 'utf-8')); const checkIfShouldUpdateDependencyPackageVersion = ( - consumerPackageAbsolutePath, - updatedPackageName, - updatedPackageVersion, + consumerPackageAbsolutePath /*: string */, + updatedPackageName /*: string */, + updatedPackageVersion /*: string */, ) => { const consumerPackageManifestPath = path.join( consumerPackageAbsolutePath, @@ -91,8 +98,18 @@ const checkIfShouldUpdateDependencyPackageVersion = ( } }; -const alignPackageVersions = () => { - forEachPackage((_, __, packageManifest) => { +async function alignPackageVersions() { + const allPackages = await getPackages({ + includeReactNative: true, + includePrivate: true, + }); + const packagesExcludingReactNative = Object.keys(allPackages).filter( + packageName => packageName !== 'react-native', + ); + + for (const packageName of packagesExcludingReactNative) { + const {packageJson: packageManifest} = allPackages[packageName]; + checkIfShouldUpdateDependencyPackageVersion( ROOT_LOCATION, packageManifest.name, @@ -105,16 +122,14 @@ const alignPackageVersions = () => { packageManifest.version, ); - forEachPackage( - pathToPackage => - checkIfShouldUpdateDependencyPackageVersion( - pathToPackage, - packageManifest.name, - packageManifest.version, - ), - {includeReactNative: true}, - ); - }); -}; + for (const {path: pathToPackage} of Object.values(allPackages)) { + checkIfShouldUpdateDependencyPackageVersion( + pathToPackage, + packageManifest.name, + packageManifest.version, + ); + } + } +} module.exports = alignPackageVersions; diff --git a/scripts/monorepo/bump-all-updated-packages/index.js b/scripts/monorepo/bump-all-updated-packages/index.js index b619c3129c4fbd..ae8bb555a6bd36 100644 --- a/scripts/monorepo/bump-all-updated-packages/index.js +++ b/scripts/monorepo/bump-all-updated-packages/index.js @@ -9,12 +9,14 @@ * @oncall react_native */ +const {REPO_ROOT} = require('../../consts'); const {getPackageVersionStrByTag} = require('../../npm-utils'); const { isReleaseBranch, parseVersion, } = require('../../releases/utils/version-utils'); const {getBranchName} = require('../../scm-utils'); +const {getPackages} = require('../../utils/monorepo'); const alignPackageVersions = require('../align-package-versions'); const checkForGitChanges = require('../check-for-git-changes'); const { @@ -24,7 +26,6 @@ const { NO_COMMIT_CHOICE, PUBLISH_PACKAGES_TAG, } = require('../constants'); -const forEachPackage = require('../for-each-package'); const bumpPackageVersion = require('./bump-package-version'); const detectPackageUnreleasedChanges = require('./bump-utils'); const chalk = require('chalk'); @@ -33,8 +34,6 @@ const inquirer = require('inquirer'); const path = require('path'); const {echo, exec, exit} = require('shelljs'); -const ROOT_LOCATION = path.join(__dirname, '..', '..', '..'); - const buildExecutor = ( packageAbsolutePath /*: string */, @@ -53,7 +52,7 @@ const buildExecutor = !detectPackageUnreleasedChanges( packageRelativePathFromRoot, packageName, - ROOT_LOCATION, + REPO_ROOT, ) ) { return; @@ -99,16 +98,6 @@ const buildExecutor = }); }; -const buildAllExecutors = () => { - const executors = []; - - forEachPackage((...params) => { - executors.push(buildExecutor(...params)); - }); - - return executors; -}; - const main = async () => { if (checkForGitChanges()) { echo( @@ -119,8 +108,18 @@ const main = async () => { exit(1); } - const executors = buildAllExecutors(); - for (const executor of executors) { + const packages = await getPackages({ + includeReactNative: false, + includePrivate: true, + }); + + for (const pkg of Object.values(packages)) { + const executor = buildExecutor( + pkg.path, + path.relative(REPO_ROOT, pkg.path), + pkg.packageJson, + ); + await executor() .catch(() => exit(1)) .then(() => echo()); @@ -132,7 +131,7 @@ const main = async () => { } echo('Aligning new versions across monorepo...'); - alignPackageVersions(); + await alignPackageVersions(); echo(chalk.green('Done!\n')); // Figure out the npm dist-tags we want for all monorepo packages we're bumping @@ -219,7 +218,7 @@ const main = async () => { case COMMIT_WITH_GENERIC_MESSAGE_CHOICE: { exec(`git commit -am "${GENERIC_COMMIT_MESSAGE}${tagString}"`, { - cwd: ROOT_LOCATION, + cwd: REPO_ROOT, silent: true, }); @@ -229,17 +228,17 @@ const main = async () => { case COMMIT_WITH_CUSTOM_MESSAGE_CHOICE: { // exec from shelljs currently does not support interactive input // https://github.com/shelljs/shelljs/wiki/FAQ#running-interactive-programs-with-exec - execSync('git commit -a', {cwd: ROOT_LOCATION, stdio: 'inherit'}); + execSync('git commit -a', {cwd: REPO_ROOT, stdio: 'inherit'}); const enteredCommitMessage = exec('git log -n 1 --format=format:%B', { - cwd: ROOT_LOCATION, + cwd: REPO_ROOT, silent: true, }).stdout.trim(); const commitMessageWithTag = enteredCommitMessage + `\n\n${PUBLISH_PACKAGES_TAG}${tagString}`; exec(`git commit --amend -m "${commitMessageWithTag}"`, { - cwd: ROOT_LOCATION, + cwd: REPO_ROOT, silent: true, }); diff --git a/scripts/monorepo/for-each-package.js b/scripts/monorepo/for-each-package.js deleted file mode 100644 index 49d7c9eee3f028..00000000000000 --- a/scripts/monorepo/for-each-package.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -const {PACKAGES_DIR} = require('../consts'); -const {readdirSync, readFileSync} = require('fs'); -const path = require('path'); - -const DEFAULT_OPTIONS /*: Options */ = {includeReactNative: false}; - -/*:: -type PackageJSON = { - name: string, - private?: ?boolean, - version: string, - dependencies: {[string]: string}, - devDependencies: {[string]: string}, - ... -}; - -type Options = { - includeReactNative?: ?boolean, -}; -*/ - -/** - * Function, which returns an array of all directories inside specified location - */ -const getDirectories = (source /*: string */) /*: Array */ => - readdirSync(source, {withFileTypes: true}) - .filter(file => file.isDirectory()) - .map(directory => directory.name.toString()); -/** - * Iterate through every package inside /packages (ignoring react-native) and call provided callback for each of them - * - * @deprecated Use scripts/releases/utils/monorepo.js#getPackages instead - */ -const forEachPackage = ( - callback /*: (string, string, PackageJSON) => void */, - options /*: Options */ = DEFAULT_OPTIONS, -) => { - const {includeReactNative} = options; - - // We filter react-native package on purpose, so that no CI's script will be executed for this package in future - // Unless includeReactNative options is provided - const packagesDirectories = getDirectories(PACKAGES_DIR).filter( - directoryName => - directoryName !== 'react-native' || includeReactNative === true, - ); - - packagesDirectories.forEach(packageDirectory => { - const packageAbsolutePath = path.join(PACKAGES_DIR, packageDirectory); - const packageRelativePathFromRoot = path.join('packages', packageDirectory); - - const packageManifest = JSON.parse( - readFileSync(path.join(packageAbsolutePath, 'package.json')).toString(), - ); - - callback(packageAbsolutePath, packageRelativePathFromRoot, packageManifest); - }); -}; - -module.exports = forEachPackage; diff --git a/scripts/monorepo/print/index.js b/scripts/monorepo/print/index.js index 5846837ddfaf02..4783c5c02f37b6 100644 --- a/scripts/monorepo/print/index.js +++ b/scripts/monorepo/print/index.js @@ -8,7 +8,7 @@ */ const {getVersionsBySpec} = require('../../npm-utils'); -const forEachPackage = require('../for-each-package'); +const {getPackages} = require('../../utils/monorepo'); const {exit} = require('shelljs'); const yargs = require('yargs'); @@ -41,40 +41,46 @@ function reversePatchComp(semverA, semverB) { return patchB - patchA; } -const main = () => { +async function main() { const data = []; - forEachPackage( - (_packageAbsolutePath, _packageRelativePathFromRoot, packageManifest) => { - const isPublic = !packageManifest.private; - if ( - type === 'all' || - (type === 'private' && !isPublic) || - (type === 'public' && isPublic) - ) { - const packageInfo = { - 'Public?': isPublic ? '\u{2705}' : '\u{274C}', - Name: packageManifest.name, - 'Version (main)': packageManifest.version, - }; + const packages = await getPackages({ + includeReactNative: true, + includePrivate: true, + }); - if (isPublic && minor !== 0) { - try { - const versions = getVersionsBySpec( - packageManifest.name, - `^0.${minor}.0`, - ).sort(reversePatchComp); - packageInfo[`Version (${minor})`] = versions[0]; - } catch (e) { - packageInfo[`Version (${minor})`] = e.message; - } + for (const {packageJson} of Object.values(packages)) { + const isPublic = !packageJson.private; + if ( + type === 'all' || + (type === 'private' && !isPublic) || + (type === 'public' && isPublic) + ) { + const packageInfo = { + 'Public?': isPublic ? '\u{2705}' : '\u{274C}', + Name: packageJson.name, + 'Version (main)': packageJson.version, + }; + + if (isPublic && minor !== 0) { + try { + const versions = getVersionsBySpec( + packageJson.name, + `^0.${minor}.0`, + ).sort(reversePatchComp); + packageInfo[`Version (${minor})`] = versions[0]; + } catch (e) { + packageInfo[`Version (${minor})`] = e.message; } - data.push(packageInfo); } - }, - {includeReactNative: true}, - ); + data.push(packageInfo); + } + } + console.table(data); exit(0); -}; +} -main(); +if (require.main === module) { + // eslint-disable-next-line no-void + void main(); +} diff --git a/scripts/npm-utils.js b/scripts/npm-utils.js index b127448c6856b0..8886b08122c0d5 100644 --- a/scripts/npm-utils.js +++ b/scripts/npm-utils.js @@ -34,8 +34,9 @@ type PackageJSON = { ... } type NpmPackageOptions = { - tags: ?Array, + tags: ?Array | ?Array, otp: ?string, + access?: ?('public' | 'restricted') } */ @@ -114,8 +115,8 @@ function getNpmInfo(buildType /*: BuildType */) /*: NpmInfo */ { prerelease != null ? 'next' : isLatest === true - ? 'latest' - : releaseBranchTag; + ? 'latest' + : releaseBranchTag; return { version, @@ -131,14 +132,21 @@ function publishPackage( packageOptions /*: NpmPackageOptions */, execOptions /*: ?ExecOptsSync */, ) /*: ShellString */ { - const {otp, tags} = packageOptions; - const tagsFlag = tags != null ? tags.map(t => ` --tag ${t}`).join('') : ''; + const {otp, tags, access} = packageOptions; + const tagsFlag = + tags != null + ? tags + .filter(Boolean) + .map(t => ` --tag ${t}`) + .join('') + : ''; const otpFlag = otp != null ? ` --otp ${otp}` : ''; + const accessFlag = access != null ? ` --access ${access}` : ''; const options = execOptions ? {...execOptions, cwd: packagePath} : {cwd: packagePath}; - return exec(`npm publish${tagsFlag}${otpFlag}`, options); + return exec(`npm publish${tagsFlag}${otpFlag}${accessFlag}`, options); } function diffPackages( diff --git a/scripts/release-testing/test-e2e-local.js b/scripts/release-testing/test-e2e-local.js index fbdd376f291a77..01efa244a5bb3e 100644 --- a/scripts/release-testing/test-e2e-local.js +++ b/scripts/release-testing/test-e2e-local.js @@ -27,6 +27,7 @@ const { prepareArtifacts, setupCircleCIArtifacts, } = require('./utils/testing-utils'); +const chalk = require('chalk'); const debug = require('debug')('test-e2e-local'); const fs = require('fs'); const path = require('path'); @@ -301,10 +302,10 @@ async function testRNTestProject( ); cd('..'); - exec('yarn ios'); + exec('npm run ios'); } else { // android - exec('yarn android'); + exec('npm run android'); } popd(); } @@ -329,7 +330,7 @@ async function main() { let circleCIArtifacts = await setupCircleCIArtifacts( // $FlowIgnoreError[prop-missing] - argv.circleCIToken, + argv.circleciToken, branchName, ); @@ -337,6 +338,15 @@ async function main() { await testRNTester(circleCIArtifacts, onReleaseBranch); } else { await testRNTestProject(circleCIArtifacts); + + console.warn( + chalk.yellow(` +================================================================================ +NOTE: Verdaccio may still be running on after this script has finished. Please +Force Quit via Activity Monitor. +================================================================================ + `), + ); } } diff --git a/scripts/releases-ci/__tests__/publish-npm-test.js b/scripts/releases-ci/__tests__/publish-npm-test.js index c8852d37a50179..00a4a25ee530f1 100644 --- a/scripts/releases-ci/__tests__/publish-npm-test.js +++ b/scripts/releases-ci/__tests__/publish-npm-test.js @@ -121,14 +121,14 @@ describe('publish-npm', () => { describe("publishNpm('nightly')", () => { beforeAll(() => { - jest.mock('../../releases/utils/monorepo', () => ({ - ...jest.requireActual('../../releases/utils/monorepo'), + jest.mock('../../utils/monorepo', () => ({ + ...jest.requireActual('../../utils/monorepo'), getPackages: getPackagesMock, })); }); afterAll(() => { - jest.unmock('../../releases/utils/monorepo'); + jest.unmock('../../utils/monorepo'); }); it('should publish', async () => { @@ -160,8 +160,14 @@ describe('publish-npm', () => { expect(setVersionMock).toBeCalledWith(expectedVersion); expect(generateAndroidArtifactsMock).toHaveBeenCalled(); expect(publishPackageMock.mock.calls).toEqual([ - ['path/to/monorepo/pkg-a', {otp: undefined, tags: ['nightly']}], - ['path/to/monorepo/pkg-b', {otp: undefined, tags: ['nightly']}], + [ + 'path/to/monorepo/pkg-a', + {otp: undefined, tags: ['nightly'], access: 'public'}, + ], + [ + 'path/to/monorepo/pkg-b', + {otp: undefined, tags: ['nightly'], access: 'public'}, + ], [ path.join(REPO_ROOT, 'packages', 'react-native'), {otp: undefined, tags: ['nightly']}, @@ -249,8 +255,14 @@ describe('publish-npm', () => { // Note that we don't call `publishPackage` for react-native, or monorepo/pkg-c expect(publishPackageMock.mock.calls).toEqual([ - ['path/to/monorepo/pkg-a', {otp: undefined, tags: ['nightly']}], - ['path/to/monorepo/pkg-b', {otp: undefined, tags: ['nightly']}], + [ + 'path/to/monorepo/pkg-a', + {otp: undefined, tags: ['nightly'], access: 'public'}, + ], + [ + 'path/to/monorepo/pkg-b', + {otp: undefined, tags: ['nightly'], access: 'public'}, + ], ]); expect(consoleLogMock.mock.calls).toEqual([ diff --git a/scripts/releases-ci/__tests__/publish-updated-packages-test.js b/scripts/releases-ci/__tests__/publish-updated-packages-test.js index 9f7845ba93e10d..c2b1918c819a53 100644 --- a/scripts/releases-ci/__tests__/publish-updated-packages-test.js +++ b/scripts/releases-ci/__tests__/publish-updated-packages-test.js @@ -21,7 +21,7 @@ const fetchMock = jest.fn(); jest.mock('child_process', () => ({execSync})); jest.mock('shelljs', () => ({exec: execMock})); -jest.mock('../../releases/utils/monorepo', () => ({ +jest.mock('../../utils/monorepo', () => ({ getPackages: getPackagesMock, })); // $FlowIgnore[cannot-write] diff --git a/scripts/releases-ci/prepare-package-for-release.js b/scripts/releases-ci/prepare-package-for-release.js index 7969b8b1ccd566..80362844cd6c40 100755 --- a/scripts/releases-ci/prepare-package-for-release.js +++ b/scripts/releases-ci/prepare-package-for-release.js @@ -11,12 +11,14 @@ 'use strict'; +const {RN_TESTER_DIR} = require('../consts'); const {setReactNativeVersion} = require('../releases/set-rn-version'); const {failIfTagExists} = require('../releases/utils/release-utils'); const { isReleaseBranch, parseVersion, } = require('../releases/utils/version-utils'); +const {execSync} = require('child_process'); const {echo, exec, exit} = require('shelljs'); const yargs = require('yargs'); @@ -68,8 +70,8 @@ async function main() { const buildType = isDryRun ? 'dry-run' : isReleaseBranch(branch) - ? 'release' - : 'nightly'; + ? 'release' + : 'nightly'; failIfTagExists(releaseVersion, buildType); @@ -95,11 +97,21 @@ async function main() { } // Release builds should commit the version bumps, and create tags. - echo('Updating RNTester Podfile.lock...'); - if (exec('source scripts/update_podfile_lock.sh && update_pods').code) { - echo('Failed to update RNTester Podfile.lock.'); - echo('Fix the issue, revert and try again.'); - exit(1); + try { + console.log('Updating RNTester Podfile.lock'); + execSync( + ` + bundle install; + bundle exec pod install; + `, + {cwd: RN_TESTER_DIR, stdio: 'inherit'}, + ); + } catch (e) { + console.error('Failed to update RNTester Podfile.lock.'); + console.error('Fix the issue, revert and try again.'); + + process.exitCode = 1; + return; } echo(`Local checkout has been prepared for release version ${version}.`); diff --git a/scripts/releases-ci/publish-npm.js b/scripts/releases-ci/publish-npm.js index ddb38248f96b1e..7d2d47d02cfdee 100755 --- a/scripts/releases-ci/publish-npm.js +++ b/scripts/releases-ci/publish-npm.js @@ -20,11 +20,11 @@ const {getNpmInfo, publishPackage} = require('../npm-utils'); const {removeNewArchFlags} = require('../releases/remove-new-arch-flags'); const {setReactNativeVersion} = require('../releases/set-rn-version'); const setVersion = require('../releases/set-version'); -const {getPackages} = require('../releases/utils/monorepo'); const { generateAndroidArtifacts, publishAndroidArtifactsToMaven, } = require('../releases/utils/release-utils'); +const {getPackages} = require('../utils/monorepo'); const path = require('path'); const yargs = require('yargs'); @@ -75,9 +75,9 @@ async function publishMonorepoPackages(tag /*: ?string */) { for (const packageInfo of Object.values(projectInfo)) { console.log(`Publishing ${packageInfo.name}...`); const result = publishPackage(packageInfo.path, { - // $FlowFixMe[incompatible-call] tags: [tag], otp: process.env.NPM_CONFIG_OTP, + access: 'public', }); const spec = `${packageInfo.name}@${packageInfo.packageJson.version}`; @@ -122,7 +122,6 @@ async function publishNpm(buildType /*: BuildType */) /*: Promise */ { const packagePath = path.join(REPO_ROOT, 'packages', 'react-native'); const result = publishPackage(packagePath, { - // $FlowFixMe[incompatible-call] tags: [tag], otp: process.env.NPM_CONFIG_OTP, }); diff --git a/scripts/releases-ci/publish-updated-packages.js b/scripts/releases-ci/publish-updated-packages.js index f20a7d5b45bf95..56b4bd61003f5f 100644 --- a/scripts/releases-ci/publish-updated-packages.js +++ b/scripts/releases-ci/publish-updated-packages.js @@ -11,7 +11,7 @@ const {PUBLISH_PACKAGES_TAG} = require('../monorepo/constants'); const {publishPackage} = require('../npm-utils'); -const {getPackages} = require('../releases/utils/monorepo'); +const {getPackages} = require('../utils/monorepo'); const {parseArgs} = require('@pkgjs/parseargs'); const {execSync} = require('child_process'); diff --git a/scripts/releases-local/trigger-react-native-release.js b/scripts/releases-local/trigger-react-native-release.js index 266c5cccc3e1fc..8515f06c0f982e 100644 --- a/scripts/releases-local/trigger-react-native-release.js +++ b/scripts/releases-local/trigger-react-native-release.js @@ -14,15 +14,16 @@ const {REPO_ROOT} = require('../consts'); const detectPackageUnreleasedChanges = require('../monorepo/bump-all-updated-packages/bump-utils.js'); const checkForGitChanges = require('../monorepo/check-for-git-changes'); -const forEachPackage = require('../monorepo/for-each-package'); const {failIfTagExists} = require('../releases/utils/release-utils'); const { isReleaseBranch, parseVersion, } = require('../releases/utils/version-utils'); const {exitIfNotOnGit, getBranchName} = require('../scm-utils'); +const {getPackages} = require('../utils/monorepo'); const chalk = require('chalk'); const inquirer = require('inquirer'); +const path = require('path'); const request = require('request'); const {echo, exit} = require('shelljs'); const yargs = require('yargs'); @@ -48,6 +49,16 @@ let argv = yargs describe: 'Version you aim to release, ex. 0.67.0-rc.1, 0.66.3', required: true, }) + .option('dry-run', { + type: 'boolean', + default: false, + }) + // TODO(T182533699): Remove arg once new workflow is default + .option('use-new-workflow', { + describe: 'When set, triggers the experimental unified release workflow.', + type: 'boolean', + default: false, + }) .check(() => { const branch = exitIfNotOnGit( () => getBranchName(), @@ -77,7 +88,6 @@ const buildExecutor = if (packageManifest.private) { return; } - if ( detectPackageUnreleasedChanges( packageRelativePathFromRoot, @@ -92,22 +102,22 @@ const buildExecutor = } }; -const buildAllExecutors = () => { - const executors = []; - - forEachPackage((...params) => { - executors.push(buildExecutor(...params)); - }); - - return executors; -}; - async function exitIfUnreleasedPackages() { // use the other script to verify that there's no packages in the monorepo // that have changes that haven't been released - const executors = buildAllExecutors(); - for (const executor of executors) { + const packages = await getPackages({ + includeReactNative: false, + includePrivate: true, + }); + + for (const pkg of Object.values(packages)) { + const executor = buildExecutor( + pkg.path, + path.relative(REPO_ROOT, pkg.path), + pkg.packageJson, + ); + await executor().catch(error => { echo(chalk.red(error)); // need to throw upward @@ -116,6 +126,36 @@ async function exitIfUnreleasedPackages() { } } +/** + * Get the next version that all workspace packages will be set to. + * + * This approach is specific to the 0.74 release. For 0.75, the `--to-version` + * value will be used instead, setting all packages to a single version. + */ +async function getNextMonorepoPackagesVersion() /*: Promise */ { + // Based on last publish before this strategy + const _0_74_MIN_PATCH = 75; + + const packages = await getPackages({ + includeReactNative: false, + }); + + let patchVersion = _0_74_MIN_PATCH; + + for (const pkg of Object.values(packages)) { + const {version} = pkg.packageJson; + + if (!version.startsWith('0.74.') || version.endsWith('-main')) { + return null; + } + + const {patch} = parseVersion(version, 'release'); + patchVersion = Math.max(patchVersion, parseInt(patch, 10) + 1); + } + + return '0.74.' + patchVersion; +} + function triggerReleaseWorkflow(options /*: $FlowFixMe */) { return new Promise((resolve, reject) => { request(options, function (error, response, body) { @@ -144,11 +184,16 @@ async function main() { exit(1); } + // $FlowFixMe[prop-missing] + const useNewWorkflow /*: boolean */ = argv.useNewWorkflow; + // now check for unreleased packages - try { - await exitIfUnreleasedPackages(); - } catch (error) { - exit(1); + if (!useNewWorkflow) { + try { + await exitIfUnreleasedPackages(); + } catch (error) { + exit(1); + } } // $FlowFixMe[prop-missing] @@ -193,11 +238,39 @@ async function main() { return; } - const parameters = { - release_version: version, - release_latest: latest, - run_release_workflow: true, - }; + let nextMonorepoPackagesVersion; + + if (useNewWorkflow) { + nextMonorepoPackagesVersion = await getNextMonorepoPackagesVersion(); + + if (nextMonorepoPackagesVersion == null) { + // TODO(T182538198): Once this warning is hit, we can remove the + // `release_monorepo_packages_version` logic from here and the CI jobs, + // see other TODOs. + console.warn( + 'Warning: No longer on the 0.74-stable branch, meaning we will ' + + 'write all package versions identically. Please double-check the ' + + 'generated diff to see if this is correct.', + ); + nextMonorepoPackagesVersion = version; + } + } + + const parameters = useNewWorkflow + ? { + run_new_release_workflow: true, + release_version: version, + release_tag: npmTag, + // NOTE: Necessary for 0.74, should be dropped for 0.75+ + release_monorepo_packages_version: nextMonorepoPackagesVersion, + // $FlowFixMe[prop-missing] + release_dry_run: argv.dryRun, + } + : { + release_version: version, + release_latest: latest, + run_release_workflow: true, + }; const options = { method: 'POST', diff --git a/scripts/releases/__tests__/__snapshots__/set-rn-version-test.js.snap b/scripts/releases/__tests__/__snapshots__/set-rn-version-test.js.snap index a21f33faa62cfd..bef170436e374f 100644 --- a/scripts/releases/__tests__/__snapshots__/set-rn-version-test.js.snap +++ b/scripts/releases/__tests__/__snapshots__/set-rn-version-test.js.snap @@ -128,7 +128,8 @@ exports[`setReactNativeVersion should set nightly version: packages/react-native \\"dependencies\\": { \\"@react-native/package-a\\": \\"0.81.0-nightly-29282302-abcd1234\\" } -}" +} +" `; exports[`setReactNativeVersion should set release version: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = ` @@ -259,5 +260,6 @@ exports[`setReactNativeVersion should set release version: packages/react-native \\"dependencies\\": { \\"@react-native/package-a\\": \\"1000.0.0\\" } -}" +} +" `; diff --git a/scripts/releases/set-rn-version.js b/scripts/releases/set-rn-version.js index 0efca718782cbf..52ea23b183f412 100755 --- a/scripts/releases/set-rn-version.js +++ b/scripts/releases/set-rn-version.js @@ -110,8 +110,7 @@ async function setReactNativePackageVersion( await fs.writeFile( path.join(REPO_ROOT, 'packages/react-native/package.json'), - JSON.stringify(packageJson, null, 2), - 'utf-8', + JSON.stringify(packageJson, null, 2) + '\n', ); } diff --git a/scripts/releases/set-version/__tests__/__fixtures__/package.json b/scripts/releases/set-version/__tests__/__fixtures__/package.json new file mode 100644 index 00000000000000..f8a85180bf959f --- /dev/null +++ b/scripts/releases/set-version/__tests__/__fixtures__/package.json @@ -0,0 +1,8 @@ +{ + "name": "@react-native/monorepo", + "private": true, + "version": "1000.0.0", + "devDependencies": { + "@monorepo/pkg-c": "0.0.1" + } +} diff --git a/scripts/releases/set-version/__tests__/__snapshots__/set-version-test.js.snap b/scripts/releases/set-version/__tests__/__snapshots__/set-version-test.js.snap index 33c0979d209f4c..40393488d604cb 100644 --- a/scripts/releases/set-version/__tests__/__snapshots__/set-version-test.js.snap +++ b/scripts/releases/set-version/__tests__/__snapshots__/set-version-test.js.snap @@ -1,5 +1,17 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`setVersion updates monorepo for nightly: package.json 1`] = ` +"{ + \\"name\\": \\"@react-native/monorepo\\", + \\"private\\": true, + \\"version\\": \\"1000.0.0\\", + \\"devDependencies\\": { + \\"@monorepo/pkg-c\\": \\"0.81.0-nightly-29282302-abcd1234\\" + } +} +" +`; + exports[`setVersion updates monorepo for nightly: packages/monorepo-pkg-a/package.json 1`] = ` "{ \\"name\\": \\"@monorepo/pkg-a\\", @@ -43,126 +55,15 @@ exports[`setVersion updates monorepo for nightly: packages/monorepo-pkg-c/packag " `; -exports[`setVersion updates monorepo for nightly: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @generated by scripts/releases/set-rn-version.js - */ - -const version: $ReadOnly<{ - major: number, - minor: number, - patch: number, - prerelease: string | null, -}> = { - major: 0, - minor: 81, - patch: 0, - prerelease: 'nightly-29282302-abcd1234', -}; - -module.exports = {version}; -" -`; +exports[`setVersion updates monorepo for nightly: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for nightly: packages/react-native/React/Base/RCTVersion.m 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#import \\"RCTVersion.h\\" - -NSString* const RCTVersionMajor = @\\"major\\"; -NSString* const RCTVersionMinor = @\\"minor\\"; -NSString* const RCTVersionPatch = @\\"patch\\"; -NSString* const RCTVersionPrerelease = @\\"prerelease\\"; - - -NSDictionary* RCTGetReactNativeVersion(void) -{ - static NSDictionary* __rnVersion; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^(void){ - __rnVersion = @{ - RCTVersionMajor: @(0), - RCTVersionMinor: @(81), - RCTVersionPatch: @(0), - RCTVersionPrerelease: @\\"nightly-29282302-abcd1234\\", - }; - }); - return __rnVersion; -} -" -`; +exports[`setVersion updates monorepo for nightly: packages/react-native/React/Base/RCTVersion.m 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for nightly: packages/react-native/ReactAndroid/gradle.properties 1`] = ` -"VERSION_NAME=0.81.0-nightly-29282302-abcd1234 -" -`; +exports[`setVersion updates monorepo for nightly: packages/react-native/ReactAndroid/gradle.properties 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for nightly: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ +exports[`setVersion updates monorepo for nightly: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = `"[omitted]"`; -package com.facebook.react.modules.systeminfo; - -import com.facebook.react.common.MapBuilder; - -import java.util.Map; - -public class ReactNativeVersion { - public static final Map VERSION = MapBuilder.of( - \\"major\\", 0, - \\"minor\\", 81, - \\"patch\\", 0, - \\"prerelease\\", \\"nightly-29282302-abcd1234\\"); -} -" -`; - -exports[`setVersion updates monorepo for nightly: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -constexpr struct { - int32_t Major = 0; - int32_t Minor = 81; - int32_t Patch = 0; - std::string_view Prerelease = \\"nightly-29282302-abcd1234\\"; -} ReactNativeVersion; - -} // namespace facebook::react -" -`; +exports[`setVersion updates monorepo for nightly: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = `"[omitted]"`; exports[`setVersion updates monorepo for nightly: packages/react-native/package.json 1`] = ` "{ @@ -176,7 +77,8 @@ exports[`setVersion updates monorepo for nightly: packages/react-native/package. \\"metro-config\\": \\"^0.80.3\\", \\"metro-runtime\\": \\"^0.80.3\\" } -}" +} +" `; exports[`setVersion updates monorepo for nightly: packages/react-native/template/package.json 1`] = ` @@ -198,6 +100,18 @@ exports[`setVersion updates monorepo for nightly: packages/react-native/template " `; +exports[`setVersion updates monorepo for release-candidate: package.json 1`] = ` +"{ + \\"name\\": \\"@react-native/monorepo\\", + \\"private\\": true, + \\"version\\": \\"1000.0.0\\", + \\"devDependencies\\": { + \\"@monorepo/pkg-c\\": \\"0.80.0-rc.3\\" + } +} +" +`; + exports[`setVersion updates monorepo for release-candidate: packages/monorepo-pkg-a/package.json 1`] = ` "{ \\"name\\": \\"@monorepo/pkg-a\\", @@ -241,126 +155,15 @@ exports[`setVersion updates monorepo for release-candidate: packages/monorepo-pk " `; -exports[`setVersion updates monorepo for release-candidate: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @generated by scripts/releases/set-rn-version.js - */ - -const version: $ReadOnly<{ - major: number, - minor: number, - patch: number, - prerelease: string | null, -}> = { - major: 0, - minor: 80, - patch: 0, - prerelease: 'rc.3', -}; - -module.exports = {version}; -" -`; +exports[`setVersion updates monorepo for release-candidate: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for release-candidate: packages/react-native/React/Base/RCTVersion.m 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#import \\"RCTVersion.h\\" - -NSString* const RCTVersionMajor = @\\"major\\"; -NSString* const RCTVersionMinor = @\\"minor\\"; -NSString* const RCTVersionPatch = @\\"patch\\"; -NSString* const RCTVersionPrerelease = @\\"prerelease\\"; - - -NSDictionary* RCTGetReactNativeVersion(void) -{ - static NSDictionary* __rnVersion; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^(void){ - __rnVersion = @{ - RCTVersionMajor: @(0), - RCTVersionMinor: @(80), - RCTVersionPatch: @(0), - RCTVersionPrerelease: @\\"rc.3\\", - }; - }); - return __rnVersion; -} -" -`; +exports[`setVersion updates monorepo for release-candidate: packages/react-native/React/Base/RCTVersion.m 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactAndroid/gradle.properties 1`] = ` -"VERSION_NAME=0.80.0-rc.3 -" -`; +exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactAndroid/gradle.properties 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ +exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = `"[omitted]"`; -package com.facebook.react.modules.systeminfo; - -import com.facebook.react.common.MapBuilder; - -import java.util.Map; - -public class ReactNativeVersion { - public static final Map VERSION = MapBuilder.of( - \\"major\\", 0, - \\"minor\\", 80, - \\"patch\\", 0, - \\"prerelease\\", \\"rc.3\\"); -} -" -`; - -exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -constexpr struct { - int32_t Major = 0; - int32_t Minor = 80; - int32_t Patch = 0; - std::string_view Prerelease = \\"rc.3\\"; -} ReactNativeVersion; - -} // namespace facebook::react -" -`; +exports[`setVersion updates monorepo for release-candidate: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = `"[omitted]"`; exports[`setVersion updates monorepo for release-candidate: packages/react-native/package.json 1`] = ` "{ @@ -374,7 +177,8 @@ exports[`setVersion updates monorepo for release-candidate: packages/react-nativ \\"metro-config\\": \\"^0.80.3\\", \\"metro-runtime\\": \\"^0.80.3\\" } -}" +} +" `; exports[`setVersion updates monorepo for release-candidate: packages/react-native/template/package.json 1`] = ` @@ -396,6 +200,18 @@ exports[`setVersion updates monorepo for release-candidate: packages/react-nativ " `; +exports[`setVersion updates monorepo for stable version: package.json 1`] = ` +"{ + \\"name\\": \\"@react-native/monorepo\\", + \\"private\\": true, + \\"version\\": \\"1000.0.0\\", + \\"devDependencies\\": { + \\"@monorepo/pkg-c\\": \\"0.80.1\\" + } +} +" +`; + exports[`setVersion updates monorepo for stable version: packages/monorepo-pkg-a/package.json 1`] = ` "{ \\"name\\": \\"@monorepo/pkg-a\\", @@ -439,126 +255,15 @@ exports[`setVersion updates monorepo for stable version: packages/monorepo-pkg-c " `; -exports[`setVersion updates monorepo for stable version: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @generated by scripts/releases/set-rn-version.js - */ - -const version: $ReadOnly<{ - major: number, - minor: number, - patch: number, - prerelease: string | null, -}> = { - major: 0, - minor: 80, - patch: 1, - prerelease: null, -}; - -module.exports = {version}; -" -`; +exports[`setVersion updates monorepo for stable version: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for stable version: packages/react-native/React/Base/RCTVersion.m 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#import \\"RCTVersion.h\\" - -NSString* const RCTVersionMajor = @\\"major\\"; -NSString* const RCTVersionMinor = @\\"minor\\"; -NSString* const RCTVersionPatch = @\\"patch\\"; -NSString* const RCTVersionPrerelease = @\\"prerelease\\"; - - -NSDictionary* RCTGetReactNativeVersion(void) -{ - static NSDictionary* __rnVersion; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^(void){ - __rnVersion = @{ - RCTVersionMajor: @(0), - RCTVersionMinor: @(80), - RCTVersionPatch: @(1), - RCTVersionPrerelease: [NSNull null], - }; - }); - return __rnVersion; -} -" -`; +exports[`setVersion updates monorepo for stable version: packages/react-native/React/Base/RCTVersion.m 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for stable version: packages/react-native/ReactAndroid/gradle.properties 1`] = ` -"VERSION_NAME=0.80.1 -" -`; +exports[`setVersion updates monorepo for stable version: packages/react-native/ReactAndroid/gradle.properties 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo for stable version: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ +exports[`setVersion updates monorepo for stable version: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = `"[omitted]"`; -package com.facebook.react.modules.systeminfo; - -import com.facebook.react.common.MapBuilder; - -import java.util.Map; - -public class ReactNativeVersion { - public static final Map VERSION = MapBuilder.of( - \\"major\\", 0, - \\"minor\\", 80, - \\"patch\\", 1, - \\"prerelease\\", null); -} -" -`; - -exports[`setVersion updates monorepo for stable version: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -constexpr struct { - int32_t Major = 0; - int32_t Minor = 80; - int32_t Patch = 1; - std::string_view Prerelease = \\"\\"; -} ReactNativeVersion; - -} // namespace facebook::react -" -`; +exports[`setVersion updates monorepo for stable version: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = `"[omitted]"`; exports[`setVersion updates monorepo for stable version: packages/react-native/package.json 1`] = ` "{ @@ -572,7 +277,8 @@ exports[`setVersion updates monorepo for stable version: packages/react-native/p \\"metro-config\\": \\"^0.80.3\\", \\"metro-runtime\\": \\"^0.80.3\\" } -}" +} +" `; exports[`setVersion updates monorepo for stable version: packages/react-native/template/package.json 1`] = ` @@ -594,6 +300,18 @@ exports[`setVersion updates monorepo for stable version: packages/react-native/t " `; +exports[`setVersion updates monorepo on main after release cut: package.json 1`] = ` +"{ + \\"name\\": \\"@react-native/monorepo\\", + \\"private\\": true, + \\"version\\": \\"1000.0.0\\", + \\"devDependencies\\": { + \\"@monorepo/pkg-c\\": \\"0.82.0-main\\" + } +} +" +`; + exports[`setVersion updates monorepo on main after release cut: packages/monorepo-pkg-a/package.json 1`] = ` "{ \\"name\\": \\"@monorepo/pkg-a\\", @@ -637,126 +355,15 @@ exports[`setVersion updates monorepo on main after release cut: packages/monorep " `; -exports[`setVersion updates monorepo on main after release cut: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @generated by scripts/releases/set-rn-version.js - */ - -const version: $ReadOnly<{ - major: number, - minor: number, - patch: number, - prerelease: string | null, -}> = { - major: 1000, - minor: 0, - patch: 0, - prerelease: null, -}; - -module.exports = {version}; -" -`; +exports[`setVersion updates monorepo on main after release cut: packages/react-native/Libraries/Core/ReactNativeVersion.js 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo on main after release cut: packages/react-native/React/Base/RCTVersion.m 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#import \\"RCTVersion.h\\" - -NSString* const RCTVersionMajor = @\\"major\\"; -NSString* const RCTVersionMinor = @\\"minor\\"; -NSString* const RCTVersionPatch = @\\"patch\\"; -NSString* const RCTVersionPrerelease = @\\"prerelease\\"; - - -NSDictionary* RCTGetReactNativeVersion(void) -{ - static NSDictionary* __rnVersion; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^(void){ - __rnVersion = @{ - RCTVersionMajor: @(1000), - RCTVersionMinor: @(0), - RCTVersionPatch: @(0), - RCTVersionPrerelease: [NSNull null], - }; - }); - return __rnVersion; -} -" -`; +exports[`setVersion updates monorepo on main after release cut: packages/react-native/React/Base/RCTVersion.m 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactAndroid/gradle.properties 1`] = ` -"VERSION_NAME=1000.0.0 -" -`; +exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactAndroid/gradle.properties 1`] = `"[omitted]"`; -exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ +exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java 1`] = `"[omitted]"`; -package com.facebook.react.modules.systeminfo; - -import com.facebook.react.common.MapBuilder; - -import java.util.Map; - -public class ReactNativeVersion { - public static final Map VERSION = MapBuilder.of( - \\"major\\", 1000, - \\"minor\\", 0, - \\"patch\\", 0, - \\"prerelease\\", null); -} -" -`; - -exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = ` -"/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @generated by scripts/releases/set-rn-version.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -constexpr struct { - int32_t Major = 1000; - int32_t Minor = 0; - int32_t Patch = 0; - std::string_view Prerelease = \\"\\"; -} ReactNativeVersion; - -} // namespace facebook::react -" -`; +exports[`setVersion updates monorepo on main after release cut: packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h 1`] = `"[omitted]"`; exports[`setVersion updates monorepo on main after release cut: packages/react-native/package.json 1`] = ` "{ @@ -770,7 +377,8 @@ exports[`setVersion updates monorepo on main after release cut: packages/react-n \\"metro-config\\": \\"^0.80.3\\", \\"metro-runtime\\": \\"^0.80.3\\" } -}" +} +" `; exports[`setVersion updates monorepo on main after release cut: packages/react-native/template/package.json 1`] = ` diff --git a/scripts/releases/set-version/__tests__/set-version-test.js b/scripts/releases/set-version/__tests__/set-version-test.js index cb622dfd6ef2f1..5fd12fa24563d9 100644 --- a/scripts/releases/set-version/__tests__/set-version-test.js +++ b/scripts/releases/set-version/__tests__/set-version-test.js @@ -28,13 +28,20 @@ const writeFileMock = jest.fn().mockImplementation((filePath, content) => { customWriteFileExpect(filePath, content); } - expect(content).toMatchSnapshot( - // Make snapshot names resilient to platform path sep differences - path - .relative(path.join(__dirname, '__fixtures__'), filePath) - .split(path.sep) - .join('/'), - ); + const normalizedFilePath = path + .relative(path.join(__dirname, '__fixtures__'), filePath) + .split(path.sep) + .join('/'); + + if (!filePath.endsWith('package.json')) { + // Updated source and build files are already validated in the tests for + // `set-rn-version.js`. We also want to avoid polluting this test's + // snapshots with \@\generated. + expect('[omitted]').toMatchSnapshot(normalizedFilePath); + return; + } + + expect(content).toMatchSnapshot(normalizedFilePath); }); describe('setVersion', () => { diff --git a/scripts/releases/set-version/index.js b/scripts/releases/set-version/index.js index 443863565dc383..43654a853be400 100644 --- a/scripts/releases/set-version/index.js +++ b/scripts/releases/set-version/index.js @@ -12,47 +12,17 @@ 'use strict'; /*:: -import type {PackageJson} from '../utils/monorepo'; +import type {PackageJson} from '../../utils/monorepo'; */ +const { + getPackages, + getWorkspaceRoot, + updatePackageJson, +} = require('../../utils/monorepo'); const {setReactNativeVersion} = require('../set-rn-version'); -const {getPackages} = require('../utils/monorepo'); -const {promises: fs} = require('fs'); -const path = require('path'); const yargs = require('yargs'); -async function updatePackageJson( - packagePath /*: string */, - packageJson /*: PackageJson */, - newPackageVersions /*: $ReadOnly<{[string]: string}> */, -) /*: Promise */ { - const packageName = packageJson.name; - - if (packageName in newPackageVersions) { - packageJson.version = newPackageVersions[packageName]; - } - - for (const dependencyField of ['dependencies', 'devDependencies']) { - const deps = packageJson[dependencyField]; - - if (deps == null) { - continue; - } - - for (const dependency in newPackageVersions) { - if (dependency in deps) { - deps[dependency] = newPackageVersions[dependency]; - } - } - } - - return fs.writeFile( - path.join(packagePath, 'package.json'), - JSON.stringify(packageJson, null, 2) + '\n', - 'utf-8', - ); -} - /** * Sets a singular version for the entire monorepo. * @@ -61,7 +31,7 @@ async function updatePackageJson( * stays 1000.0.0. * * This script does the following: - * - Update all public npm packages under `/packages` to specified version + * - Update all packages under `/packages` to specified version * - Update all npm dependencies of a `/packages` package to specified version * - Update npm dependencies of the template app (`packages/react-native/template`) to specified version * - Update `packages/react-native` native source and build files to specified version if relevant @@ -71,7 +41,7 @@ async function setVersion( skipReactNativeVersion /*: boolean */ = false, ) /*: Promise */ { const packages = await getPackages({ - includePrivate: false, + includePrivate: true, includeReactNative: true, }); const newPackageVersions = Object.fromEntries( @@ -83,11 +53,12 @@ async function setVersion( newPackageVersions, ); - // Exclude the react-native package, since this (and the template) are - // handled by `setReactNativeVersion`. - const packagesToUpdate = Object.values(packages).filter( - pkg => pkg.name !== 'react-native', - ); + const packagesToUpdate = [ + await getWorkspaceRoot(), + // Exclude the react-native package, since this (and the template) are + // handled by `setReactNativeVersion`. + ...Object.values(packages).filter(pkg => pkg.name !== 'react-native'), + ]; await Promise.all( packagesToUpdate.map(({path: packagePath, packageJson}) => diff --git a/scripts/releases/utils/monorepo.js b/scripts/releases/utils/monorepo.js deleted file mode 100644 index 4908f951e8ee3a..00000000000000 --- a/scripts/releases/utils/monorepo.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - * @oncall react_native - */ - -const {REPO_ROOT} = require('../../consts'); -const fs = require('fs'); -const glob = require('glob'); -const path = require('path'); - -const WORKSPACES_CONFIG = 'packages/*'; - -/*:: -export type PackageJson = { - name: string, - version: string, - private?: boolean, - dependencies?: Record, - devDependencies?: Record, - ... -}; - -type PackagesFilter = $ReadOnly<{ - includeReactNative: boolean, - includePrivate?: boolean, -}>; - -export type PackageInfo = { - // The name of the package - name: string, - - // The absolute path to the package - path: string, - - // The parsed package.json contents - packageJson: PackageJson, -}; - -type ProjectInfo = { - [packageName: string]: PackageInfo, -}; -*/ - -/** - * Locates monrepo packages and returns a mapping of package names to their - * metadata. Considers Yarn workspaces under `packages/`. - */ -async function getPackages( - filter /*: PackagesFilter */, -) /*: Promise */ { - const {includeReactNative, includePrivate = false} = filter; - - const packagesEntries = await Promise.all( - glob - .sync(`${WORKSPACES_CONFIG}/package.json`, { - cwd: REPO_ROOT, - absolute: true, - ignore: includeReactNative - ? [] - : ['packages/react-native/package.json'], - }) - .map(async packageJsonPath => { - const packagePath = path.dirname(packageJsonPath); - const packageJson = JSON.parse( - await fs.promises.readFile(packageJsonPath, 'utf-8'), - ); - - return [ - packageJson.name, - { - name: packageJson.name, - path: packagePath, - packageJson, - }, - ]; - }), - ); - - return Object.fromEntries( - packagesEntries.filter( - ([_, {packageJson}]) => !packageJson.private || includePrivate, - ), - ); -} - -module.exports = { - getPackages, -}; diff --git a/scripts/update_podfile_lock.sh b/scripts/update_podfile_lock.sh deleted file mode 100755 index 4a65df8c9d909a..00000000000000 --- a/scripts/update_podfile_lock.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -# This script updates RNTester Podfile.lock after verifying the CocoaPods environment. -# Usage: -# source scripts/update_podfile_lock && update_pods - -THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -RNTESTER_DIR="$THIS_DIR/../packages/rn-tester" - -# Keep this separate for FB internal access. -validate_env () { - cd "$RNTESTER_DIR" || exit - bundle check || exit - cd "$THIS_DIR" || exit -} - -update_pods () { - cd "$RNTESTER_DIR" || exit - bundle install || exit - bundle check || exit - bundle exec pod install - cd "$THIS_DIR" || exit -} diff --git a/scripts/utils/monorepo.js b/scripts/utils/monorepo.js new file mode 100644 index 00000000000000..1c530e89f20a48 --- /dev/null +++ b/scripts/utils/monorepo.js @@ -0,0 +1,155 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + * @oncall react_native + */ + +const {REPO_ROOT} = require('../consts'); +const {promises: fs} = require('fs'); +const glob = require('glob'); +const path = require('path'); + +const WORKSPACES_CONFIG = 'packages/*'; + +/*:: +export type PackageJson = { + name: string, + version: string, + private?: boolean, + dependencies?: Record, + devDependencies?: Record, + ... +}; + +type PackagesFilter = $ReadOnly<{ + includeReactNative: boolean, + includePrivate?: boolean, +}>; + +export type PackageInfo = { + // The name of the package + name: string, + + // The absolute path to the package + path: string, + + // The parsed package.json contents + packageJson: PackageJson, +}; + +type ProjectInfo = { + [packageName: string]: PackageInfo, +}; +*/ + +/** + * Locates monrepo packages and returns a mapping of package names to their + * metadata. Considers Yarn workspaces under `packages/`. + */ +async function getPackages( + filter /*: PackagesFilter */, +) /*: Promise */ { + const {includeReactNative, includePrivate = false} = filter; + + const packagesEntries = await Promise.all( + glob + .sync(`${WORKSPACES_CONFIG}/package.json`, { + cwd: REPO_ROOT, + absolute: true, + ignore: includeReactNative + ? [] + : ['packages/react-native/package.json'], + }) + .map(parsePackageInfo), + ); + + return Object.fromEntries( + packagesEntries.filter( + ([_, {packageJson}]) => packageJson.private !== true || includePrivate, + ), + ); +} + +/** + * Get the parsed package metadata for the workspace root. + */ +async function getWorkspaceRoot() /*: Promise */ { + const [, packageInfo] = await parsePackageInfo( + path.join(REPO_ROOT, 'package.json'), + ); + + return packageInfo; +} + +async function parsePackageInfo( + packageJsonPath /*: string */, +) /*: Promise<[string, PackageInfo]> */ { + const packagePath = path.dirname(packageJsonPath); + const packageJson /*: PackageJson */ = JSON.parse( + await fs.readFile(packageJsonPath, 'utf-8'), + ); + + return [ + packageJson.name, + { + name: packageJson.name, + path: packagePath, + packageJson, + }, + ]; +} + +/** + * Update a given package with the package versions. + */ +async function updatePackageJson( + packagePath /*: string */, + packageJson /*: PackageJson */, + newPackageVersions /*: $ReadOnly<{[string]: string}> */, +) /*: Promise */ { + const packageName = packageJson.name; + + if (packageName in newPackageVersions) { + packageJson.version = newPackageVersions[packageName]; + } + + for (const dependencyField of ['dependencies', 'devDependencies']) { + const deps = packageJson[dependencyField]; + + if (deps == null) { + continue; + } + + for (const dependency in newPackageVersions) { + if (dependency in deps) { + deps[dependency] = newPackageVersions[dependency]; + } + } + } + + return writePackageJson(path.join(packagePath, 'package.json'), packageJson); +} + +/** + * Write a `package.json` file to disk. + */ +async function writePackageJson( + packageJsonPath /*: string */, + packageJson /*: PackageJson */, +) /*: Promise */ { + return fs.writeFile( + packageJsonPath, + JSON.stringify(packageJson, null, 2) + '\n', + ); +} + +module.exports = { + getPackages, + getWorkspaceRoot, + updatePackageJson, +}; diff --git a/settings.gradle.kts b/settings.gradle.kts index 21064d004c9efe..0919ad1f7a74bf 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -17,6 +17,7 @@ include( ":packages:react-native:ReactAndroid", ":packages:react-native:ReactAndroid:hermes-engine", ":packages:react-native:ReactAndroid:external-artifacts", + ":packages:react-native-popup-menu-android:android", ":packages:rn-tester:android:app") includeBuild("packages/react-native-gradle-plugin/") diff --git a/yarn.lock b/yarn.lock index 0437eb362646b0..72e2b95a0950bf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,6 +2,11 @@ # yarn lockfile v1 +"@aashutoshrathi/word-wrap@^1.2.3": + version "1.2.6" + resolved "https://registry.yarnpkg.com/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz#bd9154aec9983f77b3a034ecaa015c2e4201f6cf" + integrity sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA== + "@ampproject/remapping@^2.1.0": version "2.2.0" resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.2.0.tgz#56c133824780de3174aed5ab6834f3026790154d" @@ -1351,14 +1356,19 @@ resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.8.2.tgz#26585b7c0ba36362893d3a3c206ee0c57c389616" integrity sha512-0MGxAVt1m/ZK+LTJp/j0qF7Hz97D9O/FH9Ms3ltnyIdDD57cbb1ACIQTkbHvNXtWDv5TPq7w5Kq56+cNukbo7g== -"@eslint/eslintrc@^1.3.2": - version "1.4.1" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-1.4.1.tgz#af58772019a2d271b7e2d4c23ff4ddcba3ccfb3e" - integrity sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA== +"@eslint-community/regexpp@^4.6.1": + version "4.10.0" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.10.0.tgz#548f6de556857c8bb73bbee70c35dc82a2e74d63" + integrity sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA== + +"@eslint/eslintrc@^2.1.4": + version "2.1.4" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-2.1.4.tgz#388a269f0f25c1b6adc317b5a2c55714894c70ad" + integrity sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ== dependencies: ajv "^6.12.4" debug "^4.3.2" - espree "^9.4.0" + espree "^9.6.0" globals "^13.19.0" ignore "^5.2.0" import-fresh "^3.2.1" @@ -1366,6 +1376,11 @@ minimatch "^3.1.2" strip-json-comments "^3.1.1" +"@eslint/js@8.57.0": + version "8.57.0" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.0.tgz#a5417ae8427873f1dd08b70b3574b453e67b5f7f" + integrity sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g== + "@fastify/busboy@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@fastify/busboy/-/busboy-2.0.0.tgz#f22824caff3ae506b18207bad4126dbc6ccdb6b8" @@ -1817,29 +1832,24 @@ dependencies: "@hapi/hoek" "^9.0.0" -"@humanwhocodes/config-array@^0.10.4": - version "0.10.7" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.10.7.tgz#6d53769fd0c222767e6452e8ebda825c22e9f0dc" - integrity sha512-MDl6D6sBsaV452/QSdX+4CXIjZhIcI0PELsxUjk4U828yd58vk3bTIvk/6w5FY+4hIy9sLW0sfrV7K7Kc++j/w== +"@humanwhocodes/config-array@^0.11.14": + version "0.11.14" + resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.11.14.tgz#d78e481a039f7566ecc9660b4ea7fe6b1fec442b" + integrity sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg== dependencies: - "@humanwhocodes/object-schema" "^1.2.1" - debug "^4.1.1" - minimatch "^3.0.4" - -"@humanwhocodes/gitignore-to-minimatch@^1.0.2": - version "1.0.2" - resolved "https://registry.yarnpkg.com/@humanwhocodes/gitignore-to-minimatch/-/gitignore-to-minimatch-1.0.2.tgz#316b0a63b91c10e53f242efb4ace5c3b34e8728d" - integrity sha512-rSqmMJDdLFUsyxR6FMtD00nfQKKLFb1kv+qBbOVKqErvloEIJLo5bDTJTQNTYgeyp78JsA7u/NPi5jT1GR/MuA== + "@humanwhocodes/object-schema" "^2.0.2" + debug "^4.3.1" + minimatch "^3.0.5" "@humanwhocodes/module-importer@^1.0.1": version "1.0.1" resolved "https://registry.yarnpkg.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz#af5b2691a22b44be847b0ca81641c5fb6ad0172c" integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== -"@humanwhocodes/object-schema@^1.2.1": - version "1.2.1" - resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz#b520529ec21d8e5945a1851dfd1c32e94e39ff45" - integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA== +"@humanwhocodes/object-schema@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-2.0.2.tgz#d9fae00a2d5cb40f92cfe64b47ad749fbc38f917" + integrity sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw== "@isaacs/ttlcache@^1.4.1": version "1.4.1" @@ -2198,7 +2208,7 @@ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== -"@nodelib/fs.walk@^1.2.3": +"@nodelib/fs.walk@^1.2.3", "@nodelib/fs.walk@^1.2.8": version "1.2.8" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== @@ -2384,51 +2394,50 @@ optionalDependencies: npmlog "2 || ^3.1.0 || ^4.0.0" -"@react-native-community/cli-clean@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-clean/-/cli-clean-13.6.0.tgz#64d205d10d40de23f87fc20d91a8221c886cd130" - integrity sha512-pIaPxvvqdROohjnxLYkE5CDiuJWYrpzWobVu10an6QJVR2AKpmKMwoH0v5bfZXUCd1DppaYyqTdvx8navakOAA== +"@react-native-community/cli-clean@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-clean/-/cli-clean-14.0.0-alpha.0.tgz#fc7bfd187c897e5e6431f7122370886bf55dd5a7" + integrity sha512-sZPH2riywRcbV0wzfbZSGJOLxcsIt1jyB4tKmQUCcJMTd+UFUykqmYRiAw1rqAEIXzh80TVkt5GwNnLduLiyEQ== dependencies: - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" chalk "^4.1.2" execa "^5.0.0" fast-glob "^3.3.2" -"@react-native-community/cli-config@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-config/-/cli-config-13.6.0.tgz#a12eb3cf4799353eeb76b0ff662ad6013bf6ce36" - integrity sha512-KOesQvvntxgz0mT2uL+O7LrFNtA0y625FS1UdTplia9aJre3p8ZtHdyMfnXNp7ikbMcOTCmaMsH9GIqJUBswXg== +"@react-native-community/cli-config@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-config/-/cli-config-14.0.0-alpha.0.tgz#ad5a7e11b9d43aad7ceb0a2098c7acacd5cc6205" + integrity sha512-jq/mQkuOoCG+aFlQEnlPAvfWRPDOLNtBoKUQhr3db7Eex3hVlxIKqOkrcgUnDghwOdAhq+Kx2KE5brwI2ETMNw== dependencies: - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" chalk "^4.1.2" cosmiconfig "^5.1.0" deepmerge "^4.3.0" fast-glob "^3.3.2" joi "^17.2.1" -"@react-native-community/cli-debugger-ui@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-debugger-ui/-/cli-debugger-ui-13.6.0.tgz#a44effb910d084984c8dae608ff0a1344e0fca6f" - integrity sha512-w2Kr1HIcgBw1kNeSRp3lkQJeIAeVRfFNoCGN934NmtGUsex4iFf+VADGxo5f9EIF4t5zQSRz35AP5pcZfxMepg== +"@react-native-community/cli-debugger-ui@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-debugger-ui/-/cli-debugger-ui-14.0.0-alpha.0.tgz#eb8e59f4d7fc29759f0e4034e96d003cbdc8d03e" + integrity sha512-L4SOp2ktqpo4rbEK+cE49SpJgAhPj/g1nhSHami0g5kVbZjwEPugHdZlb8jxSeqCoy1kaDOt+nASInvMfg2q4Q== dependencies: serve-static "^1.13.1" -"@react-native-community/cli-doctor@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-doctor/-/cli-doctor-13.6.0.tgz#e3749a5601a1baf7d01eb9e601b79d4c77693abc" - integrity sha512-2FnKYaiSkxiwrv7PkVT18HmwNJiPNFuD7xvAs6CM1+PlQX91Qukfw7+DWzVz1Jm4XB7WEWgZj/0xA0m7ic+5BQ== +"@react-native-community/cli-doctor@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-doctor/-/cli-doctor-14.0.0-alpha.0.tgz#da539b9dddfc55d5d4ba49631fc427f1a265edd9" + integrity sha512-J7VmjyJlT9N3WryFsqFXriP9Fn7BlHqdkLa8P6TqABXxp7ZD21WrYgCqsDTR3pfBiyAFpOpyrgjO6d0RNu1SSQ== dependencies: - "@react-native-community/cli-config" "13.6.0" - "@react-native-community/cli-platform-android" "13.6.0" - "@react-native-community/cli-platform-apple" "13.6.0" - "@react-native-community/cli-platform-ios" "13.6.0" - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-config" "14.0.0-alpha.0" + "@react-native-community/cli-platform-android" "14.0.0-alpha.0" + "@react-native-community/cli-platform-apple" "14.0.0-alpha.0" + "@react-native-community/cli-platform-ios" "14.0.0-alpha.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" chalk "^4.1.2" command-exists "^1.2.8" deepmerge "^4.3.0" envinfo "^7.10.0" execa "^5.0.0" - hermes-profile-transformer "^0.0.6" node-stream-zip "^1.9.1" ora "^5.4.1" semver "^7.5.2" @@ -2436,54 +2445,44 @@ wcwidth "^1.0.1" yaml "^2.2.1" -"@react-native-community/cli-hermes@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-hermes/-/cli-hermes-13.6.0.tgz#af0a5baa33e6d5d4945d1b9022caaa19ae42dae3" - integrity sha512-PkzkB8gJ09UCJsmC5tqMnU8fgBOLiU0HI7uj2axtYLCj4IJ54J7ojRaXvisBUgDYv/yui7hPvuBIfqlA4vkowQ== - dependencies: - "@react-native-community/cli-platform-android" "13.6.0" - "@react-native-community/cli-tools" "13.6.0" - chalk "^4.1.2" - hermes-profile-transformer "^0.0.6" - -"@react-native-community/cli-platform-android@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-13.6.0.tgz#6f72a2f5e4fc1fc8edb39878179ab9091878b2f9" - integrity sha512-v0kkWU9ezm2n/tZe7lavck3aMaLL1D3YrVcIhgcYiIsZvHVgD48JOKDbqN+23yjoJP6pxVVnBA2AEwz1xLcpAQ== +"@react-native-community/cli-platform-android@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-14.0.0-alpha.0.tgz#ea3deec43f8cfb8f6fd7e00310e6c8aa255223ab" + integrity sha512-iin6jxiiFGFoO5yySFI1GPuFJVmPpoXI3+sgSHxpCA6sqSJ7iZilwa0jzDKV4XqWFstmijh2zZJgiJvv9srurw== dependencies: - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" chalk "^4.1.2" execa "^5.0.0" fast-glob "^3.3.2" fast-xml-parser "^4.2.4" logkitty "^0.7.1" -"@react-native-community/cli-platform-apple@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-apple/-/cli-platform-apple-13.6.0.tgz#71339336bdecb86b5d7b8503dab6c1e26f6e5aa5" - integrity sha512-VJM5iw9mSxLB6TKhjFf9axORASrSAbiChlZXGMZJD4MGEKrGQE67T16ztH6JxdAug9xcbDFrPekDwzuUXHslMw== +"@react-native-community/cli-platform-apple@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-apple/-/cli-platform-apple-14.0.0-alpha.0.tgz#a96d7bdd3776d711ea8c4027a38c1a7c3e554f48" + integrity sha512-8uTqmJu9wMRPStftzUUH7y5ZlYqzlkfaS1VDkz40V/ECnDQK24NzgHdm6UHckcydF4PomO4esEJUlBlMUZeK/w== dependencies: - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" chalk "^4.1.2" execa "^5.0.0" fast-glob "^3.3.2" fast-xml-parser "^4.0.12" ora "^5.4.1" -"@react-native-community/cli-platform-ios@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-ios/-/cli-platform-ios-13.6.0.tgz#99ccb4fb0464f63f6de63cbfab5ed61427ab9b50" - integrity sha512-0AcUr1WEmO79FsI4IVCO5izXf16uqY9naDezUAESMD4+UKdn/9Rrf6quBz6M4oowgI/zIagFS6JksFusP8pLFw== +"@react-native-community/cli-platform-ios@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-ios/-/cli-platform-ios-14.0.0-alpha.0.tgz#a4ef1642ef11b5edde5124a547613d6ee10aa78a" + integrity sha512-m3Eouxh7MvMmiroFdl52dJp6uP5pRasoe1sEvZ0vDzqhENCb36N7lzLlHVAd05FT9/xsC3wQvRElGiJXGhOxwg== dependencies: - "@react-native-community/cli-platform-apple" "13.6.0" + "@react-native-community/cli-platform-apple" "14.0.0-alpha.0" -"@react-native-community/cli-server-api@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-server-api/-/cli-server-api-13.6.0.tgz#20d7ec18edf3f945de25b0b7d9ab1c33298269af" - integrity sha512-3FU18/qLo2Mw1aYuIiLOaGiiPOLBeHJ+JZFRyobizvcKHEPHLc+Zt7+iFBPWiro7+pr0tdgV6EEwj1TxypUPpg== +"@react-native-community/cli-server-api@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-server-api/-/cli-server-api-14.0.0-alpha.0.tgz#3a7faea110ed6ec137052e38991aeff7944a5c9a" + integrity sha512-LA212P8nfQtLe/EVjCDFeBdzPUSexescisdhHWHlAla/V6+MzhLr+RD2Umrahha0er/Z1Y7pzayy4j/Vhky6xQ== dependencies: - "@react-native-community/cli-debugger-ui" "13.6.0" - "@react-native-community/cli-tools" "13.6.0" + "@react-native-community/cli-debugger-ui" "14.0.0-alpha.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" compression "^1.7.1" connect "^3.6.5" errorhandler "^1.5.1" @@ -2492,10 +2491,10 @@ serve-static "^1.13.1" ws "^7.5.1" -"@react-native-community/cli-tools@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-tools/-/cli-tools-13.6.0.tgz#157e18e894bdfb0ff0beca67cc7f80935492a389" - integrity sha512-lnbN3kcwYYT0y70jAfHX+VBjDN5Hb8X7GYy3ergYXrD8eBazthYGhx9wplaOfXGMtmvOSeLu/f13eDTNHPGXxQ== +"@react-native-community/cli-tools@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-tools/-/cli-tools-14.0.0-alpha.0.tgz#39d223807859d922a991dafc4bedf36c0b21301d" + integrity sha512-+ypuOKGQnUVWbxZqfflwzSUWLv3tUZBGmrpdSZoNMOtPiR+JyxgtHA9IODwTDYmuFWG+nyRZDBE+eHSk0zutww== dependencies: appdirsjs "^1.2.4" chalk "^4.1.2" @@ -2509,31 +2508,30 @@ shell-quote "^1.7.3" sudo-prompt "^9.0.0" -"@react-native-community/cli-types@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-types/-/cli-types-13.6.0.tgz#b30053d3409bc876660183e46b8e360bb35ceeba" - integrity sha512-F1M1qKdtMtFzCRvFLAFFTbc1BRHSOMkQA3XLOkpyDb9/DXDeQjkn6gAFczo1xQRJd4aUyvHaEOhSi1RJGEmlMg== +"@react-native-community/cli-types@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-types/-/cli-types-14.0.0-alpha.0.tgz#8877b21e271938750c061bbd7c9447ab961fc52d" + integrity sha512-1iQ6AgOxGz7oLlLSDOeGPD9ewPAW23OyYjVpv8+rcirZisHzqMT8zwuCtLo4vmAfKad2HB0yL2EjEDN2VFyNCQ== dependencies: joi "^17.2.1" -"@react-native-community/cli@13.6.0": - version "13.6.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-13.6.0.tgz#a5bd5ae8543923d539a4b787c1c88ea457f62e93" - integrity sha512-/NhynfYqCPVnxYa6i19+xM5ic8ebcOHQRUQZj9ZiBBZ9A7z34I2JBhSlm06IpUSJ4PgTEViYBMMJjFCRZ+a4wg== - dependencies: - "@react-native-community/cli-clean" "13.6.0" - "@react-native-community/cli-config" "13.6.0" - "@react-native-community/cli-debugger-ui" "13.6.0" - "@react-native-community/cli-doctor" "13.6.0" - "@react-native-community/cli-hermes" "13.6.0" - "@react-native-community/cli-server-api" "13.6.0" - "@react-native-community/cli-tools" "13.6.0" - "@react-native-community/cli-types" "13.6.0" +"@react-native-community/cli@14.0.0-alpha.0": + version "14.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-14.0.0-alpha.0.tgz#f7b93f38043e07cd98ea73ae716425bc192fe4d3" + integrity sha512-gl0HvvchqgDtjybHrdzkwJP/gcxmO6pTjaCXfMKu1BrGv763ZPtTyWC1hJyZD8e8srMGspuBqed870Rv+rfgbA== + dependencies: + "@react-native-community/cli-clean" "14.0.0-alpha.0" + "@react-native-community/cli-config" "14.0.0-alpha.0" + "@react-native-community/cli-debugger-ui" "14.0.0-alpha.0" + "@react-native-community/cli-doctor" "14.0.0-alpha.0" + "@react-native-community/cli-server-api" "14.0.0-alpha.0" + "@react-native-community/cli-tools" "14.0.0-alpha.0" + "@react-native-community/cli-types" "14.0.0-alpha.0" chalk "^4.1.2" commander "^9.4.1" deepmerge "^4.3.0" execa "^5.0.0" - find-up "^4.1.0" + find-up "^5.0.0" fs-extra "^8.1.0" graceful-fs "^4.1.3" prompts "^2.4.2" @@ -2876,16 +2874,16 @@ semver "^7.3.7" tsutils "^3.21.0" -"@typescript-eslint/eslint-plugin@^6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.7.4.tgz#057338df21b6062c2f2fc5999fbea8af9973ac6d" - integrity sha512-DAbgDXwtX+pDkAHwiGhqP3zWUGpW49B7eqmgpPtg+BKJXwdct79ut9+ifqOFPJGClGKSHXn2PTBatCnldJRUoA== +"@typescript-eslint/eslint-plugin@^7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.1.1.tgz#dd71fc5c7ecec745ca26ece506d84d203a205c0e" + integrity sha512-zioDz623d0RHNhvx0eesUmGfIjzrk18nSBC8xewepKXbBvN/7c1qImV7Hg8TI1URTxKax7/zxfxj3Uph8Chcuw== dependencies: "@eslint-community/regexpp" "^4.5.1" - "@typescript-eslint/scope-manager" "6.7.4" - "@typescript-eslint/type-utils" "6.7.4" - "@typescript-eslint/utils" "6.7.4" - "@typescript-eslint/visitor-keys" "6.7.4" + "@typescript-eslint/scope-manager" "7.1.1" + "@typescript-eslint/type-utils" "7.1.1" + "@typescript-eslint/utils" "7.1.1" + "@typescript-eslint/visitor-keys" "7.1.1" debug "^4.3.4" graphemer "^1.4.0" ignore "^5.2.4" @@ -2903,15 +2901,15 @@ "@typescript-eslint/typescript-estree" "5.59.5" debug "^4.3.4" -"@typescript-eslint/parser@^6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-6.7.4.tgz#23d1dd4fe5d295c7fa2ab651f5406cd9ad0bd435" - integrity sha512-I5zVZFY+cw4IMZUeNCU7Sh2PO5O57F7Lr0uyhgCJmhN/BuTlnc55KxPonR4+EM3GBdfiCyGZye6DgMjtubQkmA== +"@typescript-eslint/parser@^7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-7.1.1.tgz#6a9d0a5c9ccdf5dbd3cb8c949728c64e24e07d1f" + integrity sha512-ZWUFyL0z04R1nAEgr9e79YtV5LbafdOtN7yapNbn1ansMyaegl2D4bL7vHoJ4HPSc4CaLwuCVas8CVuneKzplQ== dependencies: - "@typescript-eslint/scope-manager" "6.7.4" - "@typescript-eslint/types" "6.7.4" - "@typescript-eslint/typescript-estree" "6.7.4" - "@typescript-eslint/visitor-keys" "6.7.4" + "@typescript-eslint/scope-manager" "7.1.1" + "@typescript-eslint/types" "7.1.1" + "@typescript-eslint/typescript-estree" "7.1.1" + "@typescript-eslint/visitor-keys" "7.1.1" debug "^4.3.4" "@typescript-eslint/scope-manager@5.59.5": @@ -2922,13 +2920,13 @@ "@typescript-eslint/types" "5.59.5" "@typescript-eslint/visitor-keys" "5.59.5" -"@typescript-eslint/scope-manager@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-6.7.4.tgz#a484a17aa219e96044db40813429eb7214d7b386" - integrity sha512-SdGqSLUPTXAXi7c3Ob7peAGVnmMoGzZ361VswK2Mqf8UOYcODiYvs8rs5ILqEdfvX1lE7wEZbLyELCW+Yrql1A== +"@typescript-eslint/scope-manager@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-7.1.1.tgz#9e301803ff8e21a74f50c6f89a4baccad9a48f93" + integrity sha512-cirZpA8bJMRb4WZ+rO6+mnOJrGFDd38WoXCEI57+CYBqta8Yc8aJym2i7vyqLL1vVYljgw0X27axkUXz32T8TA== dependencies: - "@typescript-eslint/types" "6.7.4" - "@typescript-eslint/visitor-keys" "6.7.4" + "@typescript-eslint/types" "7.1.1" + "@typescript-eslint/visitor-keys" "7.1.1" "@typescript-eslint/type-utils@5.59.5": version "5.59.5" @@ -2940,13 +2938,13 @@ debug "^4.3.4" tsutils "^3.21.0" -"@typescript-eslint/type-utils@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-6.7.4.tgz#847cd3b59baf948984499be3e0a12ff07373e321" - integrity sha512-n+g3zi1QzpcAdHFP9KQF+rEFxMb2KxtnJGID3teA/nxKHOVi3ylKovaqEzGBbVY2pBttU6z85gp0D00ufLzViQ== +"@typescript-eslint/type-utils@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-7.1.1.tgz#aee820d5bedd39b83c18585a526cc520ddb7a226" + integrity sha512-5r4RKze6XHEEhlZnJtR3GYeCh1IueUHdbrukV2KSlLXaTjuSfeVF8mZUVPLovidCuZfbVjfhi4c0DNSa/Rdg5g== dependencies: - "@typescript-eslint/typescript-estree" "6.7.4" - "@typescript-eslint/utils" "6.7.4" + "@typescript-eslint/typescript-estree" "7.1.1" + "@typescript-eslint/utils" "7.1.1" debug "^4.3.4" ts-api-utils "^1.0.1" @@ -2960,10 +2958,10 @@ resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-5.62.0.tgz#258607e60effa309f067608931c3df6fed41fd2f" integrity sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ== -"@typescript-eslint/types@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-6.7.4.tgz#5d358484d2be986980c039de68e9f1eb62ea7897" - integrity sha512-o9XWK2FLW6eSS/0r/tgjAGsYasLAnOWg7hvZ/dGYSSNjCh+49k5ocPN8OmG5aZcSJ8pclSOyVKP2x03Sj+RrCA== +"@typescript-eslint/types@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-7.1.1.tgz#ca33ba7cf58224fb46a84fea62593c2c53cd795f" + integrity sha512-KhewzrlRMrgeKm1U9bh2z5aoL4s7K3tK5DwHDn8MHv0yQfWFz/0ZR6trrIHHa5CsF83j/GgHqzdbzCXJ3crx0Q== "@typescript-eslint/typescript-estree@5.59.5": version "5.59.5" @@ -2978,16 +2976,17 @@ semver "^7.3.7" tsutils "^3.21.0" -"@typescript-eslint/typescript-estree@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.7.4.tgz#f2baece09f7bb1df9296e32638b2e1130014ef1a" - integrity sha512-ty8b5qHKatlNYd9vmpHooQz3Vki3gG+3PchmtsA4TgrZBKWHNjWfkQid7K7xQogBqqc7/BhGazxMD5vr6Ha+iQ== +"@typescript-eslint/typescript-estree@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-7.1.1.tgz#09c54af0151a1b05d0875c0fc7fe2ec7a2476ece" + integrity sha512-9ZOncVSfr+sMXVxxca2OJOPagRwT0u/UHikM2Rd6L/aB+kL/QAuTnsv6MeXtjzCJYb8PzrXarypSGIPx3Jemxw== dependencies: - "@typescript-eslint/types" "6.7.4" - "@typescript-eslint/visitor-keys" "6.7.4" + "@typescript-eslint/types" "7.1.1" + "@typescript-eslint/visitor-keys" "7.1.1" debug "^4.3.4" globby "^11.1.0" is-glob "^4.0.3" + minimatch "9.0.3" semver "^7.5.4" ts-api-utils "^1.0.1" @@ -3005,17 +3004,17 @@ eslint-scope "^5.1.1" semver "^7.3.7" -"@typescript-eslint/utils@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-6.7.4.tgz#2236f72b10e38277ee05ef06142522e1de470ff2" - integrity sha512-PRQAs+HUn85Qdk+khAxsVV+oULy3VkbH3hQ8hxLRJXWBEd7iI+GbQxH5SEUSH7kbEoTp6oT1bOwyga24ELALTA== +"@typescript-eslint/utils@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-7.1.1.tgz#bdeeb789eee4af5d3fb5400a69566d4dbf97ff3b" + integrity sha512-thOXM89xA03xAE0lW7alstvnyoBUbBX38YtY+zAUcpRPcq9EIhXPuJ0YTv948MbzmKh6e1AUszn5cBFK49Umqg== dependencies: "@eslint-community/eslint-utils" "^4.4.0" "@types/json-schema" "^7.0.12" "@types/semver" "^7.5.0" - "@typescript-eslint/scope-manager" "6.7.4" - "@typescript-eslint/types" "6.7.4" - "@typescript-eslint/typescript-estree" "6.7.4" + "@typescript-eslint/scope-manager" "7.1.1" + "@typescript-eslint/types" "7.1.1" + "@typescript-eslint/typescript-estree" "7.1.1" semver "^7.5.4" "@typescript-eslint/visitor-keys@5.59.5": @@ -3026,12 +3025,12 @@ "@typescript-eslint/types" "5.59.5" eslint-visitor-keys "^3.3.0" -"@typescript-eslint/visitor-keys@6.7.4": - version "6.7.4" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.7.4.tgz#80dfecf820fc67574012375859085f91a4dff043" - integrity sha512-pOW37DUhlTZbvph50x5zZCkFn3xzwkGtNoJHzIM3svpiSkJzwOYr/kVBaXmf+RAQiUDs1AHEZVNPg6UJCJpwRA== +"@typescript-eslint/visitor-keys@7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-7.1.1.tgz#e6538a58c9b157f03bcbb29e3b6a92fe39a6ab0d" + integrity sha512-yTdHDQxY7cSoCcAtiBzVzxleJhkGB9NncSIyMYe2+OGON1ZsP9zOPws/Pqgopa65jvknOjlk/w7ulPlZ78PiLQ== dependencies: - "@typescript-eslint/types" "6.7.4" + "@typescript-eslint/types" "7.1.1" eslint-visitor-keys "^3.4.1" "@typescript-eslint/visitor-keys@^5.42.0": @@ -3042,6 +3041,11 @@ "@typescript-eslint/types" "5.62.0" eslint-visitor-keys "^3.3.0" +"@ungap/structured-clone@^1.2.0": + version "1.2.0" + resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.2.0.tgz#756641adb587851b5ccb3e095daf27ae581c8406" + integrity sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ== + "@wdio/config@7.31.1": version "7.31.1" resolved "https://registry.yarnpkg.com/@wdio/config/-/config-7.31.1.tgz#53550a164c970403628525ecdc5e0c3f96a0ff30" @@ -3130,7 +3134,7 @@ agent-base@6: dependencies: debug "4" -ajv@^6.10.0, ajv@^6.12.3, ajv@^6.12.4: +ajv@^6.12.3, ajv@^6.12.4: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== @@ -4239,7 +4243,7 @@ debug@2.6.9, debug@^2.2.0, debug@^2.6.9: dependencies: ms "2.0.0" -debug@4, debug@4.3.4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2, debug@^4.3.4: +debug@4, debug@4.3.4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== @@ -4605,10 +4609,10 @@ eslint-plugin-ft-flow@^2.0.1: lodash "^4.17.21" string-natural-compare "^3.0.1" -eslint-plugin-jest@^26.5.3: - version "26.5.3" - resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-26.5.3.tgz#a3ceeaf4a757878342b8b00eca92379b246e5505" - integrity sha512-sICclUqJQnR1bFRZGLN2jnSVsYOsmPYYnroGCIMVSvTS3y8XR3yjzy1EcTQmk6typ5pRgyIWzbjqxK6cZHEZuQ== +eslint-plugin-jest@^27.9.0: + version "27.9.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-27.9.0.tgz#7c98a33605e1d8b8442ace092b60e9919730000b" + integrity sha512-QIT7FH7fNmd9n4se7FFKHbsLKGQiw885Ds6Y/sxKgCZ6natwCsXdgPOADnYVxN2QrRweF0FZWbJ6S7Rsn7llug== dependencies: "@typescript-eslint/utils" "^5.10.0" @@ -4708,7 +4712,7 @@ eslint-scope@5.1.1, eslint-scope@^5.1.1: esrecurse "^4.3.0" estraverse "^4.1.1" -eslint-scope@^7.1.1: +eslint-scope@^7.2.2: version "7.2.2" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-7.2.2.tgz#deb4f92563390f32006894af62a22dba1c46423f" integrity sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg== @@ -4716,19 +4720,12 @@ eslint-scope@^7.1.1: esrecurse "^4.3.0" estraverse "^5.2.0" -eslint-utils@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-3.0.0.tgz#8aebaface7345bb33559db0a1f13a1d2d48c3672" - integrity sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA== - dependencies: - eslint-visitor-keys "^2.0.0" - -eslint-visitor-keys@^2.0.0, eslint-visitor-keys@^2.1.0: +eslint-visitor-keys@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303" integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw== -eslint-visitor-keys@^3.0.0: +eslint-visitor-keys@^3.0.0, eslint-visitor-keys@^3.4.3: version "3.4.3" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== @@ -4738,52 +4735,51 @@ eslint-visitor-keys@^3.3.0, eslint-visitor-keys@^3.4.1: resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz#c22c48f48942d08ca824cc526211ae400478a994" integrity sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA== -eslint@^8.17.0, eslint@^8.19.0, eslint@^8.23.1: - version "8.23.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.23.1.tgz#cfd7b3f7fdd07db8d16b4ac0516a29c8d8dca5dc" - integrity sha512-w7C1IXCc6fNqjpuYd0yPlcTKKmHlHHktRkzmBPZ+7cvNBQuiNjx0xaMTjAJGCafJhQkrFJooREv0CtrVzmHwqg== +eslint@^8.17.0, eslint@^8.19.0, eslint@^8.57.0: + version "8.57.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.57.0.tgz#c786a6fd0e0b68941aaf624596fb987089195668" + integrity sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ== dependencies: - "@eslint/eslintrc" "^1.3.2" - "@humanwhocodes/config-array" "^0.10.4" - "@humanwhocodes/gitignore-to-minimatch" "^1.0.2" + "@eslint-community/eslint-utils" "^4.2.0" + "@eslint-community/regexpp" "^4.6.1" + "@eslint/eslintrc" "^2.1.4" + "@eslint/js" "8.57.0" + "@humanwhocodes/config-array" "^0.11.14" "@humanwhocodes/module-importer" "^1.0.1" - ajv "^6.10.0" + "@nodelib/fs.walk" "^1.2.8" + "@ungap/structured-clone" "^1.2.0" + ajv "^6.12.4" chalk "^4.0.0" cross-spawn "^7.0.2" debug "^4.3.2" doctrine "^3.0.0" escape-string-regexp "^4.0.0" - eslint-scope "^7.1.1" - eslint-utils "^3.0.0" - eslint-visitor-keys "^3.3.0" - espree "^9.4.0" - esquery "^1.4.0" + eslint-scope "^7.2.2" + eslint-visitor-keys "^3.4.3" + espree "^9.6.1" + esquery "^1.4.2" esutils "^2.0.2" fast-deep-equal "^3.1.3" file-entry-cache "^6.0.1" find-up "^5.0.0" - glob-parent "^6.0.1" - globals "^13.15.0" - globby "^11.1.0" - grapheme-splitter "^1.0.4" + glob-parent "^6.0.2" + globals "^13.19.0" + graphemer "^1.4.0" ignore "^5.2.0" - import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" - js-sdsl "^4.1.4" + is-path-inside "^3.0.3" js-yaml "^4.1.0" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash.merge "^4.6.2" minimatch "^3.1.2" natural-compare "^1.4.0" - optionator "^0.9.1" - regexpp "^3.2.0" + optionator "^0.9.3" strip-ansi "^6.0.1" - strip-json-comments "^3.1.0" text-table "^0.2.0" -espree@^9.0.0, espree@^9.4.0: +espree@^9.0.0, espree@^9.6.0, espree@^9.6.1: version "9.6.1" resolved "https://registry.yarnpkg.com/espree/-/espree-9.6.1.tgz#a2a17b8e434690a5432f2f8018ce71d331a48c6f" integrity sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ== @@ -4797,7 +4793,7 @@ esprima@^4.0.0, esprima@~4.0.0: resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== -esquery@^1.4.0: +esquery@^1.4.0, esquery@^1.4.2: version "1.5.0" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.5.0.tgz#6ce17738de8577694edd7361c57182ac8cb0db0b" integrity sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg== @@ -5137,23 +5133,23 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.2.tgz#64bfed5cb68fe3ca78b3eb214ad97b63bedce561" integrity sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA== -flow-api-translator@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/flow-api-translator/-/flow-api-translator-0.19.1.tgz#e5707f6ba96571ccfada231c013386504c8be3a0" - integrity sha512-3O5SZFKJNcpsyyBsnkh6VlHBVjjzQULtZSZSXgs/KKzvAKTnH8z+f5A49jqozsWzrfUcJziS6nrS3eVRsPYazA== +flow-api-translator@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/flow-api-translator/-/flow-api-translator-0.20.1.tgz#22d2be2f95edc6c397d00c0bf41d419a2eae35ba" + integrity sha512-RY/flm0omS6LjKna93HUUtx2bUf9qTX9i90RtUdZoVSB7u41nEAebmyM+mpOPsNqvCEIHQxxXs/22/PkQW1OCw== dependencies: "@babel/code-frame" "^7.16.0" "@typescript-eslint/visitor-keys" "^5.42.0" flow-enums-runtime "^0.0.6" - hermes-eslint "0.19.1" - hermes-estree "0.19.1" - hermes-parser "0.19.1" - hermes-transform "0.19.1" + hermes-eslint "0.20.1" + hermes-estree "0.20.1" + hermes-parser "0.20.1" + hermes-transform "0.20.1" -flow-bin@^0.228.0: - version "0.228.0" - resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.228.0.tgz#345dfd090c9edc074a14ad88d1558051ac124529" - integrity sha512-+Q6A+4nmhvf5yPXHxht9yWqRoto6Ith1HPU736iEghf+yGNzrnONyv+OlLG5TUH5cQegXasBmzBJKa3/+A8ZUA== +flow-bin@^0.231.0: + version "0.231.0" + resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.231.0.tgz#b9fde021e60ff6e40e4f0212b6c426fdde798ac7" + integrity sha512-nB5/rH+bUCIAXWagwIEYM0q/2M4mgkD5q16/eZyNx7sfqsmMkZLg0KmPH5hgvzq6PkVoeCoM8sjhPyzLW2wT+w== flow-enums-runtime@^0.0.6: version "0.0.6" @@ -5368,7 +5364,7 @@ glob-parent@^5.1.2, glob-parent@~5.1.2: dependencies: is-glob "^4.0.1" -glob-parent@^6.0.1: +glob-parent@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== @@ -5403,13 +5399,6 @@ globals@^11.1.0: resolved "https://registry.yarnpkg.com/globals/-/globals-11.8.0.tgz#c1ef45ee9bed6badf0663c5cb90e8d1adec1321d" integrity sha512-io6LkyPVuzCHBSQV9fmOwxZkUk6nIaGmxheLDgmuFv89j0fm2aqDbIXKAGfzCMHqz3HLF2Zf8WSG6VqMh2qFmA== -globals@^13.15.0: - version "13.21.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-13.21.0.tgz#163aae12f34ef502f5153cfbdd3600f36c63c571" - integrity sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg== - dependencies: - type-fest "^0.20.2" - globals@^13.19.0: version "13.20.0" resolved "https://registry.yarnpkg.com/globals/-/globals-13.20.0.tgz#ea276a1e508ffd4f1612888f9d1bad1e2717bf82" @@ -5537,14 +5526,14 @@ has@^1.0.3: dependencies: function-bind "^1.1.1" -hermes-eslint@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/hermes-eslint/-/hermes-eslint-0.19.1.tgz#289076a840c12a0682a4fe0ae394de021299ff7f" - integrity sha512-GCTgMq1zpR4z5AcBVzgjmirwLEA6TpYIAgmK37Ncpc8NTGnE3cgtPikLtQIVS5GrNtVNOBvPnbCARTu0Esojhw== +hermes-eslint@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/hermes-eslint/-/hermes-eslint-0.20.1.tgz#4a731b47a6d169bbd4514aaa74bd812fd90f3554" + integrity sha512-EhdvFV6RkPIJvbqN8oqFZO1oF4NlPWMjhMjCWkUJX1YL1MZMfkF7nSdx6RKTq6xK17yo+Bgv88L21xuH9GtRpw== dependencies: esrecurse "^4.3.0" - hermes-estree "0.19.1" - hermes-parser "0.19.1" + hermes-estree "0.20.1" + hermes-parser "0.20.1" hermes-estree@0.17.0: version "0.17.0" @@ -5556,10 +5545,10 @@ hermes-estree@0.18.2: resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.18.2.tgz#fd450fa1659cf074ceaa2ddeeb21674f3b2342f3" integrity sha512-KoLsoWXJ5o81nit1wSyEZnWUGy9cBna9iYMZBR7skKh7okYAYKqQ9/OczwpMHn/cH0hKDyblulGsJ7FknlfVxQ== -hermes-estree@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.19.1.tgz#d5924f5fac2bf0532547ae9f506d6db8f3c96392" - integrity sha512-daLGV3Q2MKk8w4evNMKwS8zBE/rcpA800nu1Q5kM08IKijoSnPe9Uo1iIxzPKRkn95IxxsgBMPeYHt3VG4ej2g== +hermes-estree@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.20.1.tgz#0b9a544cf883a779a8e1444b915fa365bef7f72d" + integrity sha512-SQpZK4BzR48kuOg0v4pb3EAGNclzIlqMj3Opu/mu7bbAoFw6oig6cEt/RAi0zTFW/iW6Iz9X9ggGuZTAZ/yZHg== hermes-parser@0.17.0: version "0.17.0" @@ -5575,31 +5564,24 @@ hermes-parser@0.18.2: dependencies: hermes-estree "0.18.2" -hermes-parser@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/hermes-parser/-/hermes-parser-0.19.1.tgz#1044348097165b7c93dc198a80b04ed5130d6b1a" - integrity sha512-Vp+bXzxYJWrpEuJ/vXxUsLnt0+y4q9zyi4zUlkLqD8FKv4LjIfOvP69R/9Lty3dCyKh0E2BU7Eypqr63/rKT/A== - dependencies: - hermes-estree "0.19.1" - -hermes-profile-transformer@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/hermes-profile-transformer/-/hermes-profile-transformer-0.0.6.tgz#bd0f5ecceda80dd0ddaae443469ab26fb38fc27b" - integrity sha512-cnN7bQUm65UWOy6cbGcCcZ3rpwW8Q/j4OP5aWRhEry4Z2t2aR1cjrbp0BS+KiBN0smvP1caBgAuxutvyvJILzQ== +hermes-parser@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/hermes-parser/-/hermes-parser-0.20.1.tgz#ad10597b99f718b91e283f81cbe636c50c3cff92" + integrity sha512-BL5P83cwCogI8D7rrDCgsFY0tdYUtmFP9XaXtl2IQjC+2Xo+4okjfXintlTxcIwl4qeGddEl28Z11kbVIw0aNA== dependencies: - source-map "^0.7.3" + hermes-estree "0.20.1" -hermes-transform@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/hermes-transform/-/hermes-transform-0.19.1.tgz#2c4896f5a1b9ad61bb2b37b2df5ceb2e60aa3b29" - integrity sha512-jfBgKhFBqQi6/K7u1/IfwRUZFzl0S628wftWsSCdDvMbzF1DReIz5A0Be47jDZ1eniLP6QF8fIsH/mP2ttylCw== +hermes-transform@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/hermes-transform/-/hermes-transform-0.20.1.tgz#910bd0ea7cc58eca4c0acadb413d779b70dd3803" + integrity sha512-gpetyzAQvuLXVWIk8/I2A/ei/5+o8eT+QuSGd8FcWpXoYxVkYjVKLVNE9xKLsEkk2wQ1tXODY5OeOZoaz9jL7Q== dependencies: "@babel/code-frame" "^7.16.0" esquery "^1.4.0" flow-enums-runtime "^0.0.6" - hermes-eslint "0.19.1" - hermes-estree "0.19.1" - hermes-parser "0.19.1" + hermes-eslint "0.20.1" + hermes-estree "0.20.1" + hermes-parser "0.20.1" homedir-polyfill@^1.0.0, homedir-polyfill@^1.0.1: version "1.0.3" @@ -5740,7 +5722,7 @@ import-fresh@^2.0.0: caller-path "^2.0.0" resolve-from "^3.0.0" -import-fresh@^3.0.0, import-fresh@^3.2.1: +import-fresh@^3.2.1: version "3.2.2" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.2.tgz#fc129c160c5d68235507f4331a6baad186bdbc3e" integrity sha512-cTPNrlvJT6twpYy+YmKUKrTSjWFs3bjYjAhCwm+z4EOCubZxAuO+hHpRN64TqjEaYSHs7tJAE0w1CKMGmsG/lw== @@ -5934,6 +5916,11 @@ is-number@^7.0.0: resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== +is-path-inside@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" + integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ== + is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" @@ -6532,11 +6519,6 @@ joi@^17.2.1: "@sideway/formula" "^3.0.0" "@sideway/pinpoint" "^2.0.0" -js-sdsl@^4.1.4: - version "4.1.4" - resolved "https://registry.yarnpkg.com/js-sdsl/-/js-sdsl-4.1.4.tgz#78793c90f80e8430b7d8dc94515b6c77d98a26a6" - integrity sha512-Y2/yD55y5jteOAmY50JbUZYwk3CP3wnLPEZnlR1w9oKhITrBEtAxwuWKebFf8hMrPMgbYwFoWK/lH2sBkErELw== - "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" @@ -7303,7 +7285,14 @@ mimic-response@^3.1.0: resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== -minimatch@^3.0.2, minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.2: +minimatch@9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.3.tgz#a6e00c3de44c3a542bfaae70abfc22420a6da825" + integrity sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg== + dependencies: + brace-expansion "^2.0.1" + +minimatch@^3.0.2, minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== @@ -7629,17 +7618,17 @@ open@^7.0.3: is-docker "^2.0.0" is-wsl "^2.1.1" -optionator@^0.9.1: - version "0.9.1" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" - integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== +optionator@^0.9.3: + version "0.9.3" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.3.tgz#007397d44ed1872fdc6ed31360190f81814e2c64" + integrity sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg== dependencies: + "@aashutoshrathi/word-wrap" "^1.2.3" deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" - word-wrap "^1.2.3" ora@^5.4.1: version "5.4.1" @@ -7878,14 +7867,14 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier-plugin-hermes-parser@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/prettier-plugin-hermes-parser/-/prettier-plugin-hermes-parser-0.19.1.tgz#63aa752003da4d70399e7c6bad8da99ac9fa1fd3" - integrity sha512-XK739fHNPrR03i//AV1e9g47fnqvQY2sUto30GbI5xyWRb+2XQlcL1kdA43yAj4Dfb45NyxtzooVvz2cSiNMzQ== +prettier-plugin-hermes-parser@0.20.1: + version "0.20.1" + resolved "https://registry.yarnpkg.com/prettier-plugin-hermes-parser/-/prettier-plugin-hermes-parser-0.20.1.tgz#a5f395ae77170813e631f4538c9ef29311b4db1d" + integrity sha512-T6dfa1++ckTxd3MbLxS6sTv1T3yvTu1drahNt3g34hyCzSwYTKTByocLyhd1A9j9uCUlIPD+ogum7+i1h3+CEw== dependencies: - hermes-estree "0.19.1" - hermes-parser "0.19.1" - prettier-plugin-hermes-parser "0.19.1" + hermes-estree "0.20.1" + hermes-parser "0.20.1" + prettier-plugin-hermes-parser "0.20.1" prettier@2.8.8: version "2.8.8" @@ -8120,10 +8109,10 @@ range-parser@~1.2.1: resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== -react-devtools-core@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/react-devtools-core/-/react-devtools-core-5.0.0.tgz#50b04a4dbfa62badbe4d86529e9478c396988b31" - integrity sha512-SAAMLacNDfFjMJjmbXURNWtrTyARi9xTqGkY48Btw5cIWlr1wgxfWYZKxoUZav1qqmhbpgTzSmmF+cpMHGHY3A== +react-devtools-core@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/react-devtools-core/-/react-devtools-core-5.0.2.tgz#c3c11c7b91857131d694457885ef49b7ae590857" + integrity sha512-+fDp3kDfPpF5xbAACJmihPHL0iDKpnKr7MyRvW0nZq71xwHWDW3zRCNpiiAJWd85vAGT+GbV9O87zAIDgvV1gw== dependencies: shell-quote "^1.6.1" ws "^7" @@ -8268,11 +8257,6 @@ regexp.prototype.flags@^1.4.1, regexp.prototype.flags@^1.4.3: define-properties "^1.1.3" functions-have-names "^1.2.2" -regexpp@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2" - integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== - regexpu-core@^5.2.1: version "5.2.2" resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-5.2.2.tgz#3e4e5d12103b64748711c3aad69934d7718e75fc" @@ -8709,11 +8693,6 @@ source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.1: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== -source-map@^0.7.3: - version "0.7.3" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383" - integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ== - spdx-correct@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz#dece81ac9c1e6713e5f7d1b6f17d468fa53d89a9" @@ -8919,7 +8898,7 @@ strip-json-comments@^2.0.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ== -strip-json-comments@^3.1.0, strip-json-comments@^3.1.1: +strip-json-comments@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== @@ -9491,11 +9470,6 @@ wide-align@^1.1.0: dependencies: string-width "^1.0.2 || 2 || 3 || 4" -word-wrap@^1.2.3: - version "1.2.3" - resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" - integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== - wrap-ansi@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53"