From 2edda6d967c10db6c2f7a6a7cd0f0b5717af6d0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0001/1383] Add basic Fantom tests for performance.mark and performance.measure (#52432) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52432 Changelog: [internal] This creates a battery of tests for `performance.mark` and `performance.measure`. For this, it was necessary to add a new method in the native module to mock the current time. Many of the tests are currently failing, as the API doesn't support all the options or behaviors defined in the spec. They're skipped here and will be re-enabled and fixed in a following diff. Reviewed By: huntie Differential Revision: D77795989 fbshipit-source-id: 3ebf18c8ac336df1fb43003a55a4678b52e8982d --- .../webperformance/NativePerformance.cpp | 16 +- .../webperformance/NativePerformance.h | 7 + .../__tests__/Performance-itest.js | 434 +++++++++++++++++- .../performance/specs/NativePerformance.js | 2 + 4 files changed, 434 insertions(+), 25 deletions(-) diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp index 7fa624f29246ee..82250fb424695e 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp @@ -117,15 +117,15 @@ NativePerformance::NativePerformance(std::shared_ptr jsInvoker) : NativePerformanceCxxSpec(std::move(jsInvoker)) {} HighResTimeStamp NativePerformance::now(jsi::Runtime& /*rt*/) { - return HighResTimeStamp::now(); + return forcedCurrentTimeStamp_.value_or(HighResTimeStamp::now()); } HighResTimeStamp NativePerformance::markWithResult( jsi::Runtime& rt, std::string name, std::optional startTime) { - auto entry = - PerformanceEntryReporter::getInstance()->reportMark(name, startTime); + auto entry = PerformanceEntryReporter::getInstance()->reportMark( + name, startTime.value_or(now(rt))); return entry.startTime; } @@ -167,7 +167,7 @@ NativePerformance::measureWithResult( } else if (endTimeValue < startTimeValue) { // The end time is not specified, take the current time, according to the // standard - endTimeValue = reporter->getCurrentTimeStamp(); + endTimeValue = now(runtime); } auto entry = reporter->reportMeasure(name, startTime, endTime); @@ -406,4 +406,12 @@ NativePerformance::getSupportedPerformanceEntryTypes(jsi::Runtime& /*rt*/) { return {supportedEntryTypes.begin(), supportedEntryTypes.end()}; } +#pragma mark - Testing + +void NativePerformance::setCurrentTimeStampForTesting( + jsi::Runtime& /*rt*/, + HighResTimeStamp ts) { + forcedCurrentTimeStamp_ = ts; +} + } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index d2602b0b78bd63..94888ab3cd42f8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -184,6 +184,13 @@ class NativePerformance : public NativePerformanceCxxSpec { // tracking. std::unordered_map getReactNativeStartupTiming( jsi::Runtime& rt); + +#pragma mark - Testing + + void setCurrentTimeStampForTesting(jsi::Runtime& rt, HighResTimeStamp ts); + + private: + std::optional forcedCurrentTimeStamp_; }; } // namespace facebook::react diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js index dc79c14e794d56..95855a3e4670b9 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js @@ -8,32 +8,424 @@ * @format */ +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + import type Performance from '../Performance'; -import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; +import ensureInstance from '../../../__tests__/utilities/ensureInstance'; +import DOMException from '../../errors/DOMException'; +import NativePerformance from '../specs/NativePerformance'; +import {PerformanceMark, PerformanceMeasure} from '../UserTiming'; + +/* eslint-disable jest/no-disabled-tests */ declare var performance: Performance; +function getThrownError(fn: () => mixed): mixed { + try { + fn(); + } catch (e) { + return e; + } + throw new Error('Expected function to throw'); +} + describe('Performance', () => { - it('measure validates mark names presence in the buffer, if specified', () => { - expect(() => { - performance.measure('measure', 'start', 'end'); - }).toThrow( - "Failed to execute 'measure' on 'Performance': The mark 'start' does not exist.", - ); // This should also check that Error is an instance of DOMException and is SyntaxError, - // but toThrow checked currently only supports string argument. - - performance.mark('start'); - expect(() => { - performance.measure('measure', 'start', 'end'); - }).toThrow( - "Failed to execute 'measure' on 'Performance': The mark 'end' does not exist.", - ); // This should also check that Error is an instance of DOMException and is SyntaxError, - // but toThrow checked currently only supports string argument. - - performance.mark('end'); - expect(() => { - performance.measure('measure', 'start', 'end'); - }).not.toThrow(); + beforeEach(() => { + performance.clearMarks(); + performance.clearMeasures(); + }); + + describe('mark', () => { + it('works with default timestamp', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + const mark = performance.mark('mark-now'); + + expect(mark).toBeInstanceOf(PerformanceMark); + expect(mark.entryType).toBe('mark'); + expect(mark.name).toBe('mark-now'); + expect(mark.startTime).toBe(25); + expect(mark.duration).toBe(0); + expect(mark.detail).toBeUndefined(); + }); + + it('works with custom timestamp', () => { + const mark = performance.mark('mark-custom', {startTime: 10}); + + expect(mark).toBeInstanceOf(PerformanceMark); + expect(mark.entryType).toBe('mark'); + expect(mark.name).toBe('mark-custom'); + expect(mark.startTime).toBe(10); + expect(mark.duration).toBe(0); + expect(mark.detail).toBeUndefined(); + }); + + it('provides detail', () => { + const originalDetail = {foo: 'bar'}; + + const mark = performance.mark('some-mark', { + detail: originalDetail, + }); + + expect(mark.detail).toEqual(originalDetail); + // TODO structuredClone + // expect(mark.detail).not.toBe(originalDetail); + }); + + it.skip('throws if no name is provided', () => { + expect(() => { + // $FlowExpectedError[incompatible-call] + performance.mark(); + }).toThrow( + `Failed to execute 'mark' on 'Performance': 1 argument required, but only 0 present.`, + ); + }); + + it.skip('casts startTime to a number', () => { + const mark = performance.mark('some-mark', { + // $FlowExpectedError[incompatible-call] + startTime: '10', + }); + + expect(mark.startTime).toBe(10); + + const mark2 = performance.mark('some-mark', { + // $FlowExpectedError[incompatible-call] + startTime: null, + }); + + expect(mark2.startTime).toBe(0); + }); + + it.skip('throws if startTime cannot be converted to a finite number', () => { + expect(() => { + performance.mark('some-mark', {startTime: NaN}); + }).toThrow( + `Failed to execute 'mark' on 'Performance': Failed to read the 'startTime' property from 'PerformanceMarkOptions': The provided double value is non-finite.`, + ); + + expect(() => { + // $FlowExpectedError[incompatible-call] + performance.mark('some-mark', {startTime: {}}); + }).toThrow( + `Failed to execute 'mark' on 'Performance': Failed to read the 'startTime' property from 'PerformanceMarkOptions': The provided double value is non-finite.`, + ); + }); + + it.skip('throws if startTime is negative', () => { + expect(() => { + performance.mark('some-mark', {startTime: -1}); + }).toThrow( + `Failed to execute 'mark' on 'Performance': 'some-mark' cannot have a negative start time.`, + ); + }); + }); + + describe('measure', () => { + describe('with measureOptions', () => { + it.skip('uses 0 as default start and now as default end', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + const measure = performance.measure('measure-with-defaults', {}); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-defaults'); + expect(measure.startTime).toBe(0); + expect(measure.duration).toBe(25); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with a start timestamp', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + const measure = performance.measure('measure-with-start-timestamp', { + start: 10, + }); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-timestamp'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(15); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with start mark', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + performance.mark('start-mark', { + startTime: 10, + }); + + // $FlowFixMe[incompatible-call] + const measure = performance.measure('measure-with-start-mark', { + start: 'start-mark', + }); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-mark'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(15); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with end mark', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + performance.mark('end-mark', { + startTime: 50, + }); + + // $FlowFixMe[incompatible-call] + const measure = performance.measure('measure-with-end-mark', { + end: 'end-mark', + }); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-end-mark'); + expect(measure.startTime).toBe(0); + expect(measure.duration).toBe(50); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with start mark and end mark', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + performance.mark('start-mark', { + startTime: 10, + }); + + performance.mark('end-mark', { + startTime: 50, + }); + + const measure = performance.measure( + 'measure-with-start-mark-and-end-mark', + // $FlowFixMe[incompatible-call] + { + start: 'start-mark', + end: 'end-mark', + }, + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-mark-and-end-mark'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(40); + expect(measure.detail).toBeUndefined(); + }); + + it('works with a start timestamp and an end timestamp', () => { + const measure = performance.measure( + 'measure-with-start-timestamp-and-end-timestamp', + { + start: 10, + end: 25, + }, + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe( + 'measure-with-start-timestamp-and-end-timestamp', + ); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(15); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with a start timestamp and a duration', () => { + const measure = performance.measure( + 'measure-with-start-timestamp-and-duration', + { + start: 10, + duration: 30, + }, + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-timestamp-and-duration'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(30); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with a start mark and a duration', () => { + performance.mark('start-mark', { + startTime: 10, + }); + + const measure = performance.measure( + 'measure-with-start-mark-and-duration', + // $FlowFixMe[incompatible-call] + { + start: 'start-mark', + duration: 30, + }, + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-mark-and-duration'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(30); + expect(measure.detail).toBeUndefined(); + }); + + it('throws if the specified mark does NOT exist', () => { + const missingStartMarkError = ensureInstance( + getThrownError(() => { + // $FlowFixMe[incompatible-call] + performance.measure('measure', { + start: 'start', + end: 'end', + }); + }), + DOMException, + ); + + expect(missingStartMarkError.name).toBe('SyntaxError'); + expect(missingStartMarkError.message).toBe( + "Failed to execute 'measure' on 'Performance': The mark 'start' does not exist.", + ); + + performance.mark('start'); + + const missingEndMarkError = ensureInstance( + getThrownError(() => { + // $FlowFixMe[incompatible-call] + performance.measure('measure', { + start: 'start', + end: 'end', + }); + }), + DOMException, + ); + + expect(missingEndMarkError.message).toBe( + "Failed to execute 'measure' on 'Performance': The mark 'end' does not exist.", + ); + + performance.mark('end'); + expect(() => { + // $FlowFixMe[incompatible-call] + performance.measure('measure', { + start: 'start', + end: 'end', + }); + }).not.toThrow(); + }); + }); + + describe('with startMark / endMark', () => { + it.skip('uses 0 as default start and now as default end', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + const measure = performance.measure('measure-with-defaults', undefined); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-defaults'); + expect(measure.startTime).toBe(0); + expect(measure.duration).toBe(25); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with startMark', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + performance.mark('start-mark', { + startTime: 10, + }); + + const measure = performance.measure( + 'measure-with-start-mark', + 'start-mark', + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-mark'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(15); + expect(measure.detail).toBeUndefined(); + }); + + it.skip('works with startMark and endMark', () => { + NativePerformance?.setCurrentTimeStampForTesting?.(25); + + performance.mark('start-mark', { + startTime: 10, + }); + + performance.mark('end-mark', { + startTime: 25, + }); + + const measure = performance.measure( + 'measure-with-start-mark-and-end-mark', + 'start-mark', + ); + + expect(measure).toBeInstanceOf(PerformanceMeasure); + expect(measure.entryType).toBe('measure'); + expect(measure.name).toBe('measure-with-start-mark-and-end-mark'); + expect(measure.startTime).toBe(10); + expect(measure.duration).toBe(15); + expect(measure.detail).toBeUndefined(); + }); + + it('throws if the specified marks do NOT exist', () => { + const missingStartMarkError = ensureInstance( + getThrownError(() => { + performance.measure('measure', 'start', 'end'); + }), + DOMException, + ); + + expect(missingStartMarkError.name).toBe('SyntaxError'); + expect(missingStartMarkError.message).toBe( + "Failed to execute 'measure' on 'Performance': The mark 'start' does not exist.", + ); + + performance.mark('start'); + + const missingEndMarkError = ensureInstance( + getThrownError(() => { + performance.measure('measure', 'start', 'end'); + }), + DOMException, + ); + + expect(missingEndMarkError.message).toBe( + "Failed to execute 'measure' on 'Performance': The mark 'end' does not exist.", + ); + + performance.mark('end'); + expect(() => { + performance.measure('measure', 'start', 'end'); + }).not.toThrow(); + }); + }); + + it('provides detail', () => { + const originalDetail = {foo: 'bar'}; + + const measure = performance.measure('measure-with-detail', { + start: 10, + end: 20, + detail: originalDetail, + }); + + expect(measure.detail).toEqual(originalDetail); + // TODO structuredClone + // expect(measure.detail).not.toBe(originalDetail); + }); }); }); diff --git a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js index 18714050b15d82..38ee53b59e7947 100644 --- a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js @@ -96,6 +96,8 @@ export interface Spec extends TurboModule { ) => $ReadOnlyArray; +getSupportedPerformanceEntryTypes?: () => $ReadOnlyArray; + + +setCurrentTimeStampForTesting?: (timeStamp: number) => void; } export default (TurboModuleRegistry.get('NativePerformanceCxx'): ?Spec); From 34201d8387a6f126dd14aa849e988de6d044b2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0002/1383] Fix Flow types for performance.measure (#52431) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52431 Changelog: [internal] `performance.measure` supports passing mark names as `start` and `end` options, so this fixes the Flow type before fixing the actual implementation. It also makes it so you can't specify both `end` and `duration`, enforced by the type system. Reviewed By: huntie Differential Revision: D77795991 fbshipit-source-id: e89f509c7efc2fa49d17d79bc19bc1d14e007871 --- .../private/webapis/performance/Performance.js | 17 +++++++++++------ .../performance/__tests__/Performance-itest.js | 7 ------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index bb14a9ef2af272..337d609f948037 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -38,12 +38,17 @@ declare var global: { const getCurrentTimeStamp: () => DOMHighResTimeStamp = NativePerformance?.now ?? global.nativePerformanceNow ?? (() => Date.now()); -export type PerformanceMeasureOptions = { - detail?: DetailType, - start?: DOMHighResTimeStamp, - duration?: DOMHighResTimeStamp, - end?: DOMHighResTimeStamp, -}; +export type PerformanceMeasureOptions = + | { + detail?: DetailType, + start?: DOMHighResTimeStamp | string, + duration?: DOMHighResTimeStamp, + } + | { + detail?: DetailType, + start?: DOMHighResTimeStamp | string, + end?: DOMHighResTimeStamp | string, + }; const ENTRY_TYPES_AVAILABLE_FROM_TIMELINE: $ReadOnlyArray = ['mark', 'measure']; diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js index 95855a3e4670b9..18f6f3ecf54eab 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js @@ -159,7 +159,6 @@ describe('Performance', () => { startTime: 10, }); - // $FlowFixMe[incompatible-call] const measure = performance.measure('measure-with-start-mark', { start: 'start-mark', }); @@ -179,7 +178,6 @@ describe('Performance', () => { startTime: 50, }); - // $FlowFixMe[incompatible-call] const measure = performance.measure('measure-with-end-mark', { end: 'end-mark', }); @@ -205,7 +203,6 @@ describe('Performance', () => { const measure = performance.measure( 'measure-with-start-mark-and-end-mark', - // $FlowFixMe[incompatible-call] { start: 'start-mark', end: 'end-mark', @@ -263,7 +260,6 @@ describe('Performance', () => { const measure = performance.measure( 'measure-with-start-mark-and-duration', - // $FlowFixMe[incompatible-call] { start: 'start-mark', duration: 30, @@ -281,7 +277,6 @@ describe('Performance', () => { it('throws if the specified mark does NOT exist', () => { const missingStartMarkError = ensureInstance( getThrownError(() => { - // $FlowFixMe[incompatible-call] performance.measure('measure', { start: 'start', end: 'end', @@ -299,7 +294,6 @@ describe('Performance', () => { const missingEndMarkError = ensureInstance( getThrownError(() => { - // $FlowFixMe[incompatible-call] performance.measure('measure', { start: 'start', end: 'end', @@ -314,7 +308,6 @@ describe('Performance', () => { performance.mark('end'); expect(() => { - // $FlowFixMe[incompatible-call] performance.measure('measure', { start: 'start', end: 'end', From 74c03b67e397f75d3bff32162756de5c90a50d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0003/1383] Fix bugs in performance.mark and performance.measure (#52430) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52430 Changelog: [internal] (This is marked as internal because this API hasn't been marked as stable yet). This fixes multiple bugs and missing features in `performance.mark` and `performance.measure`. See re-enabled tests to see the specific behaviors. Validated that performance isn't regressed by this change using the existing benchmark for `Performance` (`Performance-benchmark-itest`): * Before | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '5557.96 ± 0.34%' | '5459.00' | '182114 ± 0.02%' | '183184' | 179922 | | 1 | 'mark (with custom startTime)' | '5664.54 ± 1.71%' | '5518.00' | '180296 ± 0.02%' | '181225' | 176537 | | 2 | 'measure (with start and end timestamps)' | '6653.62 ± 0.94%' | '6530.00' | '152296 ± 0.02%' | '153139' | 150295 | | 3 | 'measure (with mark names)' | '6903.37 ± 0.42%' | '6790.00' | '146429 ± 0.02%' | '147275' | 144857 | | 4 | 'clearMarks' | '782.98 ± 0.04%' | '771.00' | '1287735 ± 0.01%' | '1297017' | 1277173 | | 5 | 'clearMeasures' | '792.24 ± 0.03%' | '781.00' | '1270847 ± 0.01%' | '1280410' | 1262238 | | 6 | 'mark + clearMarks' | '5883.69 ± 0.52%' | '5759.00' | '172863 ± 0.02%' | '173641' | 169962 | | 7 | 'measure + clearMeasures (with start and end timestamps)' | '7222.22 ± 0.68%' | '7021.00' | '141204 ± 0.02%' | '142430' | 138462 | | 8 | 'measure + clearMeasures (with mark names)' | '7234.53 ± 0.34%' | '7121.00' | '139600 ± 0.02%' | '140430' | 138227 | * After | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '5579.80 ± 0.32%' | '5479.00' | '181368 ± 0.02%' | '182515' | 179218 | | 1 | 'mark (with custom startTime)' | '5759.72 ± 0.99%' | '5648.00' | '176162 ± 0.02%' | '177054' | 173620 | | 2 | 'measure (with start and end timestamps)' | '6506.38 ± 0.34%' | '6390.00' | '155503 ± 0.02%' | '156495' | 153696 | | 3 | 'measure (with mark names)' | '6770.94 ± 0.72%' | '6620.00' | '149833 ± 0.03%' | '151057' | 147691 | | 4 | 'clearMarks' | '785.89 ± 0.07%' | '771.00' | '1291356 ± 0.01%' | '1297017' | 1272442 | | 5 | 'clearMeasures' | '777.98 ± 0.06%' | '761.00' | '1303362 ± 0.01%' | '1314060' | 1285383 | | 6 | 'mark + clearMarks' | '5995.34 ± 1.37%' | '5779.00' | '171874 ± 0.03%' | '173040' | 166797 | | 7 | 'measure + clearMeasures (with start and end timestamps)' | '7040.28 ± 0.57%' | '6830.00' | '145289 ± 0.03%' | '146413' | 142040 | | 8 | 'measure + clearMeasures (with mark names)' | '7184.43 ± 0.40%' | '6990.00' | '141809 ± 0.03%' | '143062' | 139190 | Reviewed By: huntie Differential Revision: D77795990 fbshipit-source-id: 97895065ca63f87f1f66710cf7bce97e1255a142 --- .../webperformance/NativePerformance.cpp | 50 +++++ .../webperformance/NativePerformance.h | 11 + .../webapis/performance/Performance.js | 197 +++++++++++++----- .../__tests__/Performance-itest.js | 32 ++- .../performance/__tests__/Performance-test.js | 2 +- .../performance/specs/NativePerformance.js | 9 + .../specs/__mocks__/NativePerformanceMock.js | 11 +- 7 files changed, 235 insertions(+), 77 deletions(-) diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp index 82250fb424695e..7c8be7f36d2625 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp @@ -129,6 +129,56 @@ HighResTimeStamp NativePerformance::markWithResult( return entry.startTime; } +std::tuple NativePerformance::measure( + jsi::Runtime& runtime, + std::string name, + std::optional startTime, + std::optional endTime, + std::optional duration, + std::optional startMark, + std::optional endMark) { + auto reporter = PerformanceEntryReporter::getInstance(); + + HighResTimeStamp startTimeValue; + + // If the start time mark name is specified, it takes precedence over the + // startTime parameter, which can be set to 0 by default from JavaScript. + if (startTime) { + startTimeValue = *startTime; + } else if (startMark) { + if (auto startMarkBufferedTime = reporter->getMarkTime(*startMark)) { + startTimeValue = *startMarkBufferedTime; + } else { + throw jsi::JSError( + runtime, "The mark '" + *startMark + "' does not exist."); + } + } else { + startTimeValue = HighResTimeStamp::fromDOMHighResTimeStamp(0); + } + + HighResTimeStamp endTimeValue; + + if (endTime) { + endTimeValue = *endTime; + } else if (duration) { + endTimeValue = startTimeValue + *duration; + } else if (endMark) { + if (auto endMarkBufferedTime = reporter->getMarkTime(*endMark)) { + endTimeValue = *endMarkBufferedTime; + } else { + throw jsi::JSError( + runtime, "The mark '" + *endMark + "' does not exist."); + } + } else { + // The end time is not specified, take the current time, according to the + // standard + endTimeValue = now(runtime); + } + + auto entry = reporter->reportMeasure(name, startTimeValue, endTimeValue); + return std::tuple{entry.startTime, entry.duration}; +} + std::tuple NativePerformance::measureWithResult( jsi::Runtime& runtime, diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index 94888ab3cd42f8..d713171e14c63b 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -97,6 +97,17 @@ class NativePerformance : public NativePerformanceCxxSpec { std::optional startTime); // https://w3c.github.io/user-timing/#measure-method + std::tuple measure( + jsi::Runtime& rt, + std::string name, + std::optional startTime, + std::optional endTime, + std::optional duration, + std::optional startMark, + std::optional endMark); + + // https://w3c.github.io/user-timing/#measure-method + [[deprecated("This method is deprecated. Use the measure method instead.")]] std::tuple measureWithResult( jsi::Runtime& rt, std::string name, diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index 337d609f948037..639b8de9773883 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -116,11 +116,34 @@ export default class Performance { markName: string, markOptions?: PerformanceMarkOptions, ): PerformanceMark { + if (markName == null) { + throw new TypeError( + `Failed to execute 'mark' on 'Performance': 1 argument required, but only 0 present.`, + ); + } + let computedStartTime; if (NativePerformance?.markWithResult) { + let resolvedStartTime; + + const startTime = markOptions?.startTime; + if (startTime !== undefined) { + resolvedStartTime = Number(startTime); + if (resolvedStartTime < 0) { + throw new TypeError( + `Failed to execute 'mark' on 'Performance': '${markName}' cannot have a negative start time.`, + ); + } else if (!Number.isFinite(resolvedStartTime)) { + throw new TypeError( + `Failed to execute 'mark' on 'Performance': Failed to read the 'startTime' property from 'PerformanceMarkOptions': The provided double value is non-finite.`, + ); + } + } + + // $FlowExpectedError[not-a-function] computedStartTime = NativePerformance.markWithResult( markName, - markOptions?.startTime, + resolvedStartTime, ); } else { warnNoNativePerformance(); @@ -147,66 +170,132 @@ export default class Performance { startMarkOrOptions?: string | PerformanceMeasureOptions, endMark?: string, ): PerformanceMeasure { - let options; - let startMarkName, - endMarkName = endMark, - duration, - startTime = 0, - endTime = 0; - - if (typeof startMarkOrOptions === 'string') { - startMarkName = startMarkOrOptions; - options = {}; - } else if (startMarkOrOptions !== undefined) { - options = startMarkOrOptions; - if (endMark !== undefined) { - throw new TypeError( - "Performance.measure: Can't have both options and endMark", - ); - } - if (options.start === undefined && options.end === undefined) { - throw new TypeError( - 'Performance.measure: Must have at least one of start/end specified in options', - ); + let resolvedStartTime: number | void; + let resolvedStartMark: string | void; + let resolvedEndTime: number | void; + let resolvedEndMark: string | void; + let resolvedDuration: number | void; + let resolvedDetail: mixed; + + if (startMarkOrOptions != null) { + switch (typeof startMarkOrOptions) { + case 'object': { + if (endMark != null) { + throw new TypeError( + `Failed to execute 'measure' on 'Performance': If a non-empty PerformanceMeasureOptions object was passed, |end_mark| must not be passed.`, + ); + } + + const start = startMarkOrOptions.start; + switch (typeof start) { + case 'number': { + resolvedStartTime = start; + break; + } + case 'string': { + resolvedStartMark = start; + break; + } + case 'undefined': { + break; + } + default: { + resolvedStartMark = String(start); + } + } + + const end = startMarkOrOptions.end; + switch (typeof end) { + case 'number': { + resolvedEndTime = end; + break; + } + case 'string': { + resolvedEndMark = end; + break; + } + case 'undefined': { + break; + } + default: { + resolvedEndMark = String(end); + } + } + + const duration = startMarkOrOptions.duration; + switch (typeof duration) { + case 'number': { + resolvedDuration = duration; + break; + } + case 'undefined': + break; + default: { + resolvedDuration = Number(duration); + if (!Number.isFinite(resolvedDuration)) { + throw new TypeError( + `Failed to execute 'measure' on 'Performance': Failed to read the 'duration' property from 'PerformanceMeasureOptions': The provided double value is non-finite.`, + ); + } + } + } + + if ( + resolvedDuration != null && + (resolvedEndMark != null || resolvedEndTime != null) + ) { + throw new TypeError( + `Failed to execute 'measure' on 'Performance': If a non-empty PerformanceMeasureOptions object was passed, it must not have all of its 'start', 'duration', and 'end' properties defined`, + ); + } + + resolvedDetail = startMarkOrOptions.detail; + + break; + } + case 'string': { + resolvedStartMark = startMarkOrOptions; + + if (endMark !== undefined) { + resolvedEndMark = String(endMark); + } + break; + } + default: { + resolvedStartMark = String(startMarkOrOptions); + } } - if ( - options.start !== undefined && - options.end !== undefined && - options.duration !== undefined - ) { - throw new TypeError( - "Performance.measure: Can't have both start/end and duration explicitly in options", - ); - } - - if (typeof options.start === 'number') { - startTime = options.start; - } else { - startMarkName = options.start; - } - - if (typeof options.end === 'number') { - endTime = options.end; - } else { - endMarkName = options.end; - } - - duration = options.duration ?? duration; } - let computedStartTime = startTime; - let computedDuration = duration; + let computedStartTime = 0; + let computedDuration = 0; - if (NativePerformance?.measureWithResult) { + if (NativePerformance?.measure) { + try { + [computedStartTime, computedDuration] = NativePerformance.measure( + measureName, + resolvedStartTime, + resolvedEndTime, + resolvedDuration, + resolvedStartMark, + resolvedEndMark, + ); + } catch (error) { + throw new DOMException( + "Failed to execute 'measure' on 'Performance': " + error.message, + 'SyntaxError', + ); + } + } else if (NativePerformance?.measureWithResult) { try { [computedStartTime, computedDuration] = NativePerformance.measureWithResult( measureName, - startTime, - endTime, - duration, - startMarkName, - endMarkName, + resolvedStartTime ?? 0, + resolvedEndTime ?? 0, + resolvedDuration, + resolvedStartMark, + resolvedEndMark, ); } catch (error) { throw new DOMException( @@ -221,7 +310,7 @@ export default class Performance { const measure = new PerformanceMeasure(measureName, { startTime: computedStartTime, duration: computedDuration ?? 0, - detail: options?.detail, + detail: resolvedDetail, }); return measure; diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js index 18f6f3ecf54eab..051f9eb4dc9351 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js @@ -17,8 +17,6 @@ import DOMException from '../../errors/DOMException'; import NativePerformance from '../specs/NativePerformance'; import {PerformanceMark, PerformanceMeasure} from '../UserTiming'; -/* eslint-disable jest/no-disabled-tests */ - declare var performance: Performance; function getThrownError(fn: () => mixed): mixed { @@ -73,7 +71,7 @@ describe('Performance', () => { // expect(mark.detail).not.toBe(originalDetail); }); - it.skip('throws if no name is provided', () => { + it('throws if no name is provided', () => { expect(() => { // $FlowExpectedError[incompatible-call] performance.mark(); @@ -82,7 +80,7 @@ describe('Performance', () => { ); }); - it.skip('casts startTime to a number', () => { + it('casts startTime to a number', () => { const mark = performance.mark('some-mark', { // $FlowExpectedError[incompatible-call] startTime: '10', @@ -98,7 +96,7 @@ describe('Performance', () => { expect(mark2.startTime).toBe(0); }); - it.skip('throws if startTime cannot be converted to a finite number', () => { + it('throws if startTime cannot be converted to a finite number', () => { expect(() => { performance.mark('some-mark', {startTime: NaN}); }).toThrow( @@ -113,7 +111,7 @@ describe('Performance', () => { ); }); - it.skip('throws if startTime is negative', () => { + it('throws if startTime is negative', () => { expect(() => { performance.mark('some-mark', {startTime: -1}); }).toThrow( @@ -124,7 +122,7 @@ describe('Performance', () => { describe('measure', () => { describe('with measureOptions', () => { - it.skip('uses 0 as default start and now as default end', () => { + it('uses 0 as default start and now as default end', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); const measure = performance.measure('measure-with-defaults', {}); @@ -137,7 +135,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with a start timestamp', () => { + it('works with a start timestamp', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); const measure = performance.measure('measure-with-start-timestamp', { @@ -152,7 +150,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with start mark', () => { + it('works with start mark', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { @@ -171,7 +169,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with end mark', () => { + it('works with end mark', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); performance.mark('end-mark', { @@ -190,7 +188,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with start mark and end mark', () => { + it('works with start mark and end mark', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { @@ -236,7 +234,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with a start timestamp and a duration', () => { + it('works with a start timestamp and a duration', () => { const measure = performance.measure( 'measure-with-start-timestamp-and-duration', { @@ -253,7 +251,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with a start mark and a duration', () => { + it('works with a start mark and a duration', () => { performance.mark('start-mark', { startTime: 10, }); @@ -317,10 +315,10 @@ describe('Performance', () => { }); describe('with startMark / endMark', () => { - it.skip('uses 0 as default start and now as default end', () => { + it('uses 0 as default start and now as default end', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); - const measure = performance.measure('measure-with-defaults', undefined); + const measure = performance.measure('measure-with-defaults'); expect(measure).toBeInstanceOf(PerformanceMeasure); expect(measure.entryType).toBe('measure'); @@ -330,7 +328,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with startMark', () => { + it('works with startMark', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { @@ -350,7 +348,7 @@ describe('Performance', () => { expect(measure.detail).toBeUndefined(); }); - it.skip('works with startMark and endMark', () => { + it('works with startMark and endMark', () => { NativePerformance?.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { 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 292ee6674cec07..2b7a3108952e13 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 @@ -63,7 +63,7 @@ describe('Performance', () => { startTime: 10, }, { - duration: -10, + duration: 15, entryType: 'measure', name: 'measure-now-with-start-mark', startTime: 10, diff --git a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js index 38ee53b59e7947..6ce038f9395a89 100644 --- a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js @@ -58,6 +58,15 @@ export interface Spec extends TurboModule { name: string, startTime?: number, ) => NativePerformanceMarkResult; + +measure?: ( + name: string, + startTime?: number, + endTime?: number, + duration?: number, + startMark?: string, + endMark?: string, + ) => NativePerformanceMeasureResult; + // DEPRECATED: Use measure instead. +measureWithResult?: ( name: string, startTime: number, diff --git a/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js index edab30a38d4853..518ca5e61e9978 100644 --- a/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js +++ b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js @@ -127,16 +127,17 @@ const NativePerformanceMock = { return computedStartTime; }, - measureWithResult: ( + measure: ( name: string, - startTime: number, - endTime: number, + startTime?: number, + endTime?: number, duration?: number, startMark?: string, endMark?: string, ): NativePerformanceMeasureResult => { - const start = startMark != null ? marks.get(startMark) : startTime; - const end = endMark != null ? marks.get(endMark) : endTime; + const start = startMark != null ? marks.get(startMark) : startTime ?? 0; + const end = + endMark != null ? marks.get(endMark) : endTime ?? performance.now(); if (start === undefined) { throw new Error('startMark does not exist'); From 9005d93e3225fc0dbaaae93a299d0edf6c628d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0004/1383] Optimize performance.mark and performance.measure (#52429) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52429 Changelog: [internal] This implements a significant optimization for `performance.mark` and `performance.measure`. After these changes, they take 1/3 of the time they took before. We've seen these methods show up too often in traces (in the Hermes sampling profiler) so this should significantly reduce their overhead. I found out that most of the time spent in `performance.mark` and `performance.measure` was creating the `PerformanceMark` and `PerformanceMeasure` instances returned by those methods. I applied the same playbook I did for `ReactNativeElement` (avoiding private fields and `super()` calls, which yielded these wins. * Before | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '5579.80 ± 0.32%' | '5479.00' | '181368 ± 0.02%' | '182515' | 179218 | | 1 | 'mark (with custom startTime)' | '5759.72 ± 0.99%' | '5648.00' | '176162 ± 0.02%' | '177054' | 173620 | | 2 | 'measure (with start and end timestamps)' | '6506.38 ± 0.34%' | '6390.00' | '155503 ± 0.02%' | '156495' | 153696 | | 3 | 'measure (with mark names)' | '6770.94 ± 0.72%' | '6620.00' | '149833 ± 0.03%' | '151057' | 147691 | | 4 | 'clearMarks' | '785.89 ± 0.07%' | '771.00' | '1291356 ± 0.01%' | '1297017' | 1272442 | | 5 | 'clearMeasures' | '777.98 ± 0.06%' | '761.00' | '1303362 ± 0.01%' | '1314060' | 1285383 | | 6 | 'mark + clearMarks' | '5995.34 ± 1.37%' | '5779.00' | '171874 ± 0.03%' | '173040' | 166797 | | 7 | 'measure + clearMeasures (with start and end timestamps)' | '7040.28 ± 0.57%' | '6830.00' | '145289 ± 0.03%' | '146413' | 142040 | | 8 | 'measure + clearMeasures (with mark names)' | '7184.43 ± 0.40%' | '6990.00' | '141809 ± 0.03%' | '143062' | 139190 | * After | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '1678.19 ± 0.73%' | '1633.00' | '607139 ± 0.01%' | '612370' | 595882 | | 1 | 'mark (with custom startTime)' | '1920.23 ± 1.30%' | '1843.00' | '538217 ± 0.01%' | '542594' | 520772 | | 2 | 'measure (with start and end timestamps)' | '2651.72 ± 0.94%' | '2554.00' | '388312 ± 0.02%' | '391543' | 377114 | | 3 | 'measure (with mark names)' | '2815.84 ± 0.75%' | '2744.00' | '362303 ± 0.02%' | '364431' | 355134 | | 4 | 'clearMarks' | '743.82 ± 0.06%' | '731.00' | '1363190 ± 0.01%' | '1367989' | 1344417 | | 5 | 'clearMeasures' | '776.69 ± 0.07%' | '761.00' | '1306563 ± 0.01%' | '1314060' | 1287512 | | 6 | 'mark + clearMarks' | '2043.97 ± 1.26%' | '1973.00' | '504750 ± 0.01%' | '506842' | 489801 | | 7 | 'measure + clearMeasures (with start and end timestamps)' | '3048.39 ± 0.87%' | '2965.00' | '335285 ± 0.02%' | '337268' | 328042 | | 8 | 'measure + clearMeasures (with mark names)' | '3132.75 ± 0.80%' | '3065.00' | '324365 ± 0.02%' | '326264' | 319209 | Reviewed By: huntie Differential Revision: D77790874 fbshipit-source-id: baf7aca07d281fef4373956d125c63f006fab592 --- .../webapis/performance/PerformanceEntry.js | 36 +++++----- .../private/webapis/performance/UserTiming.js | 68 ++++++++++++++++--- 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/packages/react-native/src/private/webapis/performance/PerformanceEntry.js b/packages/react-native/src/private/webapis/performance/PerformanceEntry.js index 76daf969c03c8f..f2ddfceda554ca 100644 --- a/packages/react-native/src/private/webapis/performance/PerformanceEntry.js +++ b/packages/react-native/src/private/webapis/performance/PerformanceEntry.js @@ -29,10 +29,14 @@ export type PerformanceEntryJSON = { }; export class PerformanceEntry { - #name: string; - #entryType: PerformanceEntryType; - #startTime: DOMHighResTimeStamp; - #duration: DOMHighResTimeStamp; + // We don't use private fields because they're significantly slower to + // initialize on construction and to access. + // We also need these to be protected so they can be initialized in subclasses + // where we avoid calling `super()` for performance reasons. + __name: string; + __entryType: PerformanceEntryType; + __startTime: DOMHighResTimeStamp; + __duration: DOMHighResTimeStamp; constructor(init: { name: string, @@ -40,34 +44,34 @@ export class PerformanceEntry { startTime: DOMHighResTimeStamp, duration: DOMHighResTimeStamp, }) { - this.#name = init.name; - this.#entryType = init.entryType; - this.#startTime = init.startTime; - this.#duration = init.duration; + this.__name = init.name; + this.__entryType = init.entryType; + this.__startTime = init.startTime; + this.__duration = init.duration; } get name(): string { - return this.#name; + return this.__name; } get entryType(): PerformanceEntryType { - return this.#entryType; + return this.__entryType; } get startTime(): DOMHighResTimeStamp { - return this.#startTime; + return this.__startTime; } get duration(): DOMHighResTimeStamp { - return this.#duration; + return this.__duration; } toJSON(): PerformanceEntryJSON { return { - name: this.#name, - entryType: this.#entryType, - startTime: this.#startTime, - duration: this.#duration, + name: this.__name, + entryType: this.__entryType, + startTime: this.__startTime, + duration: this.__duration, }; } } diff --git a/packages/react-native/src/private/webapis/performance/UserTiming.js b/packages/react-native/src/private/webapis/performance/UserTiming.js index 6809f3ca5ca01c..09aaa140d38023 100644 --- a/packages/react-native/src/private/webapis/performance/UserTiming.js +++ b/packages/react-native/src/private/webapis/performance/UserTiming.js @@ -29,9 +29,12 @@ export type PerformanceMeasureInit = { duration: DOMHighResTimeStamp, }; -export class PerformanceMark extends PerformanceEntry { - #detail: DetailType; +class PerformanceMarkTemplate extends PerformanceEntry { + // We don't use private fields because they're significantly slower to + // initialize on construction and to access. + _detail: DetailType; + // This constructor isn't really used. See `PerformanceMark` below. constructor(markName: string, markOptions?: PerformanceMarkOptions) { super({ name: markName, @@ -41,18 +44,46 @@ export class PerformanceMark extends PerformanceEntry { }); if (markOptions) { - this.#detail = markOptions.detail; + this._detail = markOptions.detail; } } get detail(): DetailType { - return this.#detail; + return this._detail; } } -export class PerformanceMeasure extends PerformanceEntry { - #detail: DetailType; +// This is the real value we're exporting where we define the class a function +// so we don't need to call `super()` and we can avoid the performance penalty +// of the current code transpiled with Babel. +// We should remove this when we have built-in support for classes in the +// runtime. +export const PerformanceMark: typeof PerformanceMarkTemplate = + // $FlowExpectedError[incompatible-type] + function PerformanceMark( + this: PerformanceMarkTemplate, + markName: string, + markOptions?: PerformanceMarkOptions, + ) { + this.__name = markName; + this.__entryType = 'mark'; + this.__startTime = markOptions?.startTime ?? performance.now(); + this.__duration = 0; + if (markOptions) { + this._detail = markOptions.detail; + } + }; + +// $FlowExpectedError[prop-missing] +PerformanceMark.prototype = PerformanceMarkTemplate.prototype; + +class PerformanceMeasureTemplate extends PerformanceEntry { + // We don't use private fields because they're significantly slower to + // initialize on construction and to access. + _detail: DetailType; + + // This constructor isn't really used. See `PerformanceMeasure` below. constructor(measureName: string, measureOptions: PerformanceMeasureInit) { super({ name: measureName, @@ -62,11 +93,32 @@ export class PerformanceMeasure extends PerformanceEntry { }); if (measureOptions) { - this.#detail = measureOptions.detail; + this._detail = measureOptions.detail; } } get detail(): DetailType { - return this.#detail; + return this._detail; } } + +// We do the same here as we do for `PerformanceMark` for performance reasons. +export const PerformanceMeasure: typeof PerformanceMeasureTemplate = + // $FlowExpectedError[incompatible-type] + function PerformanceMeasure( + this: PerformanceMeasureTemplate, + measureName: string, + measureOptions: PerformanceMeasureInit, + ) { + this.__name = measureName; + this.__entryType = 'measure'; + this.__startTime = measureOptions.startTime; + this.__duration = measureOptions.duration; + + if (measureOptions) { + this._detail = measureOptions.detail; + } + }; + +// $FlowExpectedError[prop-missing] +PerformanceMeasure.prototype = PerformanceMeasureTemplate.prototype; From feeef975549f456a9aceabf94aa707908a39e1b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0005/1383] Expand tests for the performance API (#52462) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52462 Changelog: [internal] This adds a few more tests for `performance.getEntries`, `performance.getEntriesByName` and `performance.getEntriesByType`. Reviewed By: huntie Differential Revision: D77801746 fbshipit-source-id: 42f80c4e2b787c455b149ee38d071511181532b0 --- .../__tests__/Performance-itest.js | 315 ++++++++++++++++++ 1 file changed, 315 insertions(+) diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js index 051f9eb4dc9351..6de3dae4ef5911 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js @@ -11,6 +11,10 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; import type Performance from '../Performance'; +import type { + PerformanceEntryJSON, + PerformanceEntryList, +} from '../PerformanceEntry'; import ensureInstance from '../../../__tests__/utilities/ensureInstance'; import DOMException from '../../errors/DOMException'; @@ -28,6 +32,10 @@ function getThrownError(fn: () => mixed): mixed { throw new Error('Expected function to throw'); } +function toJSON(entries: PerformanceEntryList): Array { + return entries.map(entry => entry.toJSON()); +} + describe('Performance', () => { beforeEach(() => { performance.clearMarks(); @@ -419,4 +427,311 @@ describe('Performance', () => { // expect(measure.detail).not.toBe(originalDetail); }); }); + + describe('getting and clearing marks and measures', () => { + it('provides access to all buffered entries ordered by startTime', () => { + performance.mark('baz', {startTime: 20}); + performance.mark('bar', {startTime: 30}); + performance.mark('foo', {startTime: 10}); + + performance.mark('foo', {startTime: 50}); // again + + performance.measure('bar', {start: 20, duration: 40}); + performance.measure('foo', {start: 10, duration: 40}); + + const expectedInitialEntries = [ + { + duration: 0, + entryType: 'mark', + name: 'foo', + startTime: 10, + }, + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + { + duration: 0, + entryType: 'mark', + name: 'baz', + startTime: 20, + }, + { + duration: 40, + entryType: 'measure', + name: 'bar', + startTime: 20, + }, + { + duration: 0, + entryType: 'mark', + name: 'bar', + startTime: 30, + }, + { + duration: 0, + entryType: 'mark', + name: 'foo', + startTime: 50, + }, + ]; + + /* + * getEntries + */ + + expect(toJSON(performance.getEntries())).toEqual(expectedInitialEntries); + + // Returns the same list again + expect(toJSON(performance.getEntries())).toEqual(expectedInitialEntries); + + /* + * getEntriesByType + */ + + expect(toJSON(performance.getEntriesByType('mark'))).toEqual( + expectedInitialEntries.filter(entry => entry.entryType === 'mark'), + ); + + // Returns the same list again + expect(toJSON(performance.getEntriesByType('mark'))).toEqual( + expectedInitialEntries.filter(entry => entry.entryType === 'mark'), + ); + + expect(toJSON(performance.getEntriesByType('measure'))).toEqual( + expectedInitialEntries.filter(entry => entry.entryType === 'measure'), + ); + + // Returns the same list again + expect(toJSON(performance.getEntriesByType('measure'))).toEqual( + expectedInitialEntries.filter(entry => entry.entryType === 'measure'), + ); + + /* + * getEntriesByName + */ + + expect(toJSON(performance.getEntriesByName('foo'))).toEqual( + expectedInitialEntries.filter(entry => entry.name === 'foo'), + ); + + // Returns the same list again + expect(toJSON(performance.getEntriesByName('foo'))).toEqual( + expectedInitialEntries.filter(entry => entry.name === 'foo'), + ); + + expect(toJSON(performance.getEntriesByName('bar'))).toEqual( + expectedInitialEntries.filter(entry => entry.name === 'bar'), + ); + + // Returns the same list again + expect(toJSON(performance.getEntriesByName('bar'))).toEqual( + expectedInitialEntries.filter(entry => entry.name === 'bar'), + ); + }); + + it('clears entries as specified', () => { + performance.mark('baz', {startTime: 20}); + performance.mark('bar', {startTime: 30}); + performance.mark('foo', {startTime: 10}); + + performance.mark('foo', {startTime: 50}); // again + + performance.measure('bar', {start: 20, duration: 40}); + performance.measure('foo', {start: 10, duration: 40}); + + performance.clearMarks('foo'); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + { + duration: 0, + entryType: 'mark', + name: 'baz', + startTime: 20, + }, + { + duration: 40, + entryType: 'measure', + name: 'bar', + startTime: 20, + }, + { + duration: 0, + entryType: 'mark', + name: 'bar', + startTime: 30, + }, + ]); + + expect(toJSON(performance.getEntriesByType('mark'))).toEqual([ + { + duration: 0, + entryType: 'mark', + name: 'baz', + startTime: 20, + }, + { + duration: 0, + entryType: 'mark', + name: 'bar', + startTime: 30, + }, + ]); + + expect(toJSON(performance.getEntriesByName('foo'))).toEqual([ + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + ]); + + performance.clearMeasures('bar'); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + { + duration: 0, + entryType: 'mark', + name: 'baz', + startTime: 20, + }, + { + duration: 0, + entryType: 'mark', + name: 'bar', + startTime: 30, + }, + ]); + + expect(toJSON(performance.getEntriesByType('measure'))).toEqual([ + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + ]); + + expect(toJSON(performance.getEntriesByName('bar'))).toEqual([ + { + duration: 0, + entryType: 'mark', + name: 'bar', + startTime: 30, + }, + ]); + + performance.clearMarks(); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 40, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + ]); + + expect(toJSON(performance.getEntriesByType('mark'))).toEqual([]); + + performance.clearMeasures(); + + expect(toJSON(performance.getEntries())).toEqual([]); + + expect(toJSON(performance.getEntriesByType('measure'))).toEqual([]); + }); + + it('handles consecutive adding and clearing (marks)', () => { + performance.mark('foo', {startTime: 10}); + performance.mark('foo', {startTime: 20}); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 0, + entryType: 'mark', + name: 'foo', + startTime: 10, + }, + { + duration: 0, + entryType: 'mark', + name: 'foo', + startTime: 20, + }, + ]); + + performance.clearMarks(); + + expect(toJSON(performance.getEntries())).toEqual([]); + + performance.mark('foo', {startTime: 30}); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 0, + entryType: 'mark', + name: 'foo', + startTime: 30, + }, + ]); + + performance.clearMarks(); + + expect(toJSON(performance.getEntries())).toEqual([]); + }); + + it('handles consecutive adding and clearing (measures)', () => { + performance.measure('foo', {start: 10, end: 20}); + performance.measure('foo', {start: 20, end: 30}); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 10, + entryType: 'measure', + name: 'foo', + startTime: 10, + }, + { + duration: 10, + entryType: 'measure', + name: 'foo', + startTime: 20, + }, + ]); + + performance.clearMeasures(); + + expect(toJSON(performance.getEntries())).toEqual([]); + + performance.measure('foo', {start: 30, end: 40}); + + expect(toJSON(performance.getEntries())).toEqual([ + { + duration: 10, + entryType: 'measure', + name: 'foo', + startTime: 30, + }, + ]); + + performance.clearMeasures(); + + expect(toJSON(performance.getEntries())).toEqual([]); + }); + }); }); From e6bff3f1fec7db9dbffa454948b994be27ec0db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0006/1383] Add tests for performance.eventCounts (#52463) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52463 Changelog: [internal] This adds Fantom tests for `performance.eventCounts`. Reviewed By: huntie Differential Revision: D77860881 fbshipit-source-id: 26b9ef56b9c610cbad7011bc0adde27251fda909 --- .../webperformance/NativePerformance.cpp | 4 ++ .../webperformance/NativePerformance.h | 1 + .../timeline/PerformanceEntryReporter.cpp | 4 ++ .../timeline/PerformanceEntryReporter.h | 2 + .../__tests__/EventTimingAPI-itest.js | 61 +++++++++++++++++++ .../performance/specs/NativePerformance.js | 1 + 6 files changed, 73 insertions(+) diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp index 7c8be7f36d2625..34b2cc21e84ce8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.cpp @@ -464,4 +464,8 @@ void NativePerformance::setCurrentTimeStampForTesting( forcedCurrentTimeStamp_ = ts; } +void NativePerformance::clearEventCountsForTesting(jsi::Runtime& /*rt*/) { + PerformanceEntryReporter::getInstance()->clearEventCounts(); +} + } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index d713171e14c63b..a1e05cf66c3d35 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -199,6 +199,7 @@ class NativePerformance : public NativePerformanceCxxSpec { #pragma mark - Testing void setCurrentTimeStampForTesting(jsi::Runtime& rt, HighResTimeStamp ts); + void clearEventCountsForTesting(jsi::Runtime& rt); private: std::optional forcedCurrentTimeStamp_; diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.cpp b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.cpp index 01a7591ccefde1..4bb9f8e44d207b 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.cpp +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.cpp @@ -213,6 +213,10 @@ PerformanceMeasure PerformanceEntryReporter::reportMeasure( return entry; } +void PerformanceEntryReporter::clearEventCounts() { + eventCounts_.clear(); +} + std::optional PerformanceEntryReporter::getMarkTime( const std::string& markName) const { std::shared_lock lock(buffersMutex_); diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h index 2eb67ceca0331f..1bacd16e1d900a 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h @@ -81,6 +81,8 @@ class PerformanceEntryReporter { return eventCounts_; } + void clearEventCounts(); + std::optional getMarkTime( const std::string& markName) const; diff --git a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js index 41df7c609a9882..4139eaaa29dff7 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js @@ -10,8 +10,10 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; +import type Performance from 'react-native/src/private/webapis/performance/Performance'; import type {PerformanceObserverEntryList} from 'react-native/src/private/webapis/performance/PerformanceObserver'; +import NativePerformance from '../specs/NativePerformance'; import * as Fantom from '@react-native/fantom'; import nullthrows from 'nullthrows'; import {useState} from 'react'; @@ -22,6 +24,8 @@ import {PerformanceObserver} from 'react-native/src/private/webapis/performance/ setUpPerformanceObserver(); +declare var performance: Performance; + function sleep(ms: number) { const end = performance.now() + ms; while (performance.now() < end) {} @@ -187,4 +191,61 @@ describe('Event Timing API', () => { expect(entry.interactionId).toBeGreaterThanOrEqual(0); }); + + it('reports number of dispatched events via performance.eventCounts', () => { + NativePerformance?.clearEventCountsForTesting?.(); + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + const element = nullthrows(root.document.documentElement.firstElementChild); + + expect(performance.eventCounts).not.toBeInstanceOf(Map); + + // FIXME: this isn't spec compliant, as the map should be prepopulated with + // all the supported event names mapped to 0. + expect(performance.eventCounts.size).toBe(0); + expect([...performance.eventCounts.entries()]).toEqual([]); + const initialForEachCallback = jest.fn(); + performance.eventCounts.forEach(initialForEachCallback); + expect(initialForEachCallback.mock.calls).toEqual([]); + expect([...performance.eventCounts.keys()]).toEqual([]); + expect([...performance.eventCounts.values()]).toEqual([]); + + Fantom.dispatchNativeEvent(element, 'click'); + Fantom.dispatchNativeEvent(element, 'click'); + Fantom.dispatchNativeEvent(element, 'click'); + + Fantom.dispatchNativeEvent(element, 'pointerDown'); + Fantom.dispatchNativeEvent(element, 'pointerUp'); + + expect(performance.eventCounts.size).toBe(3); + expect(performance.eventCounts.get('click')).toBe(3); + expect(performance.eventCounts.get('pointerdown')).toBe(1); + expect(performance.eventCounts.get('pointerup')).toBe(1); + + expect([...performance.eventCounts.entries()]).toEqual([ + ['pointerup', 1], + ['pointerdown', 1], + ['click', 3], + ]); + + const forEachCallback = jest.fn(); + performance.eventCounts.forEach(forEachCallback); + expect(forEachCallback.mock.calls).toEqual([ + [1, 'pointerup', performance.eventCounts], + [1, 'pointerdown', performance.eventCounts], + [3, 'click', performance.eventCounts], + ]); + + expect([...performance.eventCounts.keys()]).toEqual([ + 'pointerup', + 'pointerdown', + 'click', + ]); + + expect([...performance.eventCounts.values()]).toEqual([1, 1, 3]); + }); }); diff --git a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js index 6ce038f9395a89..39014040cf030a 100644 --- a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js @@ -107,6 +107,7 @@ export interface Spec extends TurboModule { +getSupportedPerformanceEntryTypes?: () => $ReadOnlyArray; +setCurrentTimeStampForTesting?: (timeStamp: number) => void; + +clearEventCountsForTesting?: () => void; } export default (TurboModuleRegistry.get('NativePerformanceCxx'): ?Spec); From 9f8179afa7c6d8ca98ea4cb871bde047e4fc5331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0007/1383] Add tests for durationThreshold option for PerformanceObserver (#52464) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52464 Changelog: [internal] This adds tests for the `durationThreshold` option for `PerformanceObserver.prototype.observe`. Reviewed By: huntie Differential Revision: D77860882 fbshipit-source-id: 1e56391166523d2c4f837f758bc367b58fe8e82e --- .../__tests__/EventTimingAPI-itest.js | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js index 4139eaaa29dff7..9f9e6615ccf6ff 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js @@ -248,4 +248,65 @@ describe('Event Timing API', () => { expect([...performance.eventCounts.values()]).toEqual([1, 1, 3]); }); + + describe('durationThreshold option', () => { + it('works when used with `type`', () => { + const callback = jest.fn(); + + const observer = new PerformanceObserver(callback); + observer.observe({type: 'event', durationThreshold: 50}); + + let forceDelay = false; + + function MyComponent() { + const [count, setCount] = useState(0); + + return ( + { + if (forceDelay) { + sleep(50); + } + setCount(count + 1); + }}> + {count} + + ); + } + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + const element = nullthrows( + root.document.documentElement.firstElementChild, + ); + + expect(callback).not.toHaveBeenCalled(); + + Fantom.dispatchNativeEvent(element, 'click'); + + expect(callback).toHaveBeenCalledTimes(0); + + forceDelay = true; + + Fantom.dispatchNativeEvent(element, 'click'); + + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('throws when used together with `entryTypes`', () => { + const observer = new PerformanceObserver(() => {}); + + expect(() => { + observer.observe({ + entryTypes: ['event', 'mark'], + durationThreshold: 100, + }); + }).toThrow( + `Failed to execute 'observe' on 'PerformanceObserver': An observe() call must not include both entryTypes and durationThreshold arguments.`, + ); + }); + }); }); From a3933e687828eeda5b2faac1f24962c95adf4a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Mon, 7 Jul 2025 06:42:23 -0700 Subject: [PATCH 0008/1383] Remove legacy tests for Performance API (#52465) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52465 Changelog: [internal] Now that we have enough coverage for the Performance API in Fantom, Jest tests where most of the API is mocked are redundant and useless, so this removes them (and the mock). Reviewed By: huntie Differential Revision: D77860888 fbshipit-source-id: 7dbd1a8a43b056a3b34e4e37d578be9ccb521824 --- .../performance/__tests__/Performance-test.js | 292 ------------------ .../__tests__/PerformanceObserver-test.js | 58 ---- .../specs/__mocks__/NativePerformanceMock.js | 269 ---------------- 3 files changed, 619 deletions(-) delete mode 100644 packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js delete mode 100644 packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js delete mode 100644 packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js 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 deleted file mode 100644 index 2b7a3108952e13..00000000000000 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-test.js +++ /dev/null @@ -1,292 +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 - */ - -// eslint-disable-next-line @react-native/monorepo/sort-imports -import type Performance from '../Performance'; - -import {performanceEntryTypeToRaw} from '../internals/RawPerformanceEntry'; -import {reportEntry} from '../specs/__mocks__/NativePerformanceMock'; - -jest.mock('../specs/NativePerformance', () => - require('../specs/__mocks__/NativePerformanceMock'), -); - -declare var performance: Performance; - -const NativePerformanceMock = - require('../specs/__mocks__/NativePerformanceMock').default; - -describe('Performance', () => { - beforeEach(() => { - jest.resetModules(); - - const PerformanceClass = require('../Performance').default; - // $FlowExpectedError[cannot-write] - global.performance = new PerformanceClass(); - }); - - it('reports marks and measures', () => { - NativePerformanceMock.setCurrentTime(25); - - performance.mark('mark-now'); - performance.mark('mark-in-the-past', { - startTime: 10, - }); - performance.mark('mark-in-the-future', { - startTime: 50, - }); - performance.measure('measure-with-specific-time', { - start: 30, - duration: 4, - }); - performance.measure('measure-now-with-start-mark', 'mark-in-the-past'); - performance.measure( - 'measure-with-start-and-end-mark', - 'mark-in-the-past', - 'mark-in-the-future', - ); - - const entries = performance.getEntries(); - expect(entries.length).toBe(6); - expect(entries.map(entry => entry.toJSON())).toEqual([ - { - duration: 0, - entryType: 'mark', - name: 'mark-in-the-past', - startTime: 10, - }, - { - duration: 15, - entryType: 'measure', - name: 'measure-now-with-start-mark', - startTime: 10, - }, - { - duration: 40, - entryType: 'measure', - name: 'measure-with-start-and-end-mark', - startTime: 10, - }, - { - duration: 0, - entryType: 'mark', - name: 'mark-now', - startTime: 25, - }, - { - duration: 4, - entryType: 'measure', - name: 'measure-with-specific-time', - startTime: 30, - }, - { - duration: 0, - entryType: 'mark', - name: 'mark-in-the-future', - startTime: 50, - }, - ]); - }); - - it('clearMarks and clearMeasures remove correct entry types', async () => { - performance.mark('entry1', {startTime: 0}); - performance.mark('mark2', {startTime: 0}); - - performance.measure('entry1', {start: 0, duration: 0}); - performance.measure('measure2', {start: 0, duration: 0}); - - performance.clearMarks(); - - expect(performance.getEntries().map(e => e.name)).toStrictEqual([ - 'entry1', - 'measure2', - ]); - - performance.mark('entry2', {startTime: 0}); - performance.mark('mark3', {startTime: 0}); - - performance.clearMeasures(); - - expect(performance.getEntries().map(e => e.name)).toStrictEqual([ - 'entry2', - 'mark3', - ]); - - performance.clearMarks(); - - expect(performance.getEntries().map(e => e.name)).toStrictEqual([]); - }); - - it('getEntries only works with allowed entry types', async () => { - performance.clearMarks(); - performance.clearMeasures(); - - performance.mark('entry1', {startTime: 0}); - performance.mark('mark2', {startTime: 0}); - - jest.spyOn(console, 'warn').mockImplementation(() => {}); - - performance.getEntriesByType('mark'); - expect(console.warn).not.toHaveBeenCalled(); - - performance.getEntriesByType('measure'); - expect(console.warn).not.toHaveBeenCalled(); - - performance.getEntriesByName('entry1'); - expect(console.warn).not.toHaveBeenCalled(); - - performance.getEntriesByName('entry1', 'event'); - expect(console.warn).toHaveBeenCalled(); - - performance.getEntriesByName('entry1', 'mark'); - expect(console.warn).toHaveBeenCalled(); - - performance.getEntriesByType('event'); - expect(console.warn).toHaveBeenCalled(); - }); - - it('getEntries works with marks and measures', async () => { - performance.clearMarks(); - performance.clearMeasures(); - - performance.mark('entry1', {startTime: 0}); - performance.mark('mark2', {startTime: 0}); - - performance.measure('entry1', {start: 0, duration: 0}); - performance.measure('measure2', {start: 0, duration: 0}); - - expect(performance.getEntries().map(e => e.name)).toStrictEqual([ - 'entry1', - 'mark2', - 'entry1', - 'measure2', - ]); - - expect(performance.getEntriesByType('mark').map(e => e.name)).toStrictEqual( - ['entry1', 'mark2'], - ); - - expect( - performance.getEntriesByType('measure').map(e => e.name), - ).toStrictEqual(['entry1', 'measure2']); - - expect( - performance.getEntriesByName('entry1').map(e => e.entryType), - ).toStrictEqual(['mark', 'measure']); - - expect( - performance.getEntriesByName('entry1', 'measure').map(e => e.entryType), - ).toStrictEqual(['measure']); - }); - - it('defines EventCounts for Performance', () => { - expect(performance.eventCounts).not.toBeUndefined(); - }); - - it('consistently implements the API for EventCounts', async () => { - let interactionId = 0; - const eventDefaultValues = { - entryType: performanceEntryTypeToRaw('event'), - startTime: 0, // startTime - duration: 100, // duration - processingStart: 0, // processing start - processingEnd: 100, // processingEnd - }; - - reportEntry({ - name: 'click', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'input', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'input', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - - const eventCounts = performance.eventCounts; - expect(eventCounts.size).toBe(3); - expect(Array.from(eventCounts.entries())).toStrictEqual([ - ['click', 1], - ['input', 2], - ['keyup', 3], - ]); - - expect(eventCounts.get('click')).toEqual(1); - expect(eventCounts.get('input')).toEqual(2); - expect(eventCounts.get('keyup')).toEqual(3); - - expect(eventCounts.has('click')).toEqual(true); - expect(eventCounts.has('input')).toEqual(true); - expect(eventCounts.has('keyup')).toEqual(true); - - expect(Array.from(eventCounts.keys())).toStrictEqual([ - 'click', - 'input', - 'keyup', - ]); - expect(Array.from(eventCounts.values())).toStrictEqual([1, 2, 3]); - - await jest.runAllTicks(); - reportEntry({ - name: 'input', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - expect(Array.from(eventCounts.values())).toStrictEqual([1, 3, 5]); - - await jest.runAllTicks(); - reportEntry({ - name: 'click', - ...eventDefaultValues, - interactionId: interactionId++, - }); - - await jest.runAllTicks(); - - reportEntry({ - name: 'keyup', - ...eventDefaultValues, - interactionId: interactionId++, - }); - - expect(Array.from(eventCounts.values())).toStrictEqual([2, 3, 6]); - }); -}); 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 deleted file mode 100644 index 9e96798378c074..00000000000000 --- a/packages/react-native/src/private/webapis/performance/__tests__/PerformanceObserver-test.js +++ /dev/null @@ -1,58 +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 - */ - -import type Performance from '../Performance'; -import type {PerformanceEntryList} from '../PerformanceEntry'; - -jest.mock( - '../specs/NativePerformance', - () => require('../specs/__mocks__/NativePerformanceMock').default, -); - -declare var performance: Performance; - -describe('PerformanceObserver', () => { - let PerformanceObserver; - - beforeEach(() => { - jest.resetModules(); - - // $FlowExpectedError[cannot-write] - global.performance = new (require('../Performance').default)(); - PerformanceObserver = require('../PerformanceObserver').PerformanceObserver; - }); - - it('prevents durationThreshold to be used together with entryTypes', async () => { - const observer = new PerformanceObserver((list, _observer) => {}); - - expect(() => - observer.observe({entryTypes: ['event', 'mark'], durationThreshold: 100}), - ).toThrow(); - }); - - it('ignores durationThreshold when used with marks or measures', async () => { - let entries: PerformanceEntryList = []; - - const observer = new PerformanceObserver((list, _observer) => { - entries = [...entries, ...list.getEntries()]; - }); - - observer.observe({type: 'measure', durationThreshold: 100}); - - performance.measure('measure1', { - start: 0, - duration: 10, - }); - - await jest.runAllTicks(); - expect(entries).toHaveLength(1); - expect(entries.map(e => e.name)).toStrictEqual(['measure1']); - }); -}); diff --git a/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js b/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js deleted file mode 100644 index 518ca5e61e9978..00000000000000 --- a/packages/react-native/src/private/webapis/performance/specs/__mocks__/NativePerformanceMock.js +++ /dev/null @@ -1,269 +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 - */ - -import type { - NativeBatchedObserverCallback, - NativeMemoryInfo, - NativePerformanceMarkResult, - NativePerformanceMeasureResult, - OpaqueNativeObserverHandle, - PerformanceObserverInit, - RawPerformanceEntry, - RawPerformanceEntryType, - ReactNativeStartupTiming, -} from '../NativePerformance'; -import typeof NativePerformance from '../NativePerformance'; - -import {RawPerformanceEntryTypeValues} from '../../internals/RawPerformanceEntry'; - -type MockObserver = { - handleEntry: (entry: RawPerformanceEntry) => void, - callback: NativeBatchedObserverCallback, - didScheduleFlushBuffer: boolean, - entries: Array, - options: PerformanceObserverInit, - droppedEntriesCount: number, -}; - -const eventCounts: Map = new Map(); -const observers: Set = new Set(); -const marks: Map = new Map(); -let entries: Array = []; - -function getMockObserver( - opaqueNativeObserverHandle: OpaqueNativeObserverHandle, -): MockObserver { - return opaqueNativeObserverHandle as $FlowFixMe as MockObserver; -} - -function createMockObserver(callback: NativeBatchedObserverCallback) { - const observer: MockObserver = { - callback, - didScheduleFlushBuffer: false, - entries: [], - options: {}, - droppedEntriesCount: 0, - handleEntry: (entry: RawPerformanceEntry) => { - if ( - observer.options.type !== entry.entryType && - !observer.options.entryTypes?.includes(entry.entryType) - ) { - return; - } - - if ( - entry.entryType === RawPerformanceEntryTypeValues.EVENT && - entry.duration < (observer.options?.durationThreshold ?? 0) - ) { - return; - } - - observer.entries.push(entry); - - if (!observer.didScheduleFlushBuffer) { - observer.didScheduleFlushBuffer = true; - // $FlowFixMe[incompatible-call] - global.queueMicrotask(() => { - observer.didScheduleFlushBuffer = false; - // We want to emulate the way it's done in native (i.e. async/batched) - observer.callback(); - }); - } - }, - }; - - return observer; -} - -export function reportEntry(entry: RawPerformanceEntry) { - entries.push(entry); - - switch (entry.entryType) { - case RawPerformanceEntryTypeValues.MARK: - marks.set(entry.name, entry.startTime); - break; - case RawPerformanceEntryTypeValues.MEASURE: - break; - case RawPerformanceEntryTypeValues.EVENT: - eventCounts.set(entry.name, (eventCounts.get(entry.name) ?? 0) + 1); - break; - } - - for (const observer of observers) { - observer.handleEntry(entry); - } -} - -let currentTime: number = 12; - -const NativePerformanceMock = { - setCurrentTime: (time: number): void => { - currentTime = time; - }, - - now: (): number => currentTime, - - markWithResult: ( - name: string, - startTime?: number, - ): NativePerformanceMarkResult => { - const computedStartTime = startTime ?? performance.now(); - - marks.set(name, computedStartTime); - reportEntry({ - entryType: RawPerformanceEntryTypeValues.MARK, - name, - startTime: computedStartTime, - duration: 0, - }); - - return computedStartTime; - }, - - measure: ( - name: string, - startTime?: number, - endTime?: number, - duration?: number, - startMark?: string, - endMark?: string, - ): NativePerformanceMeasureResult => { - const start = startMark != null ? marks.get(startMark) : startTime ?? 0; - const end = - endMark != null ? marks.get(endMark) : endTime ?? performance.now(); - - if (start === undefined) { - throw new Error('startMark does not exist'); - } - - if (end === undefined) { - throw new Error('endMark does not exist'); - } - - const computedDuration = duration ?? end - start; - reportEntry({ - entryType: RawPerformanceEntryTypeValues.MEASURE, - name, - startTime: start, - duration: computedDuration, - }); - - return [start, computedDuration]; - }, - - getSimpleMemoryInfo: (): NativeMemoryInfo => { - return {}; - }, - - getReactNativeStartupTiming: (): ReactNativeStartupTiming => { - return { - startTime: 0, - endTime: 0, - executeJavaScriptBundleEntryPointStart: 0, - executeJavaScriptBundleEntryPointEnd: 0, - initializeRuntimeStart: 0, - initializeRuntimeEnd: 0, - }; - }, - - getEventCounts: (): $ReadOnlyArray<[string, number]> => { - return Array.from(eventCounts.entries()); - }, - - createObserver: ( - callback: NativeBatchedObserverCallback, - ): OpaqueNativeObserverHandle => { - // $FlowExpectedError[incompatible-return] - return createMockObserver(callback); - }, - - getDroppedEntriesCount: (observer: OpaqueNativeObserverHandle): number => { - return getMockObserver(observer).droppedEntriesCount; - }, - - observe: ( - observer: OpaqueNativeObserverHandle, - options: PerformanceObserverInit, - ): void => { - const mockObserver = getMockObserver(observer); - mockObserver.options = options; - observers.add(mockObserver); - }, - - disconnect: (observer: OpaqueNativeObserverHandle): void => { - const mockObserver = getMockObserver(observer); - observers.delete(mockObserver); - }, - - takeRecords: ( - observer: OpaqueNativeObserverHandle, - ): $ReadOnlyArray => { - const mockObserver = getMockObserver(observer); - const observerEntries = mockObserver.entries; - mockObserver.entries = []; - return observerEntries.sort((a, b) => a.startTime - b.startTime); - }, - - clearMarks: (entryName?: string) => { - if (entryName != null) { - marks.delete(entryName); - } else { - marks.clear(); - } - - entries = entries.filter( - entry => - entry.entryType !== RawPerformanceEntryTypeValues.MARK || - (entryName != null && entry.name !== entryName), - ); - }, - - clearMeasures: (entryName?: string) => { - entries = entries.filter( - entry => - entry.entryType !== RawPerformanceEntryTypeValues.MEASURE || - (entryName != null && entry.name !== entryName), - ); - }, - - getEntries: (): $ReadOnlyArray => { - return [...entries].sort((a, b) => a.startTime - b.startTime); - }, - - getEntriesByName: ( - entryName: string, - entryType?: ?RawPerformanceEntryType, - ): $ReadOnlyArray => { - return NativePerformanceMock.getEntries().filter( - entry => - (entryType == null || entry.entryType === entryType) && - entry.name === entryName, - ); - }, - - getEntriesByType: ( - entryType: RawPerformanceEntryType, - ): $ReadOnlyArray => { - return entries.filter(entry => entry.entryType === entryType); - }, - - getSupportedPerformanceEntryTypes: - (): $ReadOnlyArray => { - return [ - RawPerformanceEntryTypeValues.MARK, - RawPerformanceEntryTypeValues.MEASURE, - RawPerformanceEntryTypeValues.EVENT, - ]; - }, -}; - -(NativePerformanceMock: NativePerformance); - -export default NativePerformanceMock; From c1200718a01e61a5c699039c6325a2fee5f42c60 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Jul 2025 08:59:56 -0700 Subject: [PATCH 0009/1383] Move RuntimeExecutor after copying it into BufferedRuntimeExecutor (#52404) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52404 Changelog: [Internal] https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h#L23 is a copy-able type (it will be copied when passed into the BufferedRuntimeExecutor constructor). Hence we can `std::move` it in the `BufferedRuntimeExecutor` constructor Reviewed By: javache Differential Revision: D77758211 fbshipit-source-id: 634b1cd0e1ed4d27a013ad8927b2123dc6977ad8 --- .../ReactCommon/react/runtime/BufferedRuntimeExecutor.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.cpp b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.cpp index 5d6a8e9960bdc2..389cbbc16a5db3 100644 --- a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.cpp +++ b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.cpp @@ -7,13 +7,11 @@ #include "BufferedRuntimeExecutor.h" -#include - namespace facebook::react { BufferedRuntimeExecutor::BufferedRuntimeExecutor( RuntimeExecutor runtimeExecutor) - : runtimeExecutor_(runtimeExecutor), + : runtimeExecutor_(std::move(runtimeExecutor)), isBufferingEnabled_(true), lastIndex_(0) {} @@ -51,7 +49,7 @@ void BufferedRuntimeExecutor::flush() { void BufferedRuntimeExecutor::unsafeFlush() { while (queue_.size() > 0) { const BufferedWork& bufferedWork = queue_.top(); - Work work = std::move(bufferedWork.work_); + Work work = bufferedWork.work_; runtimeExecutor_(std::move(work)); queue_.pop(); } From 298ec6ca5de1a14cd70152364ecead5c8fcb04a5 Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Mon, 7 Jul 2025 09:29:57 -0700 Subject: [PATCH 0010/1383] Deprecate ShadowNode::ListOfWeak and replace with std::vector> (#52401) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52401 changelog: [internal] - Mark ShadowNode::ListOfWeak as deprecated with appropriate deprecation message - Replace all usages of ShadowNode::ListOfWeak with std::vector> - Updated primitives.h and ReactNativeCPP.api to use the explicit type instead of the alias This change continues the effort to remove type aliases in favor of explicit standard library types for better code clarity and maintainability. Reviewed By: christophpurrer Differential Revision: D77652083 fbshipit-source-id: 79cad019e039c19f661346604ff49a44a4af7a79 --- .../ReactCommon/react/renderer/core/ShadowNode.h | 8 ++++++-- .../ReactCommon/react/renderer/uimanager/primitives.h | 3 ++- private/cxx-public-api/ReactNativeCPP.api | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h index eb7fd0cb1127ae..445bb9d9b070f2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h @@ -45,12 +45,16 @@ class ShadowNode : public Sealable, using ListOfShared [[deprecated( "Use std::vector> instead")]] = std::vector>; - using ListOfWeak = std::vector>; + // TODO(T223558094): delete this in the next version. + using ListOfWeak [[deprecated( + "Use std::vector> instead")]] = + std::vector>; using SharedListOfShared = std::shared_ptr>>; using UnsharedListOfShared = std::shared_ptr>>; - using UnsharedListOfWeak = std::shared_ptr; + using UnsharedListOfWeak = + std::shared_ptr>>; using AncestorList = std::vector /* parentNode */, diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h b/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h index af0da029f106da..70cb2a1cbcb5b0 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h @@ -112,7 +112,8 @@ inline static ShadowNode::UnsharedListOfWeak weakShadowNodeListFromValue( jsi::Runtime& runtime, const jsi::Value& value) { auto shadowNodeList = shadowNodeListFromValue(runtime, value); - auto weakShadowNodeList = std::make_shared(); + auto weakShadowNodeList = + std::make_shared>>(); for (const auto& shadowNode : *shadowNodeList) { weakShadowNodeList->push_back(shadowNode); } diff --git a/private/cxx-public-api/ReactNativeCPP.api b/private/cxx-public-api/ReactNativeCPP.api index 8c2f51b8e1b5d9..d52206efcce912 100644 --- a/private/cxx-public-api/ReactNativeCPP.api +++ b/private/cxx-public-api/ReactNativeCPP.api @@ -37938,7 +37938,7 @@ inline static ShadowNode::UnsharedListOfWeak weakShadowNodeListFromValue( jsi::Runtime& runtime, const jsi::Value& value) { auto shadowNodeList = shadowNodeListFromValue(runtime, value); - auto weakShadowNodeList = std::make_shared(); + auto weakShadowNodeList = std::make_shared>>(); for (const auto& shadowNode : *shadowNodeList) { weakShadowNodeList->push_back(shadowNode); } From 06034554e41fba16f3ed665fe5fbc6de33a3e4dc Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Jul 2025 09:37:37 -0700 Subject: [PATCH 0011/1383] Remove SampleTurboCxxModule example (#52442) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52442 Changelog: [Internal] The sample is from an outdated approach of enabling C++ Modules in RN which is not recommended anymore. Prefer C++ Turbo Modules if you need to expose / access C or C++ APIs in RN apps: https://reactnative.dev/docs/the-new-architecture/pure-cxx-modules It is not included in any RNTester app at this time Reviewed By: cortinico Differential Revision: D77771111 fbshipit-source-id: a4fe1d13fd0224babc46f54b921a036f7b237a48 --- .../NativeSampleTurboCxxModuleSpecJSI.cpp | 151 ------------------ .../NativeSampleTurboCxxModuleSpecJSI.h | 42 ----- .../samples/ReactCommon/README.md | 2 + .../ReactCommon/SampleTurboCxxModule.cpp | 96 ----------- .../ReactCommon/SampleTurboCxxModule.h | 43 ----- packages/rn-tester/RNTester/AppDelegate.mm | 5 - 6 files changed, 2 insertions(+), 337 deletions(-) delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h create mode 100644 packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/README.md delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp deleted file mode 100644 index adbbe2c577530a..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp +++ /dev/null @@ -1,151 +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 "NativeSampleTurboCxxModuleSpecJSI.h" - -// NOTE: This entire file should be codegen'ed. - -namespace facebook::react { - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_voidFunc( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - static_cast(&turboModule)->voidFunc(rt); - return jsi::Value::undefined(); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return jsi::Value( - static_cast(&turboModule) - ->getBool(rt, args[0].getBool())); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return jsi::Value( - static_cast(&turboModule) - ->getEnum(rt, args[0].getNumber())); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return jsi::Value( - static_cast(&turboModule) - ->getNumber(rt, args[0].getNumber())); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getString( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getString(rt, args[0].getString(rt)); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getArray( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getArray(rt, args[0].getObject(rt).getArray(rt)); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getObject( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getObject(rt, args[0].getObject(rt)); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValue( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getValue( - rt, - args[0].getNumber(), - args[1].getString(rt), - args[2].getObject(rt)); -} - -static jsi::Value -__hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValueWithCallback( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - static_cast(&turboModule) - ->getValueWithCallback( - rt, std::move(args[0].getObject(rt).getFunction(rt))); - return jsi::Value::undefined(); -} - -static jsi::Value -__hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValueWithPromise( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getValueWithPromise(rt, args[0].getBool()); -} - -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getConstants( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count) { - return static_cast(&turboModule) - ->getConstants(rt); -} - -NativeSampleTurboCxxModuleSpecJSI::NativeSampleTurboCxxModuleSpecJSI( - std::shared_ptr jsInvoker) - : TurboModule("SampleTurboCxxModule", jsInvoker) { - methodMap_["voidFunc"] = MethodMetadata{ - 0, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_voidFunc}; - methodMap_["getBool"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool}; - methodMap_["getEnum"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum}; - methodMap_["getNumber"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber}; - methodMap_["getString"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getString}; - methodMap_["getArray"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getArray}; - methodMap_["getObject"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getObject}; - methodMap_["getValue"] = MethodMetadata{ - 3, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValue}; - methodMap_["getValueWithCallback"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValueWithCallback}; - methodMap_["getValueWithPromise"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getValueWithPromise}; - methodMap_["getConstants"] = MethodMetadata{ - 0, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getConstants}; -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h deleted file mode 100644 index ad602b0425acef..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h +++ /dev/null @@ -1,42 +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 { - -// TODO: This definition should be codegen'ed for type-safety purpose. -class JSI_EXPORT NativeSampleTurboCxxModuleSpecJSI : public TurboModule { - protected: - NativeSampleTurboCxxModuleSpecJSI(std::shared_ptr jsInvoker); - - public: - virtual void voidFunc(jsi::Runtime& rt) = 0; - virtual bool getBool(jsi::Runtime& rt, bool arg) = 0; - virtual double getEnum(jsi::Runtime& rt, double arg) = 0; - virtual double getNumber(jsi::Runtime& rt, double arg) = 0; - virtual jsi::String getString(jsi::Runtime& rt, const jsi::String& arg) = 0; - virtual jsi::Array getArray(jsi::Runtime& rt, const jsi::Array& arg) = 0; - virtual jsi::Object getObject(jsi::Runtime& rt, const jsi::Object& arg) = 0; - virtual jsi::Object getValue( - jsi::Runtime& rt, - double x, - const jsi::String& y, - const jsi::Object& z) = 0; - virtual void getValueWithCallback( - jsi::Runtime& rt, - const jsi::Function& callback) = 0; - virtual jsi::Value getValueWithPromise(jsi::Runtime& rt, bool error) = 0; - virtual jsi::Object getConstants(jsi::Runtime& rt) = 0; -}; - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/README.md b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/README.md new file mode 100644 index 00000000000000..979ec378250904 --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/README.md @@ -0,0 +1,2 @@ +Refer to packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h for a concrete example. +See: https://reactnative.dev/docs/the-new-architecture/pure-cxx-modules diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp deleted file mode 100644 index bb8181592edc5a..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp +++ /dev/null @@ -1,96 +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 "SampleTurboCxxModule.h" - -#include - -using namespace facebook; - -namespace facebook::react { - -SampleTurboCxxModule::SampleTurboCxxModule( - std::shared_ptr jsInvoker) - : NativeSampleTurboCxxModuleSpecJSI(jsInvoker) {} - -void SampleTurboCxxModule::voidFunc(jsi::Runtime& rt) { - // Nothing to do -} - -bool SampleTurboCxxModule::getBool(jsi::Runtime& rt, bool arg) { - return arg; -} - -double SampleTurboCxxModule::getEnum(jsi::Runtime& rt, double arg) { - return arg; -} - -double SampleTurboCxxModule::getNumber(jsi::Runtime& rt, double arg) { - return arg; -} - -jsi::String SampleTurboCxxModule::getString( - jsi::Runtime& rt, - const jsi::String& arg) { - return jsi::String::createFromUtf8(rt, arg.utf8(rt)); -} - -jsi::Array SampleTurboCxxModule::getArray( - jsi::Runtime& rt, - const jsi::Array& arg) { - return deepCopyJSIArray(rt, arg); -} - -jsi::Object SampleTurboCxxModule::getObject( - jsi::Runtime& rt, - const jsi::Object& arg) { - return deepCopyJSIObject(rt, arg); -} - -jsi::Object SampleTurboCxxModule::getValue( - jsi::Runtime& rt, - double x, - const jsi::String& y, - const jsi::Object& z) { - // Note: return type isn't type-safe. - jsi::Object result(rt); - result.setProperty(rt, "x", jsi::Value(x)); - result.setProperty(rt, "y", jsi::String::createFromUtf8(rt, y.utf8(rt))); - result.setProperty(rt, "z", deepCopyJSIObject(rt, z)); - return result; -} - -void SampleTurboCxxModule::getValueWithCallback( - jsi::Runtime& rt, - const jsi::Function& callback) { - callback.call(rt, jsi::String::createFromUtf8(rt, "value from callback!")); -} - -jsi::Value SampleTurboCxxModule::getValueWithPromise( - jsi::Runtime& rt, - bool error) { - return createPromiseAsJSIValue( - rt, [error](jsi::Runtime& rt2, std::shared_ptr promise) { - if (error) { - promise->reject("intentional promise rejection"); - } else { - promise->resolve(jsi::String::createFromUtf8(rt2, "result!")); - } - }); -} - -jsi::Object SampleTurboCxxModule::getConstants(jsi::Runtime& rt) { - // Note: return type isn't type-safe. - jsi::Object result(rt); - result.setProperty(rt, "const1", jsi::Value(true)); - result.setProperty(rt, "const2", jsi::Value(375)); - result.setProperty( - rt, "const3", jsi::String::createFromUtf8(rt, "something")); - return result; -} - -} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h b/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h deleted file mode 100644 index 5e2d7e66980cd1..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h +++ /dev/null @@ -1,43 +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 "NativeSampleTurboCxxModuleSpecJSI.h" - -namespace facebook::react { - -/** - * A sample implementation of the C++ spec. In practice, this class can just - * extend jsi::HostObject directly, but using the spec provides build-time - * type-safety. - */ -class SampleTurboCxxModule : public NativeSampleTurboCxxModuleSpecJSI { - public: - SampleTurboCxxModule(std::shared_ptr jsInvoker); - - void voidFunc(jsi::Runtime& rt) override; - bool getBool(jsi::Runtime& rt, bool arg) override; - double getEnum(jsi::Runtime& rt, double arg) override; - double getNumber(jsi::Runtime& rt, double arg) override; - jsi::String getString(jsi::Runtime& rt, const jsi::String& arg) override; - jsi::Array getArray(jsi::Runtime& rt, const jsi::Array& arg) override; - jsi::Object getObject(jsi::Runtime& rt, const jsi::Object& arg) override; - jsi::Object getValue( - jsi::Runtime& rt, - double x, - const jsi::String& y, - const jsi::Object& z) override; - void getValueWithCallback(jsi::Runtime& rt, const jsi::Function& callback) - override; - jsi::Value getValueWithPromise(jsi::Runtime& rt, bool error) override; - jsi::Object getConstants(jsi::Runtime& rt) override; -}; - -} // namespace facebook::react diff --git a/packages/rn-tester/RNTester/AppDelegate.mm b/packages/rn-tester/RNTester/AppDelegate.mm index 857b5e4c87e9eb..22ac5f25ec9622 100644 --- a/packages/rn-tester/RNTester/AppDelegate.mm +++ b/packages/rn-tester/RNTester/AppDelegate.mm @@ -14,7 +14,6 @@ #import #import #import -#import #import @@ -83,10 +82,6 @@ - (BOOL)application:(UIApplication *)app - (std::shared_ptr)getTurboModule:(const std::string &)name jsInvoker:(std::shared_ptr)jsInvoker { - if (name == std::string([@"SampleTurboCxxModule" UTF8String])) { - return std::make_shared(jsInvoker); - } - if (name == facebook::react::NativeCxxModuleExample::kModuleName) { return std::make_shared(jsInvoker); } From 625f69f284ddfd9c6beecaa4052a871d092053ef Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 7 Jul 2025 10:20:43 -0700 Subject: [PATCH 0012/1383] @DeprecatedInNewArchitecture -> @Deprecated (#52399) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52399 I'm raising the deprecation warnings for those methods that are using legacy arch. Previously the `DeprecatedInNewArchitecture` was not generating warnings for user in their builds, while now the Kotlin's/Java's `DeprecatedInNewArchitecture` it will. Changelog: [Android] [Changed] - Introduce more deprecation warnings for Legacy Arch classes Reviewed By: mdvacca Differential Revision: D77736713 fbshipit-source-id: bc21729ed8253d3ec6b6a40577bcd76622c3f8a6 --- .../react/tasks/GeneratePackageListTask.kt | 1 + .../tasks/GeneratePackageListTaskTest.kt | 4 +- .../OSSLibraryExamplePackage.kt | 2 + .../ReactAndroid/api/ReactAndroid.api | 2 +- .../com/facebook/react/BaseReactPackage.kt | 1 + .../facebook/react/HeadlessJsTaskService.kt | 1 + .../com/facebook/react/LazyReactPackage.kt | 2 + .../facebook/react/ReactActivityDelegate.java | 63 +++++++++++-------- .../com/facebook/react/ReactApplication.kt | 4 ++ .../java/com/facebook/react/ReactDelegate.kt | 9 ++- .../java/com/facebook/react/ReactFragment.kt | 4 ++ .../com/facebook/react/ReactNativeHost.java | 10 +-- .../java/com/facebook/react/ReactPackage.kt | 6 +- .../com/facebook/react/ReactPackageHelper.kt | 1 + .../ReactPackageTurboModuleManagerDelegate.kt | 2 + .../facebook/react/bridge/BaseJavaModule.java | 2 - .../react/bridge/BridgeReactContext.java | 27 +++++--- .../react/bridge/CxxModuleWrapperBase.kt | 2 + .../com/facebook/react/bridge/ModuleHolder.kt | 1 + .../facebook/react/bridge/NativeModule.java | 6 +- .../DeprecatedInNewArchitecture.kt | 16 ----- .../react/defaults/DefaultReactHost.kt | 2 + .../react/defaults/DefaultReactNativeHost.kt | 2 + .../react/modules/blob/BlobProvider.kt | 2 +- .../uimanager/ViewManagerPropertyUpdater.kt | 3 +- .../react/uimanager/common/UIManagerType.kt | 2 - .../react/fabric/FabricUIManagerTest.kt | 2 + .../react/fabric/MountingManagerTest.kt | 2 + .../modules/clipboard/ClipboardModuleTest.kt | 2 + .../deviceinfo/DeviceInfoModuleTest.kt | 2 + .../react/uimanager/BaseViewManagerTest.kt | 2 + .../react/uimanager/ReactPropConstantsTest.kt | 2 + .../ReactPropForShadowNodeSetterTest.kt | 2 + .../uimanager/UIManagerModuleConstantsTest.kt | 2 + .../react/uiapp/RNTesterApplication.kt | 9 +-- 35 files changed, 125 insertions(+), 77 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/annotations/DeprecatedInNewArchitecture.kt diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GeneratePackageListTask.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GeneratePackageListTask.kt index 36cc66caf88831..100db62882486b 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GeneratePackageListTask.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GeneratePackageListTask.kt @@ -148,6 +148,7 @@ abstract class GeneratePackageListTask : DefaultTask() { {{ packageImports }} + @SuppressWarnings("deprecation") public class PackageList { private Application application; private ReactNativeHost reactNativeHost; diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GeneratePackageListTaskTest.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GeneratePackageListTaskTest.kt index 0214403d67c8f1..fc85587d15e39f 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GeneratePackageListTaskTest.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GeneratePackageListTaskTest.kt @@ -233,6 +233,7 @@ class GeneratePackageListTaskTest { + @SuppressWarnings("deprecation") public class PackageList { private Application application; private ReactNativeHost reactNativeHost; @@ -311,7 +312,8 @@ class GeneratePackageListTaskTest { import com.facebook.react.aPackage; // @react-native/another-package import com.facebook.react.anotherPackage; - + + @SuppressWarnings("deprecation") public class PackageList { private Application application; private ReactNativeHost reactNativeHost; diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt index 00508e089a3e2c..428cd61ed9e621 100644 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt +++ b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt @@ -12,7 +12,9 @@ import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager +@Suppress("DEPRECATION") public class OSSLibraryExamplePackage : ReactPackage { + @Deprecated("Migrate to [BaseReactPackage] and implement [getModule] instead.") override fun createNativeModules(reactContext: ReactApplicationContext): List = listOf(NativeSampleModule(reactContext)) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index fc70f58c19792f..fc5b2b28b8ae28 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -353,7 +353,7 @@ public abstract class com/facebook/react/ReactNativeHost { } public abstract interface class com/facebook/react/ReactPackage { - public abstract fun createNativeModules (Lcom/facebook/react/bridge/ReactApplicationContext;)Ljava/util/List; + public fun createNativeModules (Lcom/facebook/react/bridge/ReactApplicationContext;)Ljava/util/List; public abstract fun createViewManagers (Lcom/facebook/react/bridge/ReactApplicationContext;)Ljava/util/List; public fun getModule (Ljava/lang/String;Lcom/facebook/react/bridge/ReactApplicationContext;)Lcom/facebook/react/bridge/NativeModule; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/BaseReactPackage.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/BaseReactPackage.kt index c6a3c87d94901a..9ad6912d215f05 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/BaseReactPackage.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/BaseReactPackage.kt @@ -22,6 +22,7 @@ import javax.inject.Provider /** Abstract class that supports lazy loading of NativeModules by default. */ public abstract class BaseReactPackage : ReactPackage { + @Deprecated("Migrate to [BaseReactPackage] and implement [getModule] instead.") override fun createNativeModules(reactContext: ReactApplicationContext): List { throw UnsupportedOperationException( "createNativeModules method is not supported. Use getModule() method instead.") diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.kt index eff3c4288287e3..e974a935798e8f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.kt @@ -112,6 +112,7 @@ public abstract class HeadlessJsTaskService : Service(), HeadlessJsTaskEventList * simply have a different mechanism for storing a `ReactNativeHost`, e.g. as a static field * somewhere. */ + @Suppress("DEPRECATION") protected val reactNativeHost: ReactNativeHost get() = (application as ReactApplication).reactNativeHost diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.kt index acf881246c4ac1..66b767066e3f0b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.kt @@ -92,6 +92,8 @@ public abstract class LazyReactPackage : ReactPackage { * @param reactContext react application context that can be used to create modules * @return A [List]<[NativeModule]> to register */ + @Suppress("DEPRECATION") + @Deprecated("Migrate to [BaseReactPackage] and implement [getModule] instead.") override fun createNativeModules(reactContext: ReactApplicationContext): List = buildList { for (holder in getNativeModules(reactContext)) { 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 47945767493c3f..12793d95d9472b 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 @@ -18,20 +18,22 @@ import android.view.Window; import androidx.annotation.Nullable; import com.facebook.infer.annotation.Assertions; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactContext; -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.interfaces.fabric.ReactSurface; import com.facebook.react.internal.featureflags.ReactNativeNewArchitectureFeatureFlags; import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.views.view.WindowUtilKt; import com.facebook.systrace.Systrace; +import java.util.Objects; /** * Delegate class for {@link ReactActivity}. You can subclass this to provide custom implementations * for e.g. {@link #getReactNativeHost()}, if your Application class doesn't implement {@link * ReactApplication}. */ +@Nullsafe(Nullsafe.Mode.LOCAL) public class ReactActivityDelegate { private final @Nullable Activity mActivity; @@ -86,8 +88,11 @@ public ReactActivityDelegate( * ReactApplication#getReactNativeHost()}. Override this method if your application class does not * implement {@code ReactApplication} or you simply have a different mechanism for storing a * {@code ReactNativeHost}, e.g. as a static field somewhere. + * + * @deprecated "Do not access {@link ReactNativeHost} directly. This class is going away in the + * New Architecture. You should access {@link ReactHost} instead." */ - @DeprecatedInNewArchitecture(message = "Use getReactHost()") + @Deprecated protected ReactNativeHost getReactNativeHost() { return ((ReactApplication) getPlainActivity().getApplication()).getReactNativeHost(); } @@ -107,16 +112,21 @@ protected ReactNativeHost getReactNativeHost() { return mReactDelegate; } - @DeprecatedInNewArchitecture(message = "Use getReactHost()") + /** + * @deprecated @deprecated "Do not access {@link ReactInstanceManager} directly. This class is + * going away in the New Architecture. You should access {@link ReactHost} instead." + * @noinspection deprecation + */ public ReactInstanceManager getReactInstanceManager() { - return mReactDelegate.getReactInstanceManager(); + return Objects.requireNonNull(mReactDelegate).getReactInstanceManager(); } + @Nullable public String getMainComponentName() { return mMainComponentName; } - public void onCreate(Bundle savedInstanceState) { + public void onCreate(@Nullable Bundle savedInstanceState) { Systrace.traceSection( Systrace.TRACE_TAG_REACT, "ReactActivityDelegate.onCreate::init", @@ -147,6 +157,7 @@ public void onCreate(Bundle savedInstanceState) { launchOptions, isFabricEnabled()) { @Override + @Nullable protected ReactRootView createRootView() { ReactRootView rootView = ReactActivityDelegate.this.createRootView(); if (rootView == null) { @@ -162,31 +173,29 @@ protected ReactRootView createRootView() { }); } - protected void loadApp(String appKey) { - mReactDelegate.loadApp(appKey); + protected void loadApp(@Nullable String appKey) { + Objects.requireNonNull(mReactDelegate).loadApp(Objects.requireNonNull(appKey)); getPlainActivity().setContentView(mReactDelegate.getReactRootView()); } public void setReactSurface(ReactSurface reactSurface) { - mReactDelegate.setReactSurface(reactSurface); + Objects.requireNonNull(mReactDelegate).setReactSurface(reactSurface); } public void setReactRootView(ReactRootView reactRootView) { - mReactDelegate.setReactRootView(reactRootView); + Objects.requireNonNull(mReactDelegate).setReactRootView(reactRootView); } public void onUserLeaveHint() { - if (mReactDelegate != null) { - mReactDelegate.onUserLeaveHint(); - } + Objects.requireNonNull(mReactDelegate).onUserLeaveHint(); } public void onPause() { - mReactDelegate.onHostPause(); + Objects.requireNonNull(mReactDelegate).onHostPause(); } public void onResume() { - mReactDelegate.onHostResume(); + Objects.requireNonNull(mReactDelegate).onHostResume(); if (mPermissionsCallback != null) { mPermissionsCallback.invoke(); @@ -195,43 +204,43 @@ public void onResume() { } public void onDestroy() { - mReactDelegate.onHostDestroy(); + Objects.requireNonNull(mReactDelegate).onHostDestroy(); } - public void onActivityResult(int requestCode, int resultCode, Intent data) { - mReactDelegate.onActivityResult(requestCode, resultCode, data, true); + public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { + Objects.requireNonNull(mReactDelegate).onActivityResult(requestCode, resultCode, data, true); } public boolean onKeyDown(int keyCode, KeyEvent event) { - return mReactDelegate.onKeyDown(keyCode, event); + return Objects.requireNonNull(mReactDelegate).onKeyDown(keyCode, event); } public boolean onKeyUp(int keyCode, KeyEvent event) { - return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event); + return Objects.requireNonNull(mReactDelegate).shouldShowDevMenuOrReload(keyCode, event); } public boolean onKeyLongPress(int keyCode, KeyEvent event) { - return mReactDelegate.onKeyLongPress(keyCode); + return Objects.requireNonNull(mReactDelegate).onKeyLongPress(keyCode); } public boolean onBackPressed() { - return mReactDelegate.onBackPressed(); + return Objects.requireNonNull(mReactDelegate).onBackPressed(); } - public boolean onNewIntent(Intent intent) { - return mReactDelegate.onNewIntent(intent); + public boolean onNewIntent(@Nullable Intent intent) { + return Objects.requireNonNull(mReactDelegate).onNewIntent(Objects.requireNonNull(intent)); } public void onWindowFocusChanged(boolean hasFocus) { - mReactDelegate.onWindowFocusChanged(hasFocus); + Objects.requireNonNull(mReactDelegate).onWindowFocusChanged(hasFocus); } public void onConfigurationChanged(Configuration newConfig) { - mReactDelegate.onConfigurationChanged(newConfig); + Objects.requireNonNull(mReactDelegate).onConfigurationChanged(newConfig); } public void requestPermissions( - String[] permissions, int requestCode, PermissionListener listener) { + String[] permissions, int requestCode, @Nullable PermissionListener listener) { mPermissionListener = listener; getPlainActivity().requestPermissions(permissions, requestCode); } @@ -267,7 +276,7 @@ protected ReactActivity getReactActivity() { * context will no longer be valid. */ public @Nullable ReactContext getCurrentReactContext() { - return mReactDelegate.getCurrentReactContext(); + return Objects.requireNonNull(mReactDelegate).getCurrentReactContext(); } /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.kt index 9360b51f734237..306eb49aa3cb33 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.kt @@ -10,6 +10,10 @@ package com.facebook.react /** Interface that represents an instance of a React Native application */ public interface ReactApplication { /** Get the default [ReactNativeHost] for this app. */ + @Suppress("DEPRECATION") + @Deprecated( + "You should not use ReactNativeHost directly in the New Architecture. Use ReactHost instead.", + ReplaceWith("reactHost")) public val reactNativeHost: ReactNativeHost /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.kt index 258bb6bcf472f3..4d81bc58c1165c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.kt @@ -14,7 +14,6 @@ import android.os.Bundle import android.view.KeyEvent import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.UiThreadUtil.runOnUiThread -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture import com.facebook.react.devsupport.DoubleTapReloadRecognizer import com.facebook.react.devsupport.ReleaseDevSupportManager import com.facebook.react.devsupport.interfaces.DevSupportManager @@ -26,12 +25,17 @@ import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler * A delegate for handling React Application support. This delegate is unaware whether it is used in * an [Activity] or a [android.app.Fragment]. */ +@Suppress("DEPRECATION") public open class ReactDelegate { private val activity: Activity private var internalReactRootView: ReactRootView? = null private val mainComponentName: String? private var launchOptions: Bundle? private var doubleTapReloadRecognizer: DoubleTapReloadRecognizer? + + @Deprecated( + "You should not use ReactNativeHost directly in the New Architecture. Use ReactHost instead.", + ReplaceWith("reactHost")) private var reactNativeHost: ReactNativeHost? = null public var reactHost: ReactHost? = null private set @@ -380,7 +384,8 @@ public open class ReactDelegate { return false } - @DeprecatedInNewArchitecture(message = "Use reactHost") + @Deprecated( + "Do not access [ReactInstanceManager] directly. This class is going away in the New Architecture. You should use [ReactHost] instead.") public fun getReactInstanceManager(): ReactInstanceManager { val nonNullReactNativeHost = checkNotNull(reactNativeHost) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.kt index a8b45e5745fa17..304a0d003b43e8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.kt @@ -58,6 +58,10 @@ public open class ReactFragment : Fragment(), PermissionAwareActivity { * method if your application class does not implement `ReactApplication` or you simply have a * different mechanism for storing a `ReactNativeHost`, e.g. as a static field somewhere. */ + @Suppress("DEPRECATION") + @Deprecated( + "You should not use ReactNativeHost directly in the New Architecture. Use ReactHost instead.", + ReplaceWith("reactHost")) protected open val reactNativeHost: ReactNativeHost? get() = (activity?.application as ReactApplication?)?.reactNativeHost diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java index 2745a672cadebb..b05e6bb7dc6ee8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java @@ -10,6 +10,7 @@ import android.app.Application; import androidx.annotation.Nullable; import com.facebook.infer.annotation.Assertions; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.react.bridge.JSExceptionHandler; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.bridge.ReactMarker; @@ -18,7 +19,6 @@ import com.facebook.react.common.LifecycleState; import com.facebook.react.common.SurfaceDelegate; import com.facebook.react.common.SurfaceDelegateFactory; -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.common.annotations.internal.LegacyArchitecture; import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel; import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger; @@ -32,12 +32,12 @@ /** * Simple class that holds an instance of {@link ReactInstanceManager}. This can be used in your * {@link Application class} (see {@link ReactApplication}), or as a static field. + * + * @deprecated This class will be replaced by com.facebook.react.ReactHost in the New Architecture. */ -@DeprecatedInNewArchitecture( - message = - "This class will be replaced by com.facebook.react.ReactHost in the new architecture of" - + " React Native.") +@Deprecated @LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR) +@Nullsafe(Nullsafe.Mode.LOCAL) public abstract class ReactNativeHost { static { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.kt index 2ccc7a0edd43e6..732fe6deedd240 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.kt @@ -10,7 +10,6 @@ package com.facebook.react import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.UIManager -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture import com.facebook.react.common.annotations.StableReactNativeAPI import com.facebook.react.uimanager.ViewManager @@ -34,8 +33,9 @@ public interface ReactPackage { * @return list of native modules to register with the newly created catalyst instance This method * is deprecated in the new Architecture of React Native. */ - @DeprecatedInNewArchitecture(message = "Migrate to BaseReactPackage and implement getModule") - public fun createNativeModules(reactContext: ReactApplicationContext): List + @Deprecated(message = "Migrate to [BaseReactPackage] and implement [getModule] instead.") + public fun createNativeModules(reactContext: ReactApplicationContext): List = + emptyList() /** @return a list of view managers that should be registered with [UIManager] */ public fun createViewManagers( diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.kt index 1ade7b5d98aa11..28a3c0acca3416 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.kt @@ -28,6 +28,7 @@ internal object ReactPackageHelper { FLog.d( ReactConstants.TAG, "${reactPackage.javaClass.simpleName} is not a LazyReactPackage, falling back to old version.") + @Suppress("DEPRECATION") val nativeModules = reactPackage.createNativeModules(reactApplicationContext) return Iterable { object : Iterator { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.kt index 28e3bc0772b562..d13a565d6e0b6e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactPackageTurboModuleManagerDelegate.kt @@ -83,6 +83,7 @@ public abstract class ReactPackageTurboModuleManagerDelegate : TurboModuleManage if (shouldSupportLegacyPackages()) { // TODO(T145105887): Output warnings that ReactPackage was used + @Suppress("DEPRECATION") val nativeModules = reactPackage.createNativeModules(reactApplicationContext) val moduleMap: MutableMap = mutableMapOf() @@ -94,6 +95,7 @@ public abstract class ReactPackageTurboModuleManagerDelegate : TurboModuleManage val moduleName = reactModule?.name ?: module.name + @Suppress("DEPRECATION") val moduleInfo: ReactModuleInfo = if (reactModule != null) ReactModuleInfo( diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java index 3fec048a7705dd..ca7baa18081300 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java @@ -16,7 +16,6 @@ import com.facebook.infer.annotation.ThreadConfined; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.common.ReactConstants; -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.common.annotations.StableReactNativeAPI; import com.facebook.react.common.build.ReactBuildConfig; import java.util.Map; @@ -72,7 +71,6 @@ public BaseJavaModule(@Nullable ReactApplicationContext reactContext) { /** * @return a map of constants this module exports to JS. Supports JSON types. */ - @DeprecatedInNewArchitecture() public @Nullable Map getConstants() { return null; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BridgeReactContext.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BridgeReactContext.java index 88ea2110858de0..a8b3e7ceae60fa 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BridgeReactContext.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/BridgeReactContext.java @@ -14,11 +14,11 @@ import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; +import com.facebook.infer.annotation.Nullsafe; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.queue.ReactQueueConfiguration; import com.facebook.react.common.ReactConstants; -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.common.annotations.FrameworkAPI; import com.facebook.react.common.annotations.UnstableReactNativeAPI; import com.facebook.react.common.annotations.VisibleForTesting; @@ -27,16 +27,21 @@ import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger; import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder; import java.util.Collection; +import java.util.Objects; /** * This is the bridge-specific concrete subclass of ReactContext. ReactContext has many methods that * delegate to the react instance. This subclass implements those methods, by delegating to the * CatalystInstance. If you need to create a ReactContext within an "bridge context", please create * BridgeReactContext. + * + * @deprecated This class is deprecated in the New Architecture and will be replaced by {@link + * com.facebook.react.runtime.BridgelessReactContext} */ -@DeprecatedInNewArchitecture @VisibleForTesting @LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR) +@Deprecated +@Nullsafe(Nullsafe.Mode.LOCAL) public class BridgeReactContext extends ReactApplicationContext { static { LegacyArchitectureLogger.assertLegacyArchitecture( @@ -119,6 +124,7 @@ public boolean hasNativeModule(Class nativeModuleInt if (mCatalystInstance == null) { raiseCatalystInstanceMissingException(); } + Assertions.assertNotNull(mCatalystInstance); return mCatalystInstance.hasNativeModule(nativeModuleInterface); } @@ -127,6 +133,7 @@ public Collection getNativeModules() { if (mCatalystInstance == null) { raiseCatalystInstanceMissingException(); } + Assertions.assertNotNull(mCatalystInstance); return mCatalystInstance.getNativeModules(); } @@ -139,6 +146,7 @@ public T getNativeModule(Class nativeModuleInterface if (mCatalystInstance == null) { raiseCatalystInstanceMissingException(); } + Assertions.assertNotNull(mCatalystInstance); return mCatalystInstance.getNativeModule(nativeModuleInterface); } @@ -147,6 +155,7 @@ public T getNativeModule(Class nativeModuleInterface if (mCatalystInstance == null) { raiseCatalystInstanceMissingException(); } + Assertions.assertNotNull(mCatalystInstance); return mCatalystInstance.getNativeModule(moduleName); } @@ -210,8 +219,7 @@ public void destroy() { @Override public void handleException(Exception e) { boolean catalystInstanceVariableExists = mCatalystInstance != null; - boolean isCatalystInstanceAlive = - catalystInstanceVariableExists && !mCatalystInstance.isDestroyed(); + boolean isCatalystInstanceAlive = mCatalystInstance != null && !mCatalystInstance.isDestroyed(); boolean hasExceptionHandler = getJSExceptionHandler() != null; if (isCatalystInstanceAlive && hasExceptionHandler) { @@ -268,18 +276,19 @@ public CallInvokerHolder getJSCallInvokerHolder() { return null; } - @DeprecatedInNewArchitecture( - message = - "This method will be deprecated later as part of Stable APIs with bridge removal and not" - + " encouraged usage.") /** * Get the UIManager for Fabric from the CatalystInstance. * * @return The UIManager when CatalystInstance is active. + * @deprecated Do not use this method. Instead use {@link + * com.facebook.react.uimanager.UIManagerHelper} method {@code getUIManager} to get the + * UIManager instance from the current ReactContext. */ @Override + @Deprecated public @Nullable UIManager getFabricUIManager() { - return mCatalystInstance.getFabricUIManager(); + //noinspection deprecation + return Objects.requireNonNull(mCatalystInstance).getFabricUIManager(); } /** diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.kt index 944d56892ad9c7..b0ee31db64c65a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.kt @@ -32,6 +32,8 @@ protected constructor( // do nothing } + @Deprecated( + "The method canOverrideExistingModule is not used in the New Architecture and will be removed in a future release.") override fun canOverrideExistingModule(): Boolean = false override fun invalidate() { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt index d6e12cc369f74d..0e35427ebcf03c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt @@ -53,6 +53,7 @@ public class ModuleHolder { public constructor(nativeModule: NativeModule) { name = nativeModule.name + @Suppress("DEPRECATION") reactModuleInfo = ReactModuleInfo( nativeModule.name, diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java index 65d1a01a8f0983..6b87da715383fe 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java @@ -9,7 +9,6 @@ import com.facebook.infer.annotation.Nullsafe; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture; import com.facebook.react.common.annotations.StableReactNativeAPI; import javax.annotation.Nonnull; @@ -50,8 +49,11 @@ public interface NativeModule { * of a different package (such as the core one). Trying to override without returning true from * this method is considered an error and will throw an exception during initialization. By * default all modules return false. + * + * @deprecated The method canOverrideExistingModule is not used in the New Architecture and will + * be removed in a future release. */ - @DeprecatedInNewArchitecture() + @Deprecated default boolean canOverrideExistingModule() { return false; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/annotations/DeprecatedInNewArchitecture.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/annotations/DeprecatedInNewArchitecture.kt deleted file mode 100644 index 393ac8ade4291b..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/annotations/DeprecatedInNewArchitecture.kt +++ /dev/null @@ -1,16 +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.common.annotations - -/** - * Annotates a method or class that will be deprecated once the NewArchitecture is fully released in - * OSS. - */ -@Retention(AnnotationRetention.SOURCE) -@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) -internal annotation class DeprecatedInNewArchitecture(val message: String = "") diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHost.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHost.kt index 11b2814c48bb55..66b1519c16521c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHost.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactHost.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.defaults import android.content.Context 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 8a98a43c91fcea..c36a9be0952104 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 @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.defaults import android.app.Application diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.kt index c153eda77334df..0d94958392de2d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.kt @@ -53,7 +53,7 @@ public class BlobProvider : ContentProvider() { var blobModule: BlobModule? = null val context = context?.applicationContext if (context is ReactApplication) { - val host = (context as ReactApplication).reactNativeHost + @Suppress("DEPRECATION") val host = (context as ReactApplication).reactNativeHost val reactContext = host.reactInstanceManager.currentReactContext ?: throw RuntimeException("No ReactContext associated with BlobProvider") diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.kt index d61f559e8a76b1..d0fac3071cfa0a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.kt @@ -10,7 +10,6 @@ package com.facebook.react.uimanager import android.view.View import com.facebook.common.logging.FLog import com.facebook.react.bridge.ReadableArray -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture import com.facebook.react.uimanager.ViewManagersPropertyCache.PropSetter import java.util.HashMap @@ -70,8 +69,8 @@ public object ViewManagerPropertyUpdater { } } - @DeprecatedInNewArchitecture @JvmStatic + @Deprecated("Use ViewManager#updateProperties to update a view's properties") public fun > updateProps(node: T, props: ReactStylesDiffMap) { val setter = findNodeSetter(node.javaClass) val iterator = props.backingMap.entryIterator diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.kt index f0c97b73222253..bd2464d010f905 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.kt @@ -8,12 +8,10 @@ package com.facebook.react.uimanager.common import androidx.annotation.IntDef -import com.facebook.react.common.annotations.DeprecatedInNewArchitecture @Retention(AnnotationRetention.SOURCE) @Suppress("DEPRECATION") @IntDef(UIManagerType.DEFAULT, UIManagerType.LEGACY, UIManagerType.FABRIC) -@DeprecatedInNewArchitecture public annotation class UIManagerType { public companion object { @Deprecated( diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt index 3403b6d8f278ec..38033aae0a543e 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/FabricUIManagerTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.fabric import com.facebook.react.bridge.BridgeReactContext diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/MountingManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/MountingManagerTest.kt index 4f009cb1adf21f..473e2eb4c0bad2 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/MountingManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/MountingManagerTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.fabric import com.facebook.react.ReactRootView diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.kt index e3488696fcc429..2e7ccf0b10d9d9 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.modules.clipboard import android.annotation.SuppressLint diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/deviceinfo/DeviceInfoModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/deviceinfo/DeviceInfoModuleTest.kt index c908d39aae38a6..66c90ef5e12cba 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/deviceinfo/DeviceInfoModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/deviceinfo/DeviceInfoModuleTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.modules.deviceinfo import com.facebook.react.bridge.BridgeReactContext diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt index 39aae4363332df..f538b5475ee44a 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.uimanager import android.view.View.OnFocusChangeListener diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.kt index e2b2f5865edc67..ac8639e22045a2 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.uimanager import android.view.View diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.kt index 47d10eb489a624..b02a717e09e70d 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.uimanager import com.facebook.react.bridge.BridgeReactContext diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.kt index e1bf44598acae1..6c43884936a905 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.kt @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.uimanager import android.view.View 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 dddd3312063df5..05ca30df409d12 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 @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +@file:Suppress("DEPRECATION") + package com.facebook.react.uiapp import android.app.Application @@ -37,6 +39,9 @@ import com.facebook.react.views.view.setEdgeToEdgeFeatureFlagOn import com.facebook.soloader.SoLoader internal class RNTesterApplication : Application(), ReactApplication { + @Deprecated( + "You should not use ReactNativeHost directly in the New Architecture. Use ReactHost instead.", + replaceWith = ReplaceWith("reactHost")) override val reactNativeHost: ReactNativeHost by lazy { object : DefaultReactNativeHost(this) { public override fun getJSMainModuleName(): String = BuildConfig.JS_MAIN_MODULE_NAME @@ -86,10 +91,6 @@ internal class RNTesterApplication : Application(), ReactApplication { } }, object : ReactPackage, ViewManagerOnDemandReactPackage { - override fun createNativeModules( - reactContext: ReactApplicationContext - ): List = emptyList() - override fun getViewManagerNames(reactContext: ReactApplicationContext) = listOf("RNTMyNativeView", "RNTMyLegacyNativeView", "RNTReportFullyDrawnView") From ead669ade31ee703c407f96c0ce98d8f2991bdc8 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Jul 2025 11:04:01 -0700 Subject: [PATCH 0013/1383] Remove unused ReactCommon/TurboModuleUtils functions #deepCopyJSIObject and #deepCopyJSIArray (#52443) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52443 Changelog: [General][Breaking] Remove unused ReactCommon/TurboModuleUtils functions #deepCopyJSIObject and #deepCopyJSIArray Those are not used anymore Reviewed By: cortinico Differential Revision: D77771186 fbshipit-source-id: e1f5e34238567241b4204d58ff85fd9067e321df --- .../core/ReactCommon/TurboModuleUtils.cpp | 53 ------------------- .../core/ReactCommon/TurboModuleUtils.h | 10 ++-- 2 files changed, 3 insertions(+), 60 deletions(-) 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 2a7bbb51429603..c3915063a6a966 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp @@ -9,59 +9,6 @@ namespace facebook::react { -static jsi::Value deepCopyJSIValue(jsi::Runtime& rt, const jsi::Value& value) { - if (value.isNull()) { - return jsi::Value::null(); - } - - if (value.isBool()) { - return jsi::Value(value.getBool()); - } - - if (value.isNumber()) { - return jsi::Value(value.getNumber()); - } - - if (value.isString()) { - return value.getString(rt); - } - - if (value.isObject()) { - jsi::Object o = value.getObject(rt); - if (o.isArray(rt)) { - return deepCopyJSIArray(rt, o.getArray(rt)); - } - if (o.isFunction(rt)) { - return o.getFunction(rt); - } - return deepCopyJSIObject(rt, o); - } - - return jsi::Value::undefined(); -} - -jsi::Object deepCopyJSIObject(jsi::Runtime& rt, const jsi::Object& obj) { - jsi::Object copy(rt); - jsi::Array propertyNames = obj.getPropertyNames(rt); - size_t size = propertyNames.size(rt); - for (size_t i = 0; i < size; i++) { - jsi::String name = propertyNames.getValueAtIndex(rt, i).getString(rt); - jsi::Value value = obj.getProperty(rt, name); - copy.setProperty(rt, name, deepCopyJSIValue(rt, value)); - } - return copy; -} - -jsi::Array deepCopyJSIArray(jsi::Runtime& rt, const jsi::Array& arr) { - size_t size = arr.size(rt); - jsi::Array copy(rt, size); - for (size_t i = 0; i < size; i++) { - copy.setValueAtIndex( - rt, i, deepCopyJSIValue(rt, arr.getValueAtIndex(rt, i))); - } - return copy; -} - Promise::Promise(jsi::Runtime& rt, jsi::Function resolve, jsi::Function reject) : LongLivedObject(rt), resolve_(std::move(resolve)), 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 005fc1504ef6c5..704116f97eb386 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h @@ -7,18 +7,14 @@ #pragma once -#include -#include - #include -#include #include +#include +#include +#include namespace facebook::react { -jsi::Object deepCopyJSIObject(jsi::Runtime& rt, const jsi::Object& obj); -jsi::Array deepCopyJSIArray(jsi::Runtime& rt, const jsi::Array& arr); - struct Promise : public LongLivedObject { Promise(jsi::Runtime& rt, jsi::Function resolve, jsi::Function reject); From 3bf5cb3d0e7d9d1749ef19a8392b9bbd3ec7ab7d Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Mon, 7 Jul 2025 11:29:01 -0700 Subject: [PATCH 0014/1383] Deprecate MessageQueueThreadPerfStats (#52470) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52470 These metrics are not actively consumed and are highly noisy. Changelog: [Android][Removed] Deprecated MessageQueueThreadPerfStats API and replaced with stub. Reviewed By: cortinico Differential Revision: D77867087 fbshipit-source-id: 8bf7423ad60cb3bb21a5dbe94771d5a71832633d --- .../ReactAndroid/api/ReactAndroid.api | 8 ++--- .../facebook/react/bridge/ReactContext.java | 10 ++---- .../react/bridge/queue/MessageQueueThread.kt | 7 ++-- .../bridge/queue/MessageQueueThreadImpl.kt | 35 +++---------------- .../queue/MessageQueueThreadPerfStats.kt | 1 + .../bridge/queue/MessageQueueThreadSpec.kt | 1 + 6 files changed, 17 insertions(+), 45 deletions(-) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index fc5b2b28b8ae28..2462978d66819a 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -1561,28 +1561,26 @@ public abstract interface class com/facebook/react/bridge/queue/MessageQueueThre public abstract fun assertIsOnThread ()V public abstract fun assertIsOnThread (Ljava/lang/String;)V public abstract fun callOnQueue (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; - public abstract fun getPerfStats ()Lcom/facebook/react/bridge/queue/MessageQueueThreadPerfStats; + public fun getPerfStats ()Lcom/facebook/react/bridge/queue/MessageQueueThreadPerfStats; public abstract fun isIdle ()Z public abstract fun isOnThread ()Z public abstract fun quitSynchronous ()V - public abstract fun resetPerfStats ()V + public fun resetPerfStats ()V public abstract fun runOnQueue (Ljava/lang/Runnable;)Z } public final class com/facebook/react/bridge/queue/MessageQueueThreadImpl : com/facebook/react/bridge/queue/MessageQueueThread { public static final field Companion Lcom/facebook/react/bridge/queue/MessageQueueThreadImpl$Companion; - public synthetic fun (Ljava/lang/String;Landroid/os/Looper;Lcom/facebook/react/bridge/queue/QueueThreadExceptionHandler;Lcom/facebook/react/bridge/queue/MessageQueueThreadPerfStats;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun (Ljava/lang/String;Landroid/os/Looper;Lcom/facebook/react/bridge/queue/QueueThreadExceptionHandler;Lkotlin/jvm/internal/DefaultConstructorMarker;)V public fun assertIsOnThread ()V public fun assertIsOnThread (Ljava/lang/String;)V public fun callOnQueue (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; public static final fun create (Lcom/facebook/react/bridge/queue/MessageQueueThreadSpec;Lcom/facebook/react/bridge/queue/QueueThreadExceptionHandler;)Lcom/facebook/react/bridge/queue/MessageQueueThreadImpl; public final fun getLooper ()Landroid/os/Looper; public final fun getName ()Ljava/lang/String; - public fun getPerfStats ()Lcom/facebook/react/bridge/queue/MessageQueueThreadPerfStats; public fun isIdle ()Z public fun isOnThread ()Z public fun quitSynchronous ()V - public fun resetPerfStats ()V public fun runOnQueue (Ljava/lang/Runnable;)Z } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java index ffa72480ac97aa..7a0655081a86cb 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java @@ -108,14 +108,8 @@ protected void initializeInteropModules() { mInteropModuleRegistry = new InteropModuleRegistry(); } - public void resetPerfStats() { - if (mNativeModulesMessageQueueThread != null) { - mNativeModulesMessageQueueThread.resetPerfStats(); - } - if (mJSMessageQueueThread != null) { - mJSMessageQueueThread.resetPerfStats(); - } - } + @Deprecated(since = "MessageQueueThread perf stats are no longer collected") + public void resetPerfStats() {} public void setJSExceptionHandler(@Nullable JSExceptionHandler jSExceptionHandler) { mJSExceptionHandler = jSExceptionHandler; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.kt index b2d7d93715639f..0597e1403f5d4a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.kt @@ -55,13 +55,16 @@ public interface MessageQueueThread { * Returns the perf counters taken when the framework was started. This method is intended to be * used for instrumentation purposes. */ - public fun getPerfStats(): MessageQueueThreadPerfStats? + @Deprecated("MessageQueueThread perf stats are no longer collected") + @Suppress("DEPRECATION") + public fun getPerfStats(): MessageQueueThreadPerfStats? = null /** * Resets the perf counters. This is useful if the RN threads are being re-used. This method is * intended to be used for instrumentation purposes. */ - public fun resetPerfStats() + @Deprecated("MessageQueueThread perf stats are no longer collected") + public fun resetPerfStats(): Unit = Unit /** * Resets the perf counters. This is useful if the RN threads are being re-used. This method is diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.kt index 79cabea3864403..ab0a0edc01f4b9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.kt @@ -9,8 +9,6 @@ package com.facebook.react.bridge.queue import android.os.Looper import android.os.Process -import android.os.SystemClock -import android.util.Pair import com.facebook.common.logging.FLog import com.facebook.proguard.annotations.DoNotStripAny import com.facebook.react.bridge.AssertionException @@ -29,7 +27,6 @@ private constructor( public val name: String, public val looper: Looper, exceptionHandler: QueueThreadExceptionHandler, - private val stats: MessageQueueThreadPerfStats? = null ) : MessageQueueThread { private val handler = MessageQueueThreadHandler(looper, exceptionHandler) private val assertionErrorMessage = "Expected to be called from the '$name' thread!" @@ -105,27 +102,9 @@ private constructor( } } - override fun getPerfStats(): MessageQueueThreadPerfStats? = stats - - override fun resetPerfStats() { - assignToPerfStats(stats, -1, -1) - runOnQueue { - val wallTime = SystemClock.uptimeMillis() - val cpuTime = SystemClock.currentThreadTimeMillis() - assignToPerfStats(stats, wallTime, cpuTime) - } - } - public override fun isIdle(): Boolean = looper.queue.isIdle public companion object { - private fun assignToPerfStats(stats: MessageQueueThreadPerfStats?, wall: Long, cpu: Long) { - stats?.let { s -> - s.wallTime = wall - s.cpuTime = cpu - } - } - @JvmStatic @Throws(RuntimeException::class) public fun create( @@ -160,27 +139,23 @@ private constructor( stackSize: Long, exceptionHandler: QueueThreadExceptionHandler ): MessageQueueThreadImpl { - val dataFuture = SimpleSettableFuture>() + val looperFuture = SimpleSettableFuture() val bgThread = Thread( null, { Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY) Looper.prepare() - val stats = MessageQueueThreadPerfStats() - val wallTime = SystemClock.uptimeMillis() - val cpuTime = SystemClock.currentThreadTimeMillis() - assignToPerfStats(stats, wallTime, cpuTime) - dataFuture.set(Pair(Looper.myLooper(), stats)) + looperFuture.set(Looper.myLooper()) Looper.loop() }, "mqt_$name", stackSize) bgThread.start() - val pair = dataFuture.getOrThrow() - val looper = pair?.first ?: throw RuntimeException("Looper not found for thread") - return MessageQueueThreadImpl(name, looper, exceptionHandler, pair.second) + val looper = + looperFuture.getOrThrow() ?: throw RuntimeException("Looper not found for thread") + return MessageQueueThreadImpl(name, looper, exceptionHandler) } } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.kt index b56c3718a41082..96c3437f566614 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.kt @@ -8,6 +8,7 @@ package com.facebook.react.bridge.queue /** This class holds perf counters' values at the beginning of an RN startup. */ +@Deprecated("MessageQueueThread perf stats are no longer collected") public class MessageQueueThreadPerfStats { @JvmField public var wallTime: Long = 0 @JvmField public var cpuTime: Long = 0 diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.kt index 6186f1c8e30778..1bf72565d3664c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.kt @@ -26,6 +26,7 @@ private constructor( public const val DEFAULT_STACK_SIZE_BYTES: Long = 0 @JvmStatic + @Deprecated("Use newBackgroundThreadSpec") public fun newUIBackgroundTreadSpec(name: String): MessageQueueThreadSpec = MessageQueueThreadSpec(ThreadType.NEW_BACKGROUND, name) From abfb9cbd409845bc8ec06d68c4a3d267da956526 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Jul 2025 14:50:58 -0700 Subject: [PATCH 0015/1383] Update outdated ReactNativeCPP.api (#52475) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52475 Changelog: [Internal] Reviewed By: philIip Differential Revision: D77887914 fbshipit-source-id: 1431205eff716bac86610750103df729553d22b9 --- private/cxx-public-api/ReactNativeCPP.api | 1365 ++++++++++++++++----- 1 file changed, 1076 insertions(+), 289 deletions(-) diff --git a/private/cxx-public-api/ReactNativeCPP.api b/private/cxx-public-api/ReactNativeCPP.api index d52206efcce912..cd8febac1a332a 100644 --- a/private/cxx-public-api/ReactNativeCPP.api +++ b/private/cxx-public-api/ReactNativeCPP.api @@ -2,7 +2,7 @@ * This file is generated, do not edit. * @generated * - * @file_count 1202 + * @file_count 1206 * @generate-command: node tools/api/public-api.js */ @@ -968,19 +968,12 @@ static inline RCTResizeMode RCTResizeModeFromUIViewContentMode(UIViewContentMode switch (mode) { case UIViewContentModeScaleToFill: return RCTResizeModeStretch; - break; case UIViewContentModeScaleAspectFit: return RCTResizeModeContain; - break; case UIViewContentModeScaleAspectFill: return RCTResizeModeCover; - break; - case UIViewContentModeCenter: - return RCTResizeModeCenter; - break; case UIViewContentModeTopLeft: return RCTResizeModeNone; - break; case UIViewContentModeRedraw: case UIViewContentModeTop: case UIViewContentModeBottom: @@ -990,6 +983,9 @@ static inline RCTResizeMode RCTResizeModeFromUIViewContentMode(UIViewContentMode case UIViewContentModeBottomLeft: case UIViewContentModeBottomRight: return RCTResizeModeRepeat; + case UIViewContentModeCenter: + default: + return RCTResizeModeCenter; } }; @interface RCTConvert (RCTResizeMode) @@ -1385,13 +1381,26 @@ RCT_EXTERN void RCTSetCustomNSURLSessionConfigurationProvider(NSURLSessionConfig + (void)reportRequestStart:(NSNumber *)requestId request:(NSURLRequest *)request encodedDataLength:(int)encodedDataLength; ++ (void)reportConnectionTiming:(NSNumber *)requestId request:(NSURLRequest *)request; + (void)reportResponseStart:(NSNumber *)requestId response:(NSURLResponse *)response statusCode:(int)statusCode headers:(NSDictionary *)headers; ++ (void)reportDataReceived:(NSNumber *)requestId data:(NSData *)data; + (void)reportResponseEnd:(NSNumber *)requestId encodedDataLength:(int)encodedDataLength; ++ (void)reportRequestFailed:(NSNumber *)requestId cancelled:(BOOL)cancelled; ++ (void)maybeStoreResponseBody:(NSNumber *)requestId data:(NSData *)data base64Encoded:(bool)base64Encoded; ++ (void)maybeStoreResponseBodyIncremental:(NSNumber *)requestId data:(NSString *)data; @end +/// @src {packages/react-native/Libraries/Network/RCTNetworkConversions.h}: +NS_ASSUME_NONNULL_BEGIN +inline std::string_view RCTStringViewFromNSString(NSString *string) +{ + return std::string_view{string.UTF8String, string.length}; +} +NS_ASSUME_NONNULL_END + /// @src {packages/react-native/Libraries/Network/RCTNetworkPlugins.h}: #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" @@ -2259,12 +2268,13 @@ typedef NS_ENUM(NSInteger, RCTFunctionType) { static inline const char *RCTFunctionDescriptorFromType(RCTFunctionType type) { switch (type) { - case RCTFunctionTypeNormal: - return "async"; case RCTFunctionTypePromise: return "promise"; case RCTFunctionTypeSync: return "sync"; + case RCTFunctionTypeNormal: + default: + return "async"; } }; @protocol RCTBridgeMethod @@ -4228,6 +4238,16 @@ NS_ASSUME_NONNULL_BEGIN @end NS_ASSUME_NONNULL_END +/// @src {packages/react-native/React/Fabric/Mounting/ComponentViews/VirtualView/RCTVirtualViewComponentView.h}: +NS_ASSUME_NONNULL_BEGIN +@interface RCTVirtualViewComponentView : RCTViewComponentView ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder *)coder NS_UNAVAILABLE; +- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER; +@end +NS_ASSUME_NONNULL_END + /// @src {packages/react-native/React/Fabric/Mounting/RCTComponentViewClassDescriptor.h}: NS_ASSUME_NONNULL_BEGIN class RCTComponentViewClassDescriptor final { @@ -4787,6 +4807,12 @@ NS_ASSUME_NONNULL_BEGIN + (std::vector)getFixedColorStops: (const std::vector &)colorStops gradientLineLength:(CGFloat)gradientLineLength; ++ (std::pair)pointsForCAGradientLayerLinearGradient:(CGPoint)startPoint + endPoint:(CGPoint)endPoint + bounds:(CGSize)bounds; ++ (void)getColors:(NSMutableArray *)colors + andLocations:(NSMutableArray *)locations + fromColorStops:(const std::vector &)colorStops; @end NS_ASSUME_NONNULL_END @@ -5372,6 +5398,7 @@ NS_ASSUME_NONNULL_END @property (nonatomic, assign, getter=isTransparent) BOOL transparent; @property (nonatomic, copy) RCTDirectEventBlock onShow; @property (nonatomic, assign) BOOL visible; +@property (nonatomic, assign) BOOL allowSwipeDismissal; @property (nonatomic, assign) BOOL statusBarTranslucent; @property (nonatomic, assign) BOOL hardwareAccelerated; @property (nonatomic, assign) BOOL animated; @@ -5826,11 +5853,9 @@ typedef struct { @end /// @src {packages/react-native/ReactAndroid/src/main/jni/first-party/fbgloginit/fb/glog_init.h}: -namespace facebook { -namespace gloginit { +namespace facebook::gloginit { void initialize(const char* tag = "ReactNativeJNI"); } -} // namespace facebook /// @src {packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/jni.h}: /// @dep {packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/real/jni.h} @@ -6474,16 +6499,16 @@ enum class FocusDirection { class FocusOrderingHelper { public: static void traverseAndUpdateNextFocusableElement( - const ShadowNode::Shared& parentShadowNode, - const ShadowNode::Shared& focusedShadowNode, - const ShadowNode::Shared& currNode, + const std::shared_ptr& parentShadowNode, + const std::shared_ptr& focusedShadowNode, + const std::shared_ptr& currNode, FocusDirection focusDirection, const UIManager& uimanager, Rect sourceRect, std::optional& nextRect, - ShadowNode::Shared& nextNode); - static ShadowNode::Shared findShadowNodeByTagRecursively( - const ShadowNode::Shared& parentShadowNode, + std::shared_ptr& nextNode); + static std::shared_ptr findShadowNodeByTagRecursively( + const std::shared_ptr& parentShadowNode, Tag tag); static std::optional resolveFocusDirection(int direction); }; @@ -6604,6 +6629,8 @@ class JReactNativeFeatureFlagsCxxInterop facebook::jni::alias_ref); static bool cxxNativeAnimatedEnabled( facebook::jni::alias_ref); + static bool cxxNativeAnimatedRemoveJsSync( + facebook::jni::alias_ref); static bool disableMainQueueSyncDispatchIOS( facebook::jni::alias_ref); static bool disableMountItemReorderingAndroid( @@ -6614,6 +6641,8 @@ class JReactNativeFeatureFlagsCxxInterop facebook::jni::alias_ref); static bool enableAccumulatedUpdatesInRawPropsAndroid( facebook::jni::alias_ref); + static bool enableAndroidTextMeasurementOptimizations( + facebook::jni::alias_ref); static bool enableBridgelessArchitecture( facebook::jni::alias_ref); static bool enableCppPropsIteratorSetter( @@ -6638,6 +6667,8 @@ class JReactNativeFeatureFlagsCxxInterop facebook::jni::alias_ref); static bool enableIOSViewClipToPaddingBox( facebook::jni::alias_ref); + static bool enableInteropViewManagerClassLookUpOptimizationIOS( + facebook::jni::alias_ref); static bool enableLayoutAnimationsOnAndroid( facebook::jni::alias_ref); static bool enableLayoutAnimationsOnIOS( @@ -6672,12 +6703,20 @@ class JReactNativeFeatureFlagsCxxInterop facebook::jni::alias_ref); static bool enableVirtualViewDebugFeatures( facebook::jni::alias_ref); + static bool enableVirtualViewRenderState( + facebook::jni::alias_ref); + static bool enableVirtualViewWindowFocusDetection( + facebook::jni::alias_ref); static bool fixMappingOfEventPrioritiesBetweenFabricAndReact( facebook::jni::alias_ref); static bool fuseboxEnabledRelease( facebook::jni::alias_ref); static bool fuseboxNetworkInspectionEnabled( facebook::jni::alias_ref); + static bool hideOffscreenVirtualViewsOnIOS( + facebook::jni::alias_ref); + static double preparedTextCacheSize( + facebook::jni::alias_ref); static bool traceTurboModulePromiseRejectionsOnAndroid( facebook::jni::alias_ref); static bool updateRuntimeShadowNodeReferencesOnCommit( @@ -6747,9 +6786,7 @@ class HermesMemoryDumper : public jni::JavaClass { } // namespace facebook /// @src {packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesSamplingProfiler.h}: -namespace facebook { -namespace jsi { -namespace jni { +namespace facebook::jsi::jni { namespace jni = ::facebook::jni; class HermesSamplingProfiler : public jni::JavaClass { public: @@ -6762,9 +6799,7 @@ class HermesSamplingProfiler : public jni::JavaClass { std::string filename); static void registerNatives(); }; -} // namespace jni -} // namespace jsi -} // namespace facebook +} // namespace facebook::jsi::jni /// @src {packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.h}: /// @dep {packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h} @@ -8255,7 +8290,6 @@ class UIConstantsProviderBinding /// @src {packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h}: /// @dep {packages/react-native/ReactCommon/callinvoker/ReactCommon/SchedulerPriority.h} - namespace facebook::jsi { } namespace facebook::react { @@ -8273,7 +8307,7 @@ class CallInvoker { virtual void invokeSync(std::function&& func) { invokeSync([func](jsi::Runtime&) { func(); }); } - virtual ~CallInvoker() {} + virtual ~CallInvoker() = default; }; using NativeMethodCallFunc = std::function; class NativeMethodCallInvoker { @@ -8284,7 +8318,7 @@ class NativeMethodCallInvoker { virtual void invokeSync( const std::string& methodName, NativeMethodCallFunc&& func) = 0; - virtual ~NativeMethodCallInvoker() {} + virtual ~NativeMethodCallInvoker() = default; }; } // namespace facebook::react @@ -8302,9 +8336,7 @@ enum class SchedulerPriority : int { /// @src {packages/react-native/ReactCommon/cxxreact/CxxModule.h}: namespace facebook::react { } -namespace facebook { -namespace xplat { -namespace module { +namespace facebook::xplat::module { class CxxModule { class AsyncTagType {}; class SyncTagType {}; @@ -8429,7 +8461,7 @@ class CxxModule { isPromise(false), syncFunc(std::move(afunc)) {} }; - virtual ~CxxModule() {} + virtual ~CxxModule() = default; virtual std::string getName() = 0; virtual auto getConstants() -> std::map { return {}; @@ -8442,9 +8474,7 @@ class CxxModule { return instance_; } }; -} // namespace module -} // namespace xplat -} // namespace facebook +} // namespace facebook::xplat::module /// @src {packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h}: namespace facebook::react { @@ -8508,7 +8538,7 @@ namespace folly { } namespace facebook::react { struct InstanceCallback { - virtual ~InstanceCallback() {} + virtual ~InstanceCallback() = default; virtual void onBatchComplete() {} virtual void incrementPendingJSCalls() {} virtual void decrementPendingJSCalls() {} @@ -8583,7 +8613,7 @@ class JSBigString { JSBigString() = default; JSBigString(const JSBigString&) = delete; JSBigString& operator=(const JSBigString&) = delete; - virtual ~JSBigString() {} + virtual ~JSBigString() = default; virtual bool isAscii() const = 0; virtual const char* c_str() const = 0; virtual size_t size() const = 0; @@ -8674,7 +8704,7 @@ __attribute__((visibility("default"))) bool isHermesBytecodeBundle( namespace facebook::react { class ExecutorDelegate { public: - virtual ~ExecutorDelegate() {} + virtual ~ExecutorDelegate() = default; virtual std::shared_ptr getModuleRegistry() = 0; virtual void callNativeModules( JSExecutor& executor, @@ -8691,7 +8721,7 @@ class JSExecutorFactory { virtual std::unique_ptr createJSExecutor( std::shared_ptr delegate, std::shared_ptr jsQueue) = 0; - virtual ~JSExecutorFactory() {} + virtual ~JSExecutorFactory() = default; }; class __attribute__((visibility("default"))) JSExecutor { public: @@ -8788,7 +8818,7 @@ class JSModulesUnbundle { std::string code; }; JSModulesUnbundle() {} - virtual ~JSModulesUnbundle() {} + virtual ~JSModulesUnbundle() = default; virtual Module getModule(uint32_t moduleId) const = 0; }; } // namespace facebook::react @@ -8890,8 +8920,7 @@ typename detail::is_dynamic::type& jsArgAsObject(T&& args, size_t n) { } // namespace facebook /// @src {packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h}: -namespace facebook { -namespace xplat { +namespace facebook::xplat { class JsArgumentException : public std::logic_error { public: JsArgumentException(const std::string& msg) : std::logic_error(msg) {} @@ -8941,14 +8970,13 @@ inline double jsArgAsDouble(const folly::dynamic& args, size_t n) { inline std::string jsArgAsString(const folly::dynamic& args, size_t n) { return jsArgN(args, n, &folly::dynamic::asString); } -} // namespace xplat -} // namespace facebook +} // namespace facebook::xplat /// @src {packages/react-native/ReactCommon/cxxreact/MessageQueueThread.h}: namespace facebook::react { class MessageQueueThread { public: - virtual ~MessageQueueThread() {} + virtual ~MessageQueueThread() = default; virtual void runOnQueue(std::function&&) = 0; virtual void runOnQueueSync(std::function&&) = 0; virtual void quitSynchronous() = 0; @@ -9046,7 +9074,7 @@ struct MethodDescriptor { using MethodCallResult = std::optional; class NativeModule { public: - virtual ~NativeModule() {} + virtual ~NativeModule() = default; virtual std::string getName() = 0; virtual std::string getSyncMethodName(unsigned int methodId) = 0; virtual std::vector getMethods() = 0; @@ -9120,13 +9148,12 @@ class __attribute__((visibility("default"))) RAMBundleRegistry { RAMBundleRegistry& operator=(RAMBundleRegistry&&) = default; void registerBundle(uint32_t bundleId, std::string bundlePath); JSModulesUnbundle::Module getModule(uint32_t bundleId, uint32_t moduleId); - virtual ~RAMBundleRegistry() {}; + virtual ~RAMBundleRegistry() = default; }; } // namespace facebook::react /// @src {packages/react-native/ReactCommon/cxxreact/ReactMarker.h}: -namespace facebook::react { -namespace ReactMarker { +namespace facebook::react::ReactMarker { enum ReactMarkerId { APP_STARTUP_START, APP_STARTUP_STOP, @@ -9184,8 +9211,7 @@ class __attribute__((visibility("default"))) StartupLogger { extern __attribute__((visibility("default"))) void logMarkerDone( const ReactMarkerId markerId, double markerTime); -} // namespace ReactMarker -} // namespace facebook::react +} // namespace facebook::react::ReactMarker /// @src {packages/react-native/ReactCommon/cxxreact/ReactNativeVersion.h}: namespace facebook::react { @@ -9217,9 +9243,7 @@ struct RecoverableError : public std::exception { } // namespace facebook::react /// @src {packages/react-native/ReactCommon/cxxreact/SharedProxyCxxModule.h}: -namespace facebook { -namespace xplat { -namespace module { +namespace facebook::xplat::module { class SharedProxyCxxModule : public CxxModule { public: explicit SharedProxyCxxModule(std::shared_ptr shared) @@ -9234,9 +9258,7 @@ class SharedProxyCxxModule : public CxxModule { return shared_->getMethods(); } }; -} // namespace module -} // namespace xplat -} // namespace facebook +} // namespace facebook::xplat::module /// @src {packages/react-native/ReactCommon/cxxreact/SystraceSection.h}: /// @dep {packages/react-native/ReactCommon/cxxreact/TraceSection.h} @@ -9380,11 +9402,9 @@ class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { /// @src {packages/react-native/ReactCommon/jsc/JSCRuntime.h}: -namespace facebook { -namespace jsc { +namespace facebook::jsc { std::unique_ptr makeJSCRuntime(); } -} // namespace facebook /// @src {packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h}: namespace facebook::react { @@ -12289,6 +12309,16 @@ struct IOReadResult { return obj; } }; +struct GetResponseBodyResult { + std::string body; + bool base64Encoded; + folly::dynamic toDynamic() const { + folly::dynamic params = folly::dynamic::object; + params["body"] = body; + params["base64Encoded"] = base64Encoded; + return params; + } +}; class NetworkRequestListener { public: NetworkRequestListener() = default; @@ -12333,6 +12363,7 @@ class NetworkIOAgent { LoadNetworkResourceDelegate& delegate); void handleIoRead(const cdp::PreparsedRequest& req); void handleIoClose(const cdp::PreparsedRequest& req); + void handleGetResponseBody(const cdp::PreparsedRequest& req); }; } // namespace facebook::react::jsinspector_modern namespace facebook::react::jsinspector_modern { @@ -12647,6 +12678,16 @@ struct IOReadResult { return obj; } }; +struct GetResponseBodyResult { + std::string body; + bool base64Encoded; + folly::dynamic toDynamic() const { + folly::dynamic params = folly::dynamic::object; + params["body"] = body; + params["base64Encoded"] = base64Encoded; + return params; + } +}; class NetworkRequestListener { public: NetworkRequestListener() = default; @@ -12691,6 +12732,7 @@ class NetworkIOAgent { LoadNetworkResourceDelegate& delegate); void handleIoRead(const cdp::PreparsedRequest& req); void handleIoClose(const cdp::PreparsedRequest& req); + void handleGetResponseBody(const cdp::PreparsedRequest& req); }; } // namespace facebook::react::jsinspector_modern namespace facebook::react::jsinspector_modern { @@ -13327,6 +13369,16 @@ struct IOReadResult { return obj; } }; +struct GetResponseBodyResult { + std::string body; + bool base64Encoded; + folly::dynamic toDynamic() const { + folly::dynamic params = folly::dynamic::object; + params["body"] = body; + params["base64Encoded"] = base64Encoded; + return params; + } +}; class NetworkRequestListener { public: NetworkRequestListener() = default; @@ -13371,6 +13423,7 @@ class NetworkIOAgent { LoadNetworkResourceDelegate& delegate); void handleIoRead(const cdp::PreparsedRequest& req); void handleIoClose(const cdp::PreparsedRequest& req); + void handleGetResponseBody(const cdp::PreparsedRequest& req); }; } // namespace facebook::react::jsinspector_modern @@ -14054,6 +14107,24 @@ std::string jsonRequest( std::optional params = std::nullopt); } // namespace facebook::react::jsinspector_modern::cdp +/// @src {packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h}: +namespace facebook::react::jsinspector_modern { +constexpr size_t REQUEST_BUFFER_MAX_SIZE_BYTES = 100 * 1024 * 1024; +class BoundedRequestBuffer { + public: + struct ResponseBody { + std::string data; + bool base64Encoded; + }; + bool put( + const std::string& requestId, + std::string_view data, + bool base64Encoded) noexcept; + std::shared_ptr get(const std::string& requestId) const; + void clear(); +}; +} // namespace facebook::react::jsinspector_modern + /// @src {packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h}: /// @dep {packages/react-native/ReactCommon/jsinspector-modern/network/NetworkTypes.h} namespace facebook::react::jsinspector_modern::cdp::network { @@ -14077,6 +14148,9 @@ struct Response { int encodedDataLength); folly::dynamic toDynamic() const; }; +struct ConnectTiming { + double requestTime; +}; struct RequestWillBeSentParams { std::string requestId; std::string loaderId; @@ -14089,6 +14163,12 @@ struct RequestWillBeSentParams { std::optional redirectResponse; folly::dynamic toDynamic() const; }; +struct RequestWillBeSentExtraInfoParams { + std::string requestId; + Headers headers; + ConnectTiming connectTiming; + folly::dynamic toDynamic() const; +}; struct ResponseReceivedParams { std::string requestId; std::string loaderId; @@ -14098,6 +14178,21 @@ struct ResponseReceivedParams { bool hasExtraInfo; folly::dynamic toDynamic() const; }; +struct DataReceivedParams { + std::string requestId; + double timestamp; + int dataLength; + int encodedDataLength; + folly::dynamic toDynamic() const; +}; +struct LoadingFailedParams { + std::string requestId; + double timestamp; + std::string type; + std::string errorText; + bool canceled; + folly::dynamic toDynamic() const; +}; struct LoadingFinishedParams { std::string requestId; double timestamp; @@ -14115,6 +14210,7 @@ std::string mimeTypeFromHeaders(const Headers& headers); } // namespace facebook::react::jsinspector_modern /// @src {packages/react-native/ReactCommon/jsinspector-modern/network/NetworkReporter.h}: +/// @dep {packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h} /// @dep {packages/react-native/ReactCommon/jsinspector-modern/network/NetworkTypes.h} namespace facebook::react::jsinspector_modern { using FrontendChannel = std::function; @@ -14133,25 +14229,43 @@ class NetworkReporter { void setFrontendChannel(FrontendChannel frontendChannel); bool enableDebugging(); bool disableDebugging(); + inline bool isDebuggingEnabled() const { + return debuggingEnabled_.load(std::memory_order_acquire); + } void reportRequestStart( const std::string& requestId, const RequestInfo& requestInfo, int encodedDataLength, const std::optional& redirectResponse); - void reportConnectionTiming(const std::string& requestId); - void reportRequestFailed(const std::string& requestId) const; + void reportConnectionTiming( + const std::string& requestId, + const std::optional& headers); void reportResponseStart( const std::string& requestId, const ResponseInfo& responseInfo, int encodedDataLength); - void reportDataReceived(const std::string& requestId); + void reportDataReceived( + const std::string& requestId, + int dataLength, + const std::optional& encodedDataLength); void reportResponseEnd(const std::string& requestId, int encodedDataLength); + void reportRequestFailed(const std::string& requestId, bool cancelled) const; + void storeResponseBody( + const std::string& requestId, + std::string_view body, + bool base64Encoded); + std::optional> getResponseBody( + const std::string& requestId); }; inline bool isDebuggingEnabledNoSync() const { return debuggingEnabled_.load(std::memory_order_relaxed); } + FrontendChannel frontendChannel_; std::unordered_map perfTimingsBuffer_{}; std::mutex perfTimingsMutex_; + std::map resourceTypeMap_{}; + BoundedRequestBuffer requestBodyBuffer_{}; + std::mutex requestBodyMutex_; }; } // namespace facebook::react::jsinspector_modern @@ -14223,6 +14337,75 @@ struct DevToolsTrackEntryPayload { }; } // namespace facebook::react::jsinspector_modern +/// @src {packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h}: +namespace facebook::react::jsinspector_modern::tracing { +using ConsoleTimeStampEntry = std::variant; +enum class ConsoleTimeStampColor { + Primary, + PrimaryLight, + PrimaryDark, + Secondary, + SecondaryLight, + SecondaryDark, + Tertiary, + TertiaryLight, + TertiaryDark, + Error, +}; +inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) { + switch (color) { + case ConsoleTimeStampColor::Primary: + return "primary"; + case ConsoleTimeStampColor::PrimaryLight: + return "primary-light"; + case ConsoleTimeStampColor::PrimaryDark: + return "primary-dark"; + case ConsoleTimeStampColor::Secondary: + return "secondary"; + case ConsoleTimeStampColor::SecondaryLight: + return "secondary-light"; + case ConsoleTimeStampColor::SecondaryDark: + return "secondary-dark"; + case ConsoleTimeStampColor::Tertiary: + return "tertiary"; + case ConsoleTimeStampColor::TertiaryLight: + return "tertiary-light"; + case ConsoleTimeStampColor::TertiaryDark: + return "tertiary-dark"; + case ConsoleTimeStampColor::Error: + return "error"; + default: + throw std::runtime_error("Unknown ConsoleTimeStampColor"); + } +}; +inline std::optional getConsoleTimeStampColorFromString( + const std::string& str) { + if (str == "primary") { + return ConsoleTimeStampColor::Primary; + } else if (str == "primary-light") { + return ConsoleTimeStampColor::PrimaryLight; + } else if (str == "primary-dark") { + return ConsoleTimeStampColor::PrimaryDark; + } else if (str == "secondary") { + return ConsoleTimeStampColor::Secondary; + } else if (str == "secondary-light") { + return ConsoleTimeStampColor::SecondaryLight; + } else if (str == "secondary-dark") { + return ConsoleTimeStampColor::SecondaryDark; + } else if (str == "tertiary") { + return ConsoleTimeStampColor::Tertiary; + } else if (str == "tertiary-light") { + return ConsoleTimeStampColor::TertiaryLight; + } else if (str == "tertiary-dark") { + return ConsoleTimeStampColor::TertiaryDark; + } else if (str == "error") { + return ConsoleTimeStampColor::Error; + } else { + return std::nullopt; + } +}; +}; // namespace facebook::react::jsinspector_modern::tracing + /// @src {packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h}: namespace facebook::react::jsinspector_modern::tracing { enum class EventLoopPhase { @@ -14256,6 +14439,7 @@ struct InstanceTracingProfile { /// @src {packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h}: /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/CdpTracing.h} +/// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h} /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEvent.h} /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventProfile.h} namespace facebook::react::jsinspector_modern::tracing { @@ -14264,8 +14448,8 @@ class PerformanceTracer { static PerformanceTracer& getInstance(); bool startTracing(); bool stopTracing(); - bool isTracing() const { - return tracing_; + inline bool isTracing() const { + return tracingAtomic_; } void collectEvents( const std::function& @@ -14277,6 +14461,13 @@ class PerformanceTracer { HighResTimeStamp start, HighResDuration duration, const std::optional& trackMetadata); + void reportTimeStamp( + std::string name, + std::optional start = std::nullopt, + std::optional end = std::nullopt, + std::optional trackName = std::nullopt, + std::optional trackGroup = std::nullopt, + std::optional color = std::nullopt); void reportProcess(uint64_t id, const std::string& name); void reportThread(uint64_t id, const std::string& name); void reportJavaScriptThread(); @@ -14292,7 +14483,6 @@ class PerformanceTracer { HighResTimeStamp chunkTimestamp, const TraceEventProfileChunk& traceEventProfileChunk); }; - uint64_t processId_; uint32_t performanceMeasureCount_{0}; std::vector buffer_; std::mutex mutex_; @@ -14474,6 +14664,7 @@ struct RuntimeSamplingProfile { /// @src {packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h}: /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/CdpTracing.h} +/// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h} /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEvent.h} /// @dep {packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventProfile.h} namespace facebook::react::jsinspector_modern::tracing { @@ -14482,8 +14673,8 @@ class PerformanceTracer { static PerformanceTracer& getInstance(); bool startTracing(); bool stopTracing(); - bool isTracing() const { - return tracing_; + inline bool isTracing() const { + return tracingAtomic_; } void collectEvents( const std::function& @@ -14495,6 +14686,13 @@ class PerformanceTracer { HighResTimeStamp start, HighResDuration duration, const std::optional& trackMetadata); + void reportTimeStamp( + std::string name, + std::optional start = std::nullopt, + std::optional end = std::nullopt, + std::optional trackName = std::nullopt, + std::optional trackGroup = std::nullopt, + std::optional color = std::nullopt); void reportProcess(uint64_t id, const std::string& name); void reportThread(uint64_t id, const std::string& name); void reportJavaScriptThread(); @@ -14510,7 +14708,6 @@ class PerformanceTracer { HighResTimeStamp chunkTimestamp, const TraceEventProfileChunk& traceEventProfileChunk); }; - uint64_t processId_; uint32_t performanceMeasureCount_{0}; std::vector buffer_; std::mutex mutex_; @@ -15718,8 +15915,12 @@ struct Bridging> /// @src {packages/react-native/ReactCommon/react/bridging/Promise.h}: namespace facebook::react { -template +template class AsyncPromise { + static_assert( + sizeof...(T) <= 1, + "AsyncPromise must have at most one argument"); + public: AsyncPromise(jsi::Runtime& rt, const std::shared_ptr& jsInvoker) : state_(std::make_shared()) { @@ -15728,7 +15929,9 @@ class AsyncPromise { rt, bridging::toJs( rt, - [this](AsyncCallback resolve, AsyncCallback reject) { + [this]( + AsyncCallback resolve, + const AsyncCallback& reject) { state_->resolve = std::move(resolve); state_->reject = std::move(reject); }, @@ -15738,10 +15941,10 @@ class AsyncPromise { LongLivedObjectCollection::get(rt).add(promiseHolder); state_->promiseHolder = promiseHolder; } - void resolve(T value) { + void resolve(T... value) { std::lock_guard lock(state_->mutex); if (state_->resolve) { - state_->resolve->call(std::move(value)); + state_->resolve->call(std::forward(value)...); state_->resolve.reset(); state_->reject.reset(); } @@ -15770,14 +15973,14 @@ class AsyncPromise { } std::mutex mutex; std::weak_ptr promiseHolder; - std::optional> resolve; + std::optional> resolve; std::optional> reject; }; std::shared_ptr state_; }; -template -struct Bridging> { - static jsi::Object toJs(jsi::Runtime& rt, const AsyncPromise& promise) { +template +struct Bridging> { + static jsi::Object toJs(jsi::Runtime& rt, const AsyncPromise& promise) { return promise.get(rt); } }; @@ -16073,8 +16276,7 @@ class TurboModuleBinding { } // namespace facebook::react /// @src {packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h}: -namespace facebook::react { -namespace TurboModulePerfLogger { +namespace facebook::react::TurboModulePerfLogger { void enableLogging(std::unique_ptr&& logger); void disableLogging(); void moduleDataCreateStart(const char* moduleName, int32_t id); @@ -16145,13 +16347,10 @@ void asyncMethodCallExecutionFail( const char* moduleName, const char* methodName, int32_t id); -} // namespace TurboModulePerfLogger -} // namespace facebook::react +} // namespace facebook::react::TurboModulePerfLogger /// @src {packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h}: namespace facebook::react { -jsi::Object deepCopyJSIObject(jsi::Runtime& rt, const jsi::Object& obj); -jsi::Array deepCopyJSIArray(jsi::Runtime& rt, const jsi::Array& arr); struct Promise : public LongLivedObject { Promise(jsi::Runtime& rt, jsi::Function resolve, jsi::Function reject); void resolve(const jsi::Value& result); @@ -16164,18 +16363,6 @@ using PromiseSetupFunctionType = jsi::Value createPromiseAsJSIValue( jsi::Runtime& rt, PromiseSetupFunctionType&& func); -class RAIICallbackWrapperDestroyer { - public: - RAIICallbackWrapperDestroyer(std::weak_ptr callbackWrapper) - : callbackWrapper_(callbackWrapper) {} - ~RAIICallbackWrapperDestroyer() { - auto strongWrapper = callbackWrapper_.lock(); - if (!strongWrapper) { - return; - } - strongWrapper->destroy(); - } -}; } // namespace facebook::react /// @src {packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h}: @@ -16254,8 +16441,7 @@ class JSI_EXPORT JavaTurboModule : public TurboModule { /// @src {packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTInteropTurboModule.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.h} -namespace facebook { -namespace react { +namespace facebook::react { class JSI_EXPORT ObjCInteropTurboModule : public ObjCTurboModule { public: struct MethodDescriptor { @@ -16284,8 +16470,7 @@ class JSI_EXPORT ObjCInteropTurboModule : public ObjCTurboModule { NSInvocation *inv, NSMutableArray *retainedObjectsForInvocation) override; }; -} // namespace react -} // namespace facebook +} // namespace facebook::react /// @src {packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.h}: namespace facebook::react { @@ -16565,58 +16750,62 @@ class NativeDOM : public NativeDOMCxxSpec { bool isConnected(jsi::Runtime& rt, jsi::Value nativeNodeReference); std::tuple getBorderWidth( jsi::Runtime& rt, - ShadowNode::Shared shadowNode); + std::shared_ptr shadowNode); std::tuple getBoundingClientRect( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, bool includeTransform); std::tuple getInnerSize( jsi::Runtime& rt, - ShadowNode::Shared shadowNode); + std::shared_ptr shadowNode); std::tuple getScrollPosition( jsi::Runtime& rt, - ShadowNode::Shared shadowNode); + std::shared_ptr shadowNode); std::tuple getScrollSize( jsi::Runtime& rt, - ShadowNode::Shared shadowNode); - std::string getTagName(jsi::Runtime& rt, ShadowNode::Shared shadowNode); - std::string getTextContent(jsi::Runtime& rt, ShadowNode::Shared shadowNode); + std::shared_ptr shadowNode); + std::string getTagName( + jsi::Runtime& rt, + std::shared_ptr shadowNode); + std::string getTextContent( + jsi::Runtime& rt, + std::shared_ptr shadowNode); bool hasPointerCapture( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, double pointerId); void releasePointerCapture( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, double pointerId); void setPointerCapture( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, double pointerId); std::tuple getOffset( jsi::Runtime& rt, - ShadowNode::Shared shadowNode); + std::shared_ptr shadowNode); jsi::Value linkRootNode( jsi::Runtime& rt, SurfaceId surfaceId, jsi::Value instanceHandle); void measure( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, jsi::Function callback); void measureInWindow( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, jsi::Function callback); void measureLayout( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, - ShadowNode::Shared relativeToShadowNode, + std::shared_ptr shadowNode, + std::shared_ptr relativeToShadowNode, jsi::Function onFail, jsi::Function onSuccess); void setNativeProps( jsi::Runtime& rt, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, jsi::Value updatePayload); }; } // namespace facebook::react @@ -16630,6 +16819,7 @@ class NativeFantomTestSpecificMethods explicit NativeFantomTestSpecificMethods( std::shared_ptr jsInvoker); void registerForcedCloneCommitHook(jsi::Runtime& runtime); + void takeFunctionAndNoop(jsi::Runtime& runtime, jsi::Function callback); }; }; } // namespace facebook::react @@ -16641,7 +16831,7 @@ struct FantomForcedCloneCommitHook : public UIManagerCommitHook { void commitHookWasUnregistered(const UIManager&) noexcept override; RootShadowNode::Unshared shadowTreeWillCommit( const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, + const std::shared_ptr& oldRootShadowNode, const RootShadowNode::Unshared& newRootShadowNode) noexcept override; }; } // namespace facebook::react @@ -16658,11 +16848,13 @@ class NativeReactNativeFeatureFlags bool commonTestFlagWithoutNativeImplementation(jsi::Runtime& runtime); bool animatedShouldSignalBatch(jsi::Runtime& runtime); bool cxxNativeAnimatedEnabled(jsi::Runtime& runtime); + bool cxxNativeAnimatedRemoveJsSync(jsi::Runtime& runtime); bool disableMainQueueSyncDispatchIOS(jsi::Runtime& runtime); bool disableMountItemReorderingAndroid(jsi::Runtime& runtime); bool disableTextLayoutManagerCacheAndroid(jsi::Runtime& runtime); bool enableAccessibilityOrder(jsi::Runtime& runtime); bool enableAccumulatedUpdatesInRawPropsAndroid(jsi::Runtime& runtime); + bool enableAndroidTextMeasurementOptimizations(jsi::Runtime& runtime); bool enableBridgelessArchitecture(jsi::Runtime& runtime); bool enableCppPropsIteratorSetter(jsi::Runtime& runtime); bool enableCustomFocusSearchOnClippedElementsAndroid(jsi::Runtime& runtime); @@ -16675,6 +16867,8 @@ class NativeReactNativeFeatureFlags bool enableFontScaleChangesUpdatingLayout(jsi::Runtime& runtime); bool enableIOSTextBaselineOffsetPerLine(jsi::Runtime& runtime); bool enableIOSViewClipToPaddingBox(jsi::Runtime& runtime); + bool enableInteropViewManagerClassLookUpOptimizationIOS( + jsi::Runtime& runtime); bool enableLayoutAnimationsOnAndroid(jsi::Runtime& runtime); bool enableLayoutAnimationsOnIOS(jsi::Runtime& runtime); bool enableMainQueueCoordinatorOnIOS(jsi::Runtime& runtime); @@ -16692,9 +16886,13 @@ class NativeReactNativeFeatureFlags bool enableViewRecyclingForText(jsi::Runtime& runtime); bool enableViewRecyclingForView(jsi::Runtime& runtime); bool enableVirtualViewDebugFeatures(jsi::Runtime& runtime); + bool enableVirtualViewRenderState(jsi::Runtime& runtime); + bool enableVirtualViewWindowFocusDetection(jsi::Runtime& runtime); bool fixMappingOfEventPrioritiesBetweenFabricAndReact(jsi::Runtime& runtime); bool fuseboxEnabledRelease(jsi::Runtime& runtime); bool fuseboxNetworkInspectionEnabled(jsi::Runtime& runtime); + bool hideOffscreenVirtualViewsOnIOS(jsi::Runtime& runtime); + double preparedTextCacheSize(jsi::Runtime& runtime); bool traceTurboModulePromiseRejectionsOnAndroid(jsi::Runtime& runtime); bool updateRuntimeShadowNodeReferencesOnCommit(jsi::Runtime& runtime); bool useAlwaysAvailableJSErrorHandling(jsi::Runtime& runtime); @@ -16738,8 +16936,8 @@ using RectAsTuple = std::tuple; using NativeIntersectionObserverObserveOptions = NativeIntersectionObserverNativeIntersectionObserverObserveOptions< NativeIntersectionObserverIntersectionObserverId, - std::optional, - ShadowNode::Shared, + std::optional>, + std::shared_ptr, std::vector, std::optional>>; template <> @@ -16771,7 +16969,7 @@ class NativeIntersectionObserver void unobserve( jsi::Runtime& runtime, IntersectionObserverObserverId intersectionObserverId, - ShadowNode::Shared targetShadowNode); + std::shared_ptr targetShadowNode); jsi::Object observeV2( jsi::Runtime& runtime, NativeIntersectionObserverObserveOptions options); @@ -16807,7 +17005,7 @@ namespace facebook::react { using NativeMutationObserverObserveOptions = NativeMutationObserverNativeMutationObserverObserveOptions< MutationObserverId, - ShadowNode::Shared, + std::shared_ptr, bool>; template <> struct Bridging @@ -16850,60 +17048,7 @@ class NativeMutationObserver jsi::Value getPublicInstanceFromShadowNode( const ShadowNode& shadowNode) const; std::vector getPublicInstancesFromShadowNodes( - const std::vector& shadowNodes) const; -}; -} // namespace facebook::react - -/// @src {packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h}: -namespace facebook::react { -class JSI_EXPORT NativeSampleTurboCxxModuleSpecJSI : public TurboModule { - protected: - NativeSampleTurboCxxModuleSpecJSI(std::shared_ptr jsInvoker); - - public: - virtual void voidFunc(jsi::Runtime& rt) = 0; - virtual bool getBool(jsi::Runtime& rt, bool arg) = 0; - virtual double getEnum(jsi::Runtime& rt, double arg) = 0; - virtual double getNumber(jsi::Runtime& rt, double arg) = 0; - virtual jsi::String getString(jsi::Runtime& rt, const jsi::String& arg) = 0; - virtual jsi::Array getArray(jsi::Runtime& rt, const jsi::Array& arg) = 0; - virtual jsi::Object getObject(jsi::Runtime& rt, const jsi::Object& arg) = 0; - virtual jsi::Object getValue( - jsi::Runtime& rt, - double x, - const jsi::String& y, - const jsi::Object& z) = 0; - virtual void getValueWithCallback( - jsi::Runtime& rt, - const jsi::Function& callback) = 0; - virtual jsi::Value getValueWithPromise(jsi::Runtime& rt, bool error) = 0; - virtual jsi::Object getConstants(jsi::Runtime& rt) = 0; -}; -} // namespace facebook::react - -/// @src {packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h}: -/// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h} - -namespace facebook::react { -class SampleTurboCxxModule : public NativeSampleTurboCxxModuleSpecJSI { - public: - SampleTurboCxxModule(std::shared_ptr jsInvoker); - void voidFunc(jsi::Runtime& rt) override; - bool getBool(jsi::Runtime& rt, bool arg) override; - double getEnum(jsi::Runtime& rt, double arg) override; - double getNumber(jsi::Runtime& rt, double arg) override; - jsi::String getString(jsi::Runtime& rt, const jsi::String& arg) override; - jsi::Array getArray(jsi::Runtime& rt, const jsi::Array& arg) override; - jsi::Object getObject(jsi::Runtime& rt, const jsi::Object& arg) override; - jsi::Object getValue( - jsi::Runtime& rt, - double x, - const jsi::String& y, - const jsi::Object& z) override; - void getValueWithCallback(jsi::Runtime& rt, const jsi::Function& callback) - override; - jsi::Value getValueWithPromise(jsi::Runtime& rt, bool error) override; - jsi::Object getConstants(jsi::Runtime& rt) override; + const std::vector>& shadowNodes) const; }; } // namespace facebook::react @@ -16937,9 +17082,6 @@ std::shared_ptr SampleTurboModuleSpec_ModuleProvider( /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleLegacyModule.h} -/// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboCxxModule.h}: -/// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleTurboCxxModule.h} - /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModule.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTNativeSampleTurboModuleSpec.h} @interface RCTSampleTurboModule : NativeSampleTurboModuleSpecBase @@ -16948,18 +17090,12 @@ std::shared_ptr SampleTurboModuleSpec_ModuleProvider( /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModulePlugin.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleTurboModulePlugin.h} -/// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/SampleTurboCxxModuleLegacyImpl.h}: -/// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/SampleTurboCxxModuleLegacyImpl.h} - /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTNativeSampleTurboModuleSpec.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTNativeSampleTurboModuleSpec.h} /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleLegacyModule.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.h} -/// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleTurboCxxModule.h}: -/// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboCxxModule.h} - /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/RCTSampleTurboModule.h}: /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTNativeSampleTurboModuleSpec.h} @interface RCTSampleTurboModule : NativeSampleTurboModuleSpecBase @@ -16969,7 +17105,33 @@ std::shared_ptr SampleTurboModuleSpec_ModuleProvider( /// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModulePlugin.h} /// @src {packages/react-native/ReactCommon/react/nativemodule/samples/platform/macos/ReactCommon/SampleTurboCxxModuleLegacyImpl.h}: -/// @dep {packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/SampleTurboCxxModuleLegacyImpl.h} +namespace facebook::react { +class SampleTurboCxxModuleLegacyImpl + : public facebook::xplat::module::CxxModule { + public: + SampleTurboCxxModuleLegacyImpl(); + std::string getName() override; + std::map getConstants() override; + std::vector getMethods() override; + void voidFunc(); + bool getBool(bool arg); + double getEnum(double arg); + double getNumber(double arg); + std::string getString(const std::string& arg); + folly::dynamic getArray(const folly::dynamic& arg); + folly::dynamic getObject(const folly::dynamic& arg); + folly::dynamic getUnsafeObject(const folly::dynamic& arg); + double getRootTag(double arg); + folly::dynamic + getValue(double x, const std::string& y, const folly::dynamic& z); + void getValueWithCallback( + const facebook::xplat::module::CxxModule::Callback& callback); + void getValueWithPromise( + bool error, + const facebook::xplat::module::CxxModule::Callback& resolve, + const facebook::xplat::module::CxxModule::Callback& reject); +}; +} // namespace facebook::react /// @src {packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h}: namespace facebook::react { @@ -17020,6 +17182,15 @@ class NativePerformance : public NativePerformanceCxxSpec { jsi::Runtime& rt, std::string name, std::optional startTime); + std::tuple measure( + jsi::Runtime& rt, + std::string name, + std::optional startTime, + std::optional endTime, + std::optional duration, + std::optional startMark, + std::optional endMark); + [[deprecated("This method is deprecated. Use the measure method instead.")]] std::tuple measureWithResult( jsi::Runtime& rt, std::string name, @@ -17060,6 +17231,8 @@ class NativePerformance : public NativePerformanceCxxSpec { std::unordered_map getSimpleMemoryInfo(jsi::Runtime& rt); std::unordered_map getReactNativeStartupTiming( jsi::Runtime& rt); + void setCurrentTimeStampForTesting(jsi::Runtime& rt, HighResTimeStamp ts); + void clearEventCountsForTesting(jsi::Runtime& rt); }; } // namespace facebook::react @@ -17398,6 +17571,7 @@ class PerformanceEntryReporter { const std::unordered_map& getEventCounts() const { return eventCounts_; } + void clearEventCounts(); std::optional getMarkTime( const std::string& markName) const; PerformanceMark reportMark( @@ -19195,8 +19369,8 @@ enum class HyphenationFrequency { None, Normal, Full }; /// @src {packages/react-native/ReactCommon/react/renderer/bridging/bridging.h}: namespace facebook::react { template <> -struct Bridging { - static ShadowNode::Shared fromJs( +struct Bridging> { + static std::shared_ptr fromJs( jsi::Runtime& rt, const jsi::Value& jsiValue) { auto object = jsiValue.asObject(rt); @@ -19213,7 +19387,9 @@ struct Bridging { } return shadowNodeWrapper->shadowNode; } - static jsi::Value toJs(jsi::Runtime& rt, const ShadowNode::Shared& value) { + static jsi::Value toJs( + jsi::Runtime& rt, + const std::shared_ptr& value) { jsi::Object obj(rt); obj.setNativeState(rt, std::make_shared(value)); return obj; @@ -19717,8 +19893,9 @@ class ModalHostViewComponentDescriptor final static_cast( *shadowNode.getState()) .getData(); - layoutableShadowNode.setSize( - Size{stateData.screenSize.width, stateData.screenSize.height}); + layoutableShadowNode.setSize(Size{ + .width = stateData.screenSize.width, + .height = stateData.screenSize.height}); layoutableShadowNode.setPositionType(YGPositionTypeAbsolute); ConcreteComponentDescriptor::adopt(shadowNode); } @@ -19745,11 +19922,12 @@ class ModalHostViewShadowNode final : public ConcreteViewShadowNode< } // namespace facebook::react /// @src {packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h}: +/// @dep {packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewUtils.h} namespace facebook::react { class ModalHostViewState final { public: using Shared = std::shared_ptr; - ModalHostViewState() {}; + ModalHostViewState() : screenSize(ModalHostViewScreenSize()) {} ModalHostViewState(Size screenSize_) : screenSize(screenSize_) {}; const Size screenSize{}; }; @@ -19757,9 +19935,30 @@ class ModalHostViewState final { /// @src {packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewUtils.h}: namespace facebook::react { -Size RCTModalHostViewScreenSize(void); +Size ModalHostViewScreenSize(void); } +/// @src {packages/react-native/ReactCommon/react/renderer/components/modal/platform/android/JReactModalHostView.h}: +namespace facebook::react { +class JReactModalHostView + : public facebook::jni::JavaClass { + public: + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/views/modal/ReactModalHostView;"; + static Size getDisplayMetrics() { + static auto method = + JReactModalHostView::javaClassStatic()->getStaticMethod( + "getScreenDisplayMetricsWithoutInsets"); + auto result = method(javaClassStatic()); + int32_t wBits = 0xFFFFFFFF & (result >> 32); + int32_t hBits = 0xFFFFFFFF & result; + auto* measuredWidth = reinterpret_cast(&wBits); + auto* measuredHeight = reinterpret_cast(&hBits); + return Size{.width = *measuredWidth, .height = *measuredHeight}; + } +}; +} // namespace facebook::react + /// @src {packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarComponentDescriptor.h}: /// @dep {packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarMeasurementsManager.h} /// @dep {packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarShadowNode.h} @@ -20982,7 +21181,7 @@ class AndroidTextInputComponentDescriptor final if (getThemeData( fabricUIManager, surfaceId, defaultTextInputPaddingArray)) { jfloat* defaultTextInputPadding = - env->GetFloatArrayElements(defaultTextInputPaddingArray, 0); + env->GetFloatArrayElements(defaultTextInputPaddingArray, nullptr); theme.start = defaultTextInputPadding[0]; theme.end = defaultTextInputPadding[1]; theme.top = defaultTextInputPadding[2]; @@ -23582,10 +23781,10 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { const ShadowNode& sourceShadowNode, const ShadowNodeFragment& fragment) override; void enableMeasurement(); - void appendChild(const ShadowNode::Shared& child) override; + void appendChild(const std::shared_ptr& child) override; void replaceChild( const ShadowNode& oldChild, - const ShadowNode::Shared& newChild, + const std::shared_ptr& newChild, size_t suggestedIndex = SIZE_MAX) override; void updateYogaChildren(); void updateYogaProps(); @@ -26690,6 +26889,465 @@ struct BorderMetrics { /// @src {packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h}: namespace facebook::react { +static inline yoga::Style convertRawProp( + const PropsParserContext& context, + const RawProps& rawProps, + const yoga::Style& sourceValue) { + yoga::Style yogaStyle{}; + yogaStyle.setDirection(convertRawProp( + context, + rawProps, + "direction", + sourceValue.direction(), + yogaStyle.direction())); + yogaStyle.setFlexDirection(convertRawProp( + context, + rawProps, + "flexDirection", + sourceValue.flexDirection(), + yogaStyle.flexDirection())); + yogaStyle.setJustifyContent(convertRawProp( + context, + rawProps, + "justifyContent", + sourceValue.justifyContent(), + yogaStyle.justifyContent())); + yogaStyle.setAlignContent(convertRawProp( + context, + rawProps, + "alignContent", + sourceValue.alignContent(), + yogaStyle.alignContent())); + yogaStyle.setAlignItems(convertRawProp( + context, + rawProps, + "alignItems", + sourceValue.alignItems(), + yogaStyle.alignItems())); + yogaStyle.setAlignSelf(convertRawProp( + context, + rawProps, + "alignSelf", + sourceValue.alignSelf(), + yogaStyle.alignSelf())); + yogaStyle.setPositionType(convertRawProp( + context, + rawProps, + "position", + sourceValue.positionType(), + yogaStyle.positionType())); + yogaStyle.setFlexWrap(convertRawProp( + context, + rawProps, + "flexWrap", + sourceValue.flexWrap(), + yogaStyle.flexWrap())); + yogaStyle.setOverflow(convertRawProp( + context, + rawProps, + "overflow", + sourceValue.overflow(), + yogaStyle.overflow())); + yogaStyle.setDisplay(convertRawProp( + context, + rawProps, + "display", + sourceValue.display(), + yogaStyle.display())); + yogaStyle.setFlex(convertRawProp( + context, rawProps, "flex", sourceValue.flex(), yogaStyle.flex())); + yogaStyle.setFlexGrow(convertRawProp( + context, + rawProps, + "flexGrow", + sourceValue.flexGrow(), + yogaStyle.flexGrow())); + yogaStyle.setFlexShrink(convertRawProp( + context, + rawProps, + "flexShrink", + sourceValue.flexShrink(), + yogaStyle.flexShrink())); + yogaStyle.setFlexBasis(convertRawProp( + context, + rawProps, + "flexBasis", + sourceValue.flexBasis(), + yogaStyle.flexBasis())); + yogaStyle.setMargin( + yoga::Edge::Left, + convertRawProp( + context, + rawProps, + "marginLeft", + sourceValue.margin(yoga::Edge::Left), + yogaStyle.margin(yoga::Edge::Left))); + yogaStyle.setMargin( + yoga::Edge::Top, + convertRawProp( + context, + rawProps, + "marginTop", + sourceValue.margin(yoga::Edge::Top), + yogaStyle.margin(yoga::Edge::Top))); + yogaStyle.setMargin( + yoga::Edge::Right, + convertRawProp( + context, + rawProps, + "marginRight", + sourceValue.margin(yoga::Edge::Right), + yogaStyle.margin(yoga::Edge::Right))); + yogaStyle.setMargin( + yoga::Edge::Bottom, + convertRawProp( + context, + rawProps, + "marginBottom", + sourceValue.margin(yoga::Edge::Bottom), + yogaStyle.margin(yoga::Edge::Bottom))); + yogaStyle.setMargin( + yoga::Edge::Start, + convertRawProp( + context, + rawProps, + "marginStart", + sourceValue.margin(yoga::Edge::Start), + yogaStyle.margin(yoga::Edge::Start))); + yogaStyle.setMargin( + yoga::Edge::End, + convertRawProp( + context, + rawProps, + "marginEnd", + sourceValue.margin(yoga::Edge::End), + yogaStyle.margin(yoga::Edge::End))); + yogaStyle.setMargin( + yoga::Edge::Horizontal, + convertRawProp( + context, + rawProps, + "marginHorizontal", + sourceValue.margin(yoga::Edge::Horizontal), + yogaStyle.margin(yoga::Edge::Horizontal))); + yogaStyle.setMargin( + yoga::Edge::Vertical, + convertRawProp( + context, + rawProps, + "marginVertical", + sourceValue.margin(yoga::Edge::Vertical), + yogaStyle.margin(yoga::Edge::Vertical))); + yogaStyle.setMargin( + yoga::Edge::All, + convertRawProp( + context, + rawProps, + "margin", + sourceValue.margin(yoga::Edge::All), + yogaStyle.margin(yoga::Edge::All))); + yogaStyle.setPosition( + yoga::Edge::Left, + convertRawProp( + context, + rawProps, + "left", + sourceValue.position(yoga::Edge::Left), + yogaStyle.position(yoga::Edge::Left))); + yogaStyle.setPosition( + yoga::Edge::Top, + convertRawProp( + context, + rawProps, + "top", + sourceValue.position(yoga::Edge::Top), + yogaStyle.position(yoga::Edge::Top))); + yogaStyle.setPosition( + yoga::Edge::Right, + convertRawProp( + context, + rawProps, + "right", + sourceValue.position(yoga::Edge::Right), + yogaStyle.position(yoga::Edge::Right))); + yogaStyle.setPosition( + yoga::Edge::Bottom, + convertRawProp( + context, + rawProps, + "bottom", + sourceValue.position(yoga::Edge::Bottom), + yogaStyle.position(yoga::Edge::Bottom))); + yogaStyle.setPosition( + yoga::Edge::Start, + convertRawProp( + context, + rawProps, + "start", + sourceValue.position(yoga::Edge::Start), + yogaStyle.position(yoga::Edge::Start))); + yogaStyle.setPosition( + yoga::Edge::End, + convertRawProp( + context, + rawProps, + "end", + sourceValue.position(yoga::Edge::End), + yogaStyle.position(yoga::Edge::End))); + yogaStyle.setPosition( + yoga::Edge::Horizontal, + convertRawProp( + context, + rawProps, + "insetInline", + sourceValue.position(yoga::Edge::Horizontal), + yogaStyle.position(yoga::Edge::Horizontal))); + yogaStyle.setPosition( + yoga::Edge::Vertical, + convertRawProp( + context, + rawProps, + "insetBlock", + sourceValue.position(yoga::Edge::Vertical), + yogaStyle.position(yoga::Edge::Vertical))); + yogaStyle.setPosition( + yoga::Edge::All, + convertRawProp( + context, + rawProps, + "inset", + sourceValue.position(yoga::Edge::All), + yogaStyle.position(yoga::Edge::All))); + yogaStyle.setPadding( + yoga::Edge::Left, + convertRawProp( + context, + rawProps, + "paddingLeft", + sourceValue.padding(yoga::Edge::Left), + yogaStyle.padding(yoga::Edge::Left))); + yogaStyle.setPadding( + yoga::Edge::Top, + convertRawProp( + context, + rawProps, + "paddingTop", + sourceValue.padding(yoga::Edge::Top), + yogaStyle.padding(yoga::Edge::Top))); + yogaStyle.setPadding( + yoga::Edge::Right, + convertRawProp( + context, + rawProps, + "paddingRight", + sourceValue.padding(yoga::Edge::Right), + yogaStyle.padding(yoga::Edge::Right))); + yogaStyle.setPadding( + yoga::Edge::Bottom, + convertRawProp( + context, + rawProps, + "paddingBottom", + sourceValue.padding(yoga::Edge::Bottom), + yogaStyle.padding(yoga::Edge::Bottom))); + yogaStyle.setPadding( + yoga::Edge::Start, + convertRawProp( + context, + rawProps, + "paddingStart", + sourceValue.padding(yoga::Edge::Start), + yogaStyle.padding(yoga::Edge::Start))); + yogaStyle.setPadding( + yoga::Edge::End, + convertRawProp( + context, + rawProps, + "paddingEnd", + sourceValue.padding(yoga::Edge::End), + yogaStyle.padding(yoga::Edge::End))); + yogaStyle.setPadding( + yoga::Edge::Horizontal, + convertRawProp( + context, + rawProps, + "paddingHorizontal", + sourceValue.padding(yoga::Edge::Horizontal), + yogaStyle.padding(yoga::Edge::Horizontal))); + yogaStyle.setPadding( + yoga::Edge::Vertical, + convertRawProp( + context, + rawProps, + "paddingVertical", + sourceValue.padding(yoga::Edge::Vertical), + yogaStyle.padding(yoga::Edge::Vertical))); + yogaStyle.setPadding( + yoga::Edge::All, + convertRawProp( + context, + rawProps, + "padding", + sourceValue.padding(yoga::Edge::All), + yogaStyle.padding(yoga::Edge::All))); + yogaStyle.setGap( + yoga::Gutter::Row, + convertRawProp( + context, + rawProps, + "rowGap", + sourceValue.gap(yoga::Gutter::Row), + yogaStyle.gap(yoga::Gutter::Row))); + yogaStyle.setGap( + yoga::Gutter::Column, + convertRawProp( + context, + rawProps, + "columnGap", + sourceValue.gap(yoga::Gutter::Column), + yogaStyle.gap(yoga::Gutter::Column))); + yogaStyle.setGap( + yoga::Gutter::All, + convertRawProp( + context, + rawProps, + "gap", + sourceValue.gap(yoga::Gutter::All), + yogaStyle.gap(yoga::Gutter::All))); + yogaStyle.setBorder( + yoga::Edge::Left, + convertRawProp( + context, + rawProps, + "borderLeftWidth", + sourceValue.border(yoga::Edge::Left), + yogaStyle.border(yoga::Edge::Left))); + yogaStyle.setBorder( + yoga::Edge::Top, + convertRawProp( + context, + rawProps, + "borderTopWidth", + sourceValue.border(yoga::Edge::Top), + yogaStyle.border(yoga::Edge::Top))); + yogaStyle.setBorder( + yoga::Edge::Right, + convertRawProp( + context, + rawProps, + "borderRightWidth", + sourceValue.border(yoga::Edge::Right), + yogaStyle.border(yoga::Edge::Right))); + yogaStyle.setBorder( + yoga::Edge::Bottom, + convertRawProp( + context, + rawProps, + "borderBottomWidth", + sourceValue.border(yoga::Edge::Bottom), + yogaStyle.border(yoga::Edge::Bottom))); + yogaStyle.setBorder( + yoga::Edge::Start, + convertRawProp( + context, + rawProps, + "borderStartWidth", + sourceValue.border(yoga::Edge::Start), + yogaStyle.border(yoga::Edge::Start))); + yogaStyle.setBorder( + yoga::Edge::End, + convertRawProp( + context, + rawProps, + "borderEndWidth", + sourceValue.border(yoga::Edge::End), + yogaStyle.border(yoga::Edge::End))); + yogaStyle.setBorder( + yoga::Edge::Horizontal, + convertRawProp( + context, + rawProps, + "borderHorizontalWidth", + sourceValue.border(yoga::Edge::Horizontal), + yogaStyle.border(yoga::Edge::Horizontal))); + yogaStyle.setBorder( + yoga::Edge::Vertical, + convertRawProp( + context, + rawProps, + "borderVerticalWidth", + sourceValue.border(yoga::Edge::Vertical), + yogaStyle.border(yoga::Edge::Vertical))); + yogaStyle.setBorder( + yoga::Edge::All, + convertRawProp( + context, + rawProps, + "borderWidth", + sourceValue.border(yoga::Edge::All), + yogaStyle.border(yoga::Edge::All))); + yogaStyle.setDimension( + yoga::Dimension::Width, + convertRawProp( + context, + rawProps, + "width", + sourceValue.dimension(yoga::Dimension::Width), + {})); + yogaStyle.setDimension( + yoga::Dimension::Height, + convertRawProp( + context, + rawProps, + "height", + sourceValue.dimension(yoga::Dimension::Height), + {})); + yogaStyle.setMinDimension( + yoga::Dimension::Width, + convertRawProp( + context, + rawProps, + "minWidth", + sourceValue.minDimension(yoga::Dimension::Width), + {})); + yogaStyle.setMinDimension( + yoga::Dimension::Height, + convertRawProp( + context, + rawProps, + "minHeight", + sourceValue.minDimension(yoga::Dimension::Height), + {})); + yogaStyle.setMaxDimension( + yoga::Dimension::Width, + convertRawProp( + context, + rawProps, + "maxWidth", + sourceValue.maxDimension(yoga::Dimension::Width), + {})); + yogaStyle.setMaxDimension( + yoga::Dimension::Height, + convertRawProp( + context, + rawProps, + "maxHeight", + sourceValue.maxDimension(yoga::Dimension::Height), + {})); + yogaStyle.setAspectRatio(convertRawProp( + context, + rawProps, + "aspectRatio", + sourceValue.aspectRatio(), + yogaStyle.aspectRatio())); + yogaStyle.setBoxSizing(convertRawProp( + context, + rawProps, + "boxSizing", + sourceValue.boxSizing(), + yogaStyle.boxSizing())); + return yogaStyle; +} template static inline CascadedRectangleCorners convertRawProp( const PropsParserContext& context, @@ -27109,6 +27767,29 @@ static inline ViewEvents convertRawProp( } } // namespace facebook::react +/// @src {packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h}: +namespace facebook::react { +using VirtualViewComponentDescriptor = + ConcreteComponentDescriptor; +} + +/// @src {packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h}: +namespace facebook::react { +constexpr const char VirtualViewComponentName[] = "VirtualView"; +class VirtualViewShadowNode final : public ConcreteViewShadowNode< + VirtualViewComponentName, + VirtualViewProps, + VirtualViewEventEmitter> { + public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + static ShadowNodeTraits BaseTraits() { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::Unstable_uncullableView); + return traits; + } +}; +} // namespace facebook::react + /// @src {packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h}: namespace facebook::react { class ScopedShadowTreeRevisionLock { @@ -27167,8 +27848,8 @@ class ComponentDescriptor { const ShadowNode& sourceShadowNode, const ShadowNodeFragment& fragment) const = 0; virtual void appendChild( - const ShadowNode::Shared& parentShadowNode, - const ShadowNode::Shared& childShadowNode) const = 0; + const std::shared_ptr& parentShadowNode, + const std::shared_ptr& childShadowNode) const = 0; virtual Props::Shared cloneProps( const PropsParserContext& context, const Props::Shared& props, @@ -27249,8 +27930,8 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { return shadowNode; } void appendChild( - const ShadowNode::Shared& parentShadowNode, - const ShadowNode::Shared& childShadowNode) const override { + const std::shared_ptr& parentShadowNode, + const std::shared_ptr& childShadowNode) const override { auto& concreteParentShadowNode = static_cast(*parentShadowNode); const_cast(concreteParentShadowNode) @@ -27907,8 +28588,8 @@ class LayoutableShadowNode : public ShadowNode { virtual Transform getTransform() const; virtual Point getContentOriginOffset(bool includeTransform) const; void setLayoutMetrics(LayoutMetrics layoutMetrics); - static ShadowNode::Shared findNodeAtPoint( - const ShadowNode::Shared& node, + static std::shared_ptr findNodeAtPoint( + const std::shared_ptr& node, Point point); virtual void dirtyLayout() = 0; virtual bool getIsLayoutClean() const = 0; @@ -28318,16 +28999,24 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::NativeState { public: - using Shared = std::shared_ptr; + using Shared [[deprecated("Use std::shared_ptr instead")]] = + std::shared_ptr; using Weak [[deprecated("Use std::weak_ptr instead")]] = std::weak_ptr; using Unshared [[deprecated("Use std::shared_ptr instead")]] = std::shared_ptr; - using ListOfShared = std::vector; - using ListOfWeak = std::vector>; - using SharedListOfShared = std::shared_ptr; - using UnsharedListOfShared = std::shared_ptr; - using UnsharedListOfWeak = std::shared_ptr; + using ListOfShared [[deprecated( + "Use std::vector> instead")]] = + std::vector>; + using ListOfWeak [[deprecated( + "Use std::vector> instead")]] = + std::vector>; + using SharedListOfShared = + std::shared_ptr>>; + using UnsharedListOfShared = + std::shared_ptr>>; + using UnsharedListOfWeak = + std::shared_ptr>>; using AncestorList = std::vector, int>>; static SharedListOfShared emptySharedShadowNodeSharedList(); @@ -28363,7 +29052,7 @@ class ShadowNode : public Sealable, ComponentHandle getComponentHandle() const; ShadowNodeTraits getTraits() const; const Props::Shared& getProps() const; - const ListOfShared& getChildren() const; + const std::vector>& getChildren() const; const SharedEventEmitter& getEventEmitter() const; jsi::Value getInstanceHandle(jsi::Runtime& runtime) const; Tag getTag() const; @@ -28376,19 +29065,19 @@ class ShadowNode : public Sealable, void sealRecursive() const; const ShadowNodeFamily& getFamily() const; ShadowNodeFamily::Shared getFamilyShared() const; - virtual void appendChild(const Shared& child); + virtual void appendChild(const std::shared_ptr& child); virtual void replaceChild( const ShadowNode& oldChild, - const Shared& newChild, + const std::shared_ptr& newChild, size_t suggestedIndex = std::numeric_limits::max()); void setMounted(bool mounted) const; bool getHasBeenPromoted() const; void setRuntimeShadowNodeReference(const std::shared_ptr& runtimeShadowNodeReference) const; void updateRuntimeShadowNodeReference( - const Shared& destinationShadowNode) const; + const std::shared_ptr& destinationShadowNode) const; void transferRuntimeShadowNodeReference( - const Shared& destinationShadowNode, + const std::shared_ptr& destinationShadowNode, const ShadowNodeFragment& fragment) const; protected: @@ -28410,10 +29099,10 @@ static_assert( std::has_virtual_destructor::value, "ShadowNode must have a virtual destructor"); struct ShadowNodeWrapper : public jsi::NativeState { - explicit ShadowNodeWrapper(ShadowNode::Shared shadowNode) + explicit ShadowNodeWrapper(std::shared_ptr shadowNode) : shadowNode(std::move(shadowNode)) {} ~ShadowNodeWrapper() override; - ShadowNode::Shared shadowNode; + std::shared_ptr shadowNode; }; } // namespace facebook::react @@ -32847,7 +33536,7 @@ struct RNMeasureRect { double pageY = 0; }; struct DOMOffset { - ShadowNode::Shared offsetParent = nullptr; + std::shared_ptr offsetParent = nullptr; double top = 0; double left = 0; }; @@ -32865,10 +33554,10 @@ struct DOMBorderWidthRounded { int bottom = 0; int left = 0; }; -ShadowNode::Shared getParentNode( +std::shared_ptr getParentNode( const RootShadowNode::Shared& currentRevision, const ShadowNode& shadowNode); -std::vector getChildNodes( +std::vector> getChildNodes( const RootShadowNode::Shared& currentRevision, const ShadowNode& shadowNode); bool isConnected( @@ -32992,17 +33681,19 @@ class Element final { std::function callback) { fragment_.referenceCallback = - [callback = std::move(callback)](const ShadowNode::Shared& shadowNode) { + [callback = std::move(callback)]( + const std::shared_ptr& shadowNode) { callback(std::const_pointer_cast( std::static_pointer_cast(shadowNode))); }; return *this; } Element& reference(ConcreteUnsharedShadowNode& outShadowNode) { - fragment_.referenceCallback = [&](const ShadowNode::Shared& shadowNode) { - outShadowNode = std::const_pointer_cast( - std::static_pointer_cast(shadowNode)); - }; + fragment_.referenceCallback = + [&](const std::shared_ptr& shadowNode) { + outShadowNode = std::const_pointer_cast( + std::static_pointer_cast(shadowNode)); + }; return *this; } Element& finalize( @@ -35829,9 +36520,9 @@ namespace facebook::react { using MutationObserverId = int32_t; struct MutationRecord { MutationObserverId mutationObserverId; - ShadowNode::Shared targetShadowNode; - std::vector addedShadowNodes; - std::vector removedShadowNodes; + std::shared_ptr targetShadowNode; + std::vector> addedShadowNodes; + std::vector> removedShadowNodes; }; class MutationObserver { public: @@ -35859,7 +36550,7 @@ class MutationObserverManager final : public UIManagerCommitHook { MutationObserverManager(); void observe( MutationObserverId mutationObserverId, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, bool observeSubtree, const UIManager& uiManager); void unobserveAll(MutationObserverId mutationObserverId); @@ -36150,15 +36841,10 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { const RuntimeExecutor runtimeExecutor_; SchedulerPriority currentPriority_{SchedulerPriority::NormalPriority}; void scheduleEventLoop(); - void runEventLoop(jsi::Runtime& runtime, bool onlyExpired); - std::shared_ptr selectTask( - HighResTimeStamp currentTime, - bool onlyExpired); + void runEventLoop(jsi::Runtime& runtime); + std::shared_ptr selectTask(); void scheduleTask(std::shared_ptr task); - void runEventLoopTick( - jsi::Runtime& runtime, - Task& task, - HighResTimeStamp taskStartTime); + void runEventLoopTick(jsi::Runtime& runtime, Task& task); void executeTask( jsi::Runtime& runtime, Task& task, @@ -36410,19 +37096,21 @@ class Scheduler final : public UIManagerDelegate { bool mountSynchronously) override; void uiManagerDidCreateShadowNode(const ShadowNode& shadowNode) override; void uiManagerDidDispatchCommand( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& commandName, const folly::dynamic& args) override; void uiManagerDidSendAccessibilityEvent( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& eventType) override; void uiManagerDidSetIsJSResponder( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) override; void uiManagerShouldSynchronouslyUpdateViewOnUIThread( Tag tag, const folly::dynamic& props) override; + void uiManagerDidUpdateShadowTree( + const std::unordered_map& tagToProps) override; void uiManagerShouldAddEventListener( std::shared_ptr listener) final; void uiManagerShouldRemoveEventListener( @@ -36468,6 +37156,8 @@ class SchedulerDelegate { virtual void schedulerShouldSynchronouslyUpdateViewOnUIThread( Tag tag, const folly::dynamic& props) = 0; + virtual void schedulerDidUpdateShadowTree( + const std::unordered_map& tagToProps) = 0; virtual ~SchedulerDelegate() noexcept = default; }; } // namespace facebook::react @@ -36811,6 +37501,12 @@ class LineMeasureCacheKey final { ParagraphAttributes paragraphAttributes{}; Size size{}; }; +class PreparedTextCacheKey final { + public: + AttributedString attributedString{}; + ParagraphAttributes paragraphAttributes{}; + LayoutConstraints layoutConstraints{}; +}; constexpr auto kSimpleThreadSafeCacheSizeCap = size_t{1024}; using TextMeasureCache = SimpleThreadSafeCache< TextMeasureCacheKey, @@ -36869,11 +37565,24 @@ inline bool areAttributedStringFragmentsEquivalentLayoutWise( (lhs.parentShadowView.layoutMetrics == rhs.parentShadowView.layoutMetrics)); } +inline bool areAttributedStringFragmentsEquivalentDisplayWise( + const AttributedString::Fragment& lhs, + const AttributedString::Fragment& rhs) { + return lhs.isContentEqual(rhs) && + (!lhs.isAttachment() || + (lhs.parentShadowView.layoutMetrics == + rhs.parentShadowView.layoutMetrics)); +} inline size_t attributedStringFragmentHashLayoutWise( const AttributedString::Fragment& fragment) { return facebook::react::hash_combine( fragment.string, textAttributesHashLayoutWise(fragment.textAttributes)); } +inline size_t attributedStringFragmentHashDisplayWise( + const AttributedString::Fragment& fragment) { + return facebook::react::hash_combine( + fragment.string, fragment.textAttributes); +} inline bool areAttributedStringsEquivalentLayoutWise( const AttributedString& lhs, const AttributedString& rhs) { @@ -36891,6 +37600,23 @@ inline bool areAttributedStringsEquivalentLayoutWise( } return true; } +inline bool areAttributedStringsEquivalentDisplayWise( + const AttributedString& lhs, + const AttributedString& rhs) { + auto& lhsFragment = lhs.getFragments(); + auto& rhsFragment = rhs.getFragments(); + if (lhsFragment.size() != rhsFragment.size()) { + return false; + } + auto size = lhsFragment.size(); + for (size_t i = 0; i < size; i++) { + if (!areAttributedStringFragmentsEquivalentDisplayWise( + lhsFragment.at(i), rhsFragment.at(i))) { + return false; + } + } + return true; +} inline size_t attributedStringHashLayoutWise( const AttributedString& attributedString) { auto seed = size_t{0}; @@ -36900,6 +37626,15 @@ inline size_t attributedStringHashLayoutWise( } return seed; } +inline size_t attributedStringHashDisplayWise( + const AttributedString& attributedString) { + size_t seed = 0; + for (const auto& fragment : attributedString.getFragments()) { + facebook::react::hash_combine( + seed, attributedStringFragmentHashDisplayWise(fragment)); + } + return seed; +} inline bool operator==( const TextMeasureCacheKey& lhs, const TextMeasureCacheKey& rhs) { @@ -36908,11 +37643,6 @@ inline bool operator==( lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.layoutConstraints == rhs.layoutConstraints; } -inline bool operator!=( - const TextMeasureCacheKey& lhs, - const TextMeasureCacheKey& rhs) { - return !(lhs == rhs); -} inline bool operator==( const LineMeasureCacheKey& lhs, const LineMeasureCacheKey& rhs) { @@ -36921,10 +37651,13 @@ inline bool operator==( lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.size == rhs.size; } -inline bool operator!=( - const LineMeasureCacheKey& lhs, - const LineMeasureCacheKey& rhs) { - return !(lhs == rhs); +inline bool operator==( + const PreparedTextCacheKey& lhs, + const PreparedTextCacheKey& rhs) { + return areAttributedStringsEquivalentDisplayWise( + lhs.attributedString, rhs.attributedString) && + lhs.paragraphAttributes == rhs.paragraphAttributes && + lhs.layoutConstraints == rhs.layoutConstraints; } } // namespace facebook::react namespace std { @@ -36946,6 +37679,15 @@ struct hash { key.size); } }; +template <> +struct hash { + size_t operator()(const facebook::react::PreparedTextCacheKey& key) const { + return facebook::react::hash_combine( + attributedStringHashDisplayWise(key.attributedString), + key.paragraphAttributes, + key.layoutConstraints); + } +}; } // namespace std /// @src {packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/JPreparedLayout.h}: @@ -37534,7 +38276,7 @@ class LayoutAnimationStatusDelegate { namespace facebook::react { struct PointerEventTarget { PointerEvent event; - ShadowNode::Shared target; + std::shared_ptr target; }; struct ActivePointer { PointerEvent event; @@ -37554,11 +38296,11 @@ using PointerHoverTrackerRegistry = std::unordered_map; class PointerEventsProcessor final { public: - static ShadowNode::Shared getShadowNodeFromEventTarget( + static std::shared_ptr getShadowNodeFromEventTarget( jsi::Runtime& runtime, const EventTarget* target); void interceptPointerEvent( - const ShadowNode::Shared& target, + const std::shared_ptr& target, const std::string& type, ReactEventPriority priority, const PointerEvent& event, @@ -37566,7 +38308,7 @@ class PointerEventsProcessor final { const UIManager& uiManager); void setPointerCapture( PointerIdentifier pointerId, - const ShadowNode::Shared& shadowNode); + const std::shared_ptr& shadowNode); void releasePointerCapture( PointerIdentifier pointerId, const ShadowNode* shadowNode); @@ -37582,7 +38324,9 @@ class PointerHoverTracker { public: using Unique = std::unique_ptr; using EventPath = std::vector>; - PointerHoverTracker(ShadowNode::Shared target, const UIManager& uiManager); + PointerHoverTracker( + std::shared_ptr target, + const UIManager& uiManager); const ShadowNode* getTarget(const UIManager& uiManager) const; bool hasSameTarget(const PointerHoverTracker& other) const; bool areAnyTargetsListeningToEvents( @@ -37624,7 +38368,7 @@ class UIManager final : public ShadowTreeDelegate { void unregisterCommitHook(UIManagerCommitHook& commitHook); void registerMountHook(UIManagerMountHook& mountHook); void unregisterMountHook(UIManagerMountHook& mountHook); - ShadowNode::Shared getNewestCloneOfShadowNode( + std::shared_ptr getNewestCloneOfShadowNode( const ShadowNode& shadowNode) const; ShadowTreeRevisionConsistencyManager* getShadowTreeRevisionConsistencyManager(); @@ -37660,18 +38404,18 @@ class UIManager final : public ShadowTreeDelegate { const ShadowNode::SharedListOfShared& children, RawProps rawProps) const; void appendChild( - const ShadowNode::Shared& parentShadowNode, - const ShadowNode::Shared& childShadowNode) const; + const std::shared_ptr& parentShadowNode, + const std::shared_ptr& childShadowNode) const; void completeSurface( SurfaceId surfaceId, const ShadowNode::UnsharedListOfShared& rootChildren, ShadowTree::CommitOptions commitOptions); void setIsJSResponder( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) const; - ShadowNode::Shared findNodeAtPoint( - const ShadowNode::Shared& shadowNode, + std::shared_ptr findNodeAtPoint( + const std::shared_ptr& shadowNode, Point point) const; LayoutMetrics getRelativeLayoutMetrics( const ShadowNode& shadowNode, @@ -37679,16 +38423,17 @@ class UIManager final : public ShadowTreeDelegate { LayoutableShadowNode::LayoutInspectingPolicy policy) const; void updateState(const StateUpdate& stateUpdate) const; void dispatchCommand( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& commandName, const folly::dynamic& args) const; void setNativeProps_DEPRECATED( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, RawProps rawProps) const; void sendAccessibilityEvent( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& eventType); - ShadowNode::Shared findShadowNodeByTag_DEPRECATED(Tag tag) const; + std::shared_ptr findShadowNodeByTag_DEPRECATED( + Tag tag) const; const ShadowTreeRegistry& getShadowTreeRegistry() const; void reportMount(SurfaceId surfaceId) const; void updateShadowTree( @@ -37788,19 +38533,21 @@ class UIManagerDelegate { bool mountSynchronously) = 0; virtual void uiManagerDidCreateShadowNode(const ShadowNode& shadowNode) = 0; virtual void uiManagerDidDispatchCommand( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& commandName, const folly::dynamic& args) = 0; virtual void uiManagerDidSendAccessibilityEvent( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, const std::string& eventType) = 0; virtual void uiManagerDidSetIsJSResponder( - const ShadowNode::Shared& shadowNode, + const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) = 0; virtual void uiManagerShouldSynchronouslyUpdateViewOnUIThread( Tag tag, const folly::dynamic& props) = 0; + virtual void uiManagerDidUpdateShadowTree( + const std::unordered_map& tagToProps) = 0; virtual void uiManagerShouldAddEventListener( std::shared_ptr listener) = 0; virtual void uiManagerShouldRemoveEventListener( @@ -37876,7 +38623,7 @@ struct ShadowNodeListWrapper : public jsi::NativeState { }; inline static jsi::Value valueFromShadowNode( jsi::Runtime& runtime, - ShadowNode::Shared shadowNode, + std::shared_ptr shadowNode, bool assignRuntimeShadowNodeReference = false) { auto wrappedShadowNode = std::make_shared(std::move(shadowNode)); @@ -37896,11 +38643,13 @@ inline static ShadowNode::UnsharedListOfShared shadowNodeListFromValue( auto jsArray = std::move(object).asArray(runtime); size_t jsArrayLen = jsArray.length(runtime); if (jsArrayLen > 0) { - auto shadowNodeArray = std::make_shared>>(); + auto shadowNodeArray = + std::make_shared>>(); shadowNodeArray->reserve(jsArrayLen); for (size_t i = 0; i < jsArrayLen; i++) { - shadowNodeArray->push_back(Bridging::fromJs( - runtime, jsArray.getValueAtIndex(runtime, i))); + shadowNodeArray->push_back( + Bridging>::fromJs( + runtime, jsArray.getValueAtIndex(runtime, i))); } return shadowNodeArray; } else { @@ -37924,7 +38673,8 @@ inline static jsi::Value valueFromShadowNodeList( } inline static ShadowNode::UnsharedListOfShared shadowNodeListFromWeakList( const ShadowNode::UnsharedListOfWeak& weakShadowNodeList) { - auto result = std::make_shared>>(); + auto result = + std::make_shared>>(); for (const auto& weakShadowNode : *weakShadowNodeList) { auto sharedShadowNode = weakShadowNode.lock(); if (!sharedShadowNode) { @@ -37938,7 +38688,8 @@ inline static ShadowNode::UnsharedListOfWeak weakShadowNodeListFromValue( jsi::Runtime& runtime, const jsi::Value& value) { auto shadowNodeList = shadowNodeListFromValue(runtime, value); - auto weakShadowNodeList = std::make_shared>>(); + auto weakShadowNodeList = + std::make_shared>>(); for (const auto& shadowNode : *shadowNodeList) { weakShadowNodeList->push_back(shadowNode); } @@ -38925,8 +39676,7 @@ class FuseboxTracer { /// @src {packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h}: /// @dep {packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h} -namespace facebook::react { -namespace BridgeNativeModulePerfLogger { +namespace facebook::react::BridgeNativeModulePerfLogger { void enableLogging(std::unique_ptr&& logger); void disableLogging(); void moduleDataCreateStart(const char* moduleName, int32_t id); @@ -38997,8 +39747,7 @@ void asyncMethodCallExecutionFail( const char* moduleName, const char* methodName, int32_t id); -} // namespace BridgeNativeModulePerfLogger -} // namespace facebook::react +} // namespace facebook::react::BridgeNativeModulePerfLogger /// @src {packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h}: @@ -39010,7 +39759,7 @@ void asyncMethodCallExecutionFail( namespace facebook::react { class NativeModulePerfLogger { public: - virtual ~NativeModulePerfLogger() {} + virtual ~NativeModulePerfLogger() = default; virtual void moduleDataCreateStart(const char* moduleName, int32_t id) = 0; virtual void moduleDataCreateEnd(const char* moduleName, int32_t id) = 0; virtual void moduleCreateStart(const char* moduleName, int32_t id) = 0; @@ -39538,8 +40287,9 @@ inline bool operator==(const YGValue& lhs, const YGValue& rhs) { case YGUnitPoint: case YGUnitPercent: return lhs.value == rhs.value; + default: + return false; } - return false; } inline bool operator!=(const YGValue& lhs, const YGValue& rhs) { return !(lhs == rhs); @@ -41948,8 +42698,10 @@ using DimensionsPayload = NativeDeviceInfoDimensionsPayload< std::optional, std::optional, std::optional>; -using DeviceInfoConstants = - NativeDeviceInfoDeviceInfoConstants>; +using DeviceInfoConstants = NativeDeviceInfoDeviceInfoConstants< + DimensionsPayload, + std::optional, + std::optional>; template <> struct Bridging : NativeDeviceInfoDisplayMetricsBridging {}; @@ -42033,10 +42785,6 @@ class DevLoadingViewModule /// @src {packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.h}: namespace facebook::react { -namespace { -constexpr std::string_view DEFAULT_DEV_SERVER_HOST = "localhost"; -constexpr uint32_t DEFAULT_DEV_SERVER_PORT = 8081; -} // namespace class DevServerHelper { public: enum class DownloadProgressStatus : short { STARTED, FAILED, FINISHED }; @@ -42044,6 +42792,8 @@ class DevServerHelper { DevServerHelper( std::string appId, std::string deviceName, + std::string devServerHost, + uint32_t devServerPort, const HttpClientFactory& httpClientFactory, JavaScriptModuleCallback javaScriptModuleCallback) noexcept; ~DevServerHelper() noexcept = default; @@ -42330,6 +43080,25 @@ using WebSocketClientFactory = WebSocketClientFactory getWebSocketClientFactory(); } // namespace facebook::react +/// @src {packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h}: +namespace facebook::react { +using IImageLoaderOnLoadCallback = std::function< + void(double imageWidth, double imageHeight, const char* errorMessage)>; +class IImageLoader { + public: + enum class CacheStatus { + None = 0, + Disk = 0x1, + Memory = 0x1 << 1, + }; + virtual ~IImageLoader() = default; + virtual void loadImage( + const std::string& uri, + const IImageLoaderOnLoadCallback&& onLoad) = 0; + virtual CacheStatus getCacheStatus(const std::string& uri) = 0; +}; +} // namespace facebook::react + /// @src {packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h}: namespace facebook::react { using ImageSize = NativeImageLoaderAndroidImageSize; @@ -42339,8 +43108,11 @@ struct Bridging class ImageLoaderModule : public NativeImageLoaderAndroidCxxSpec { public: - explicit ImageLoaderModule(std::shared_ptr jsInvoker) - : NativeImageLoaderAndroidCxxSpec(jsInvoker) {} + explicit ImageLoaderModule( + std::shared_ptr jsInvoker, + std::weak_ptr imageLoader = std::weak_ptr()) + : NativeImageLoaderAndroidCxxSpec(jsInvoker), + imageLoader_(std::move(imageLoader)) {} jsi::Object getConstants(jsi::Runtime& rt); void abortRequest(jsi::Runtime& rt, int32_t requestId); AsyncPromise getSize(jsi::Runtime& rt, const std::string& uri); @@ -43723,6 +44495,7 @@ class PropsAnimatedNode final : public AnimatedNode { void update() override; void update(bool forceFabricCommit); }; + Tag connectedViewTag_{animated::undefinedAnimatedNodeIdentifier}; }; } // namespace facebook::react @@ -43785,9 +44558,9 @@ class StyleAnimatedNode final : public AnimatedNode { Tag tag, const folly::dynamic& config, NativeAnimatedNodesManager& manager); - void update() override; - const folly::dynamic& getProps() const noexcept { - return props_; + void collectViewUpdates(folly::dynamic& props); + bool isLayoutStyleUpdated() const noexcept { + return layoutStyleUpdated_; } }; } // namespace facebook::react @@ -43877,8 +44650,7 @@ class TransformAnimatedNode final : public AnimatedNode { Tag tag, const folly::dynamic& config, NativeAnimatedNodesManager& manager); - void update() override; - const folly::dynamic& getProps(); + void collectViewUpdates(folly::dynamic& props); }; } // namespace facebook::react @@ -44018,6 +44790,8 @@ class IMountingManager { virtual void synchronouslyUpdateViewOnUIThread( Tag reactTag, const folly::dynamic& changedProps) {}; + virtual void onUpdateShadowTree( + const std::unordered_map& tagToProps) {}; virtual void initializeAccessibilityManager() {}; virtual void setAccessibilityFocusedView(Tag viewTag) {}; virtual void setFocusedView(Tag viewTag) {}; @@ -44039,6 +44813,9 @@ class IMountingManager { virtual void setEventEmitterListener( std::shared_ptr listener) noexcept {}; virtual void setUIManager(std::weak_ptr uiManager) noexcept {}; + virtual std::shared_ptr getImageLoader() noexcept { + return nullptr; + } }; } // namespace facebook::react @@ -44104,10 +44881,12 @@ struct ReactInstanceConfig { bool enableDebugging{false}; std::string appId; std::string deviceName; + std::string devServerHost{"localhost"}; + uint32_t devServerPort{8081}; }; } // namespace facebook::react -/// @src {packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/PlatformTimerRegistryImpl.h}: +/// @src {packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/react/runtime/PlatformTimerRegistryImpl.h}: namespace facebook::react { class PlatformTimerRegistryImpl : public PlatformTimerRegistry { public: @@ -44241,3 +45020,11 @@ class RunLoopObserverManager void induce() const noexcept; }; } // namespace facebook::react + +/// @src {packages/react-native/scripts/ios-prebuild/React-umbrella.h}: +extern "C" double ReactVersionNumber; +extern "C" const unsigned char ReactVersionString[]; + +/// @src {packages/react-native/scripts/ios-prebuild/React_RCTAppDelegate-umbrella.h}: +extern "C" double React_RCTAppDelegateVersionNumber; +extern "C" const unsigned char React_RCTAppDelegateVersionString[]; From 5fe782a800ac7a17230364df0cad78050c097bb9 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Mon, 7 Jul 2025 15:04:37 -0700 Subject: [PATCH 0016/1383] Move cxx-api scripts under scripts/, add README (#52467) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52467 Moves the WIP `cxx-public-api` project under `scripts/cxx-api/`, add minimal README docs. Changelog: [Internal] Reviewed By: christophpurrer Differential Revision: D77865490 fbshipit-source-id: ce49845386c468ee7422b864c49f2a8c9eed5a70 --- package.json | 2 ++ private/cxx-public-api/package.json | 18 ---------------- scripts/cxx-api/README.md | 21 +++++++++++++++++++ .../cxx-api}/ReactNativeCPP.api | 0 .../cxx-api}/check-api.sh | 4 ++-- .../cxx-api}/public-api.conf | 2 +- .../cxx-api}/public-api.js | 14 ++++++------- 7 files changed, 33 insertions(+), 28 deletions(-) delete mode 100644 private/cxx-public-api/package.json create mode 100644 scripts/cxx-api/README.md rename {private/cxx-public-api => scripts/cxx-api}/ReactNativeCPP.api (100%) rename {private/cxx-public-api => scripts/cxx-api}/check-api.sh (96%) rename {private/cxx-public-api => scripts/cxx-api}/public-api.conf (94%) rename {private/cxx-public-api => scripts/cxx-api}/public-api.js (98%) diff --git a/package.json b/package.json index 84b36a75d70823..e3e8f7be7a63cb 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "build-types": "node ./scripts/build-types", "clang-format": "clang-format -i --glob=*/**/*.{h,cpp,m,mm}", "clean": "node ./scripts/build/clean.js", + "cxx-api-build": "node ./scripts/cxx-api/public-api.js", "flow-check": "flow check", "flow": "flow", "format-check": "prettier --list-different \"./**/*.{js,md,yml,ts,tsx}\"", @@ -82,6 +83,7 @@ "glob": "^7.1.1", "hermes-eslint": "0.29.1", "hermes-transform": "0.29.1", + "ini": "^5.0.0", "inquirer": "^7.1.0", "jest": "^29.7.0", "jest-config": "^29.7.0", diff --git a/private/cxx-public-api/package.json b/private/cxx-public-api/package.json deleted file mode 100644 index 11e3c5cb75eab4..00000000000000 --- a/private/cxx-public-api/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@react-native/cxx-public-api", - "version": "0.0.1", - "description": "Captures the Objective-C / C++ public API of React Native", - "main": "public-api.js", - "files": [ - "check-api.sh", - "public-api.conf", - "public-api.js" - ], - "repository": "https://reactnative.dev/", - "license": "MIT", - "private": true, - "dependencies": { - "glob": "^7.1.1", - "ini": "^5.0.0" - } -} diff --git a/scripts/cxx-api/README.md b/scripts/cxx-api/README.md new file mode 100644 index 00000000000000..c245721dc833d0 --- /dev/null +++ b/scripts/cxx-api/README.md @@ -0,0 +1,21 @@ +# scripts/cxx-api + +[Experimental] Build scripts for React Native's C++ / Objective-C / Objective-C++ API. + +## Usage + +#### Build API snapshot + +Builds a `ReactNativeCPP.api` file to the `output` location configured in `public-api.conf`. + +```sh +yarn cxx-api-build +``` + +#### Check API snapshot + +Prints a warning message with the API snapshot diff since the previous commit. + +```sh +./scripts/cxx-api/check-api.sh +``` diff --git a/private/cxx-public-api/ReactNativeCPP.api b/scripts/cxx-api/ReactNativeCPP.api similarity index 100% rename from private/cxx-public-api/ReactNativeCPP.api rename to scripts/cxx-api/ReactNativeCPP.api diff --git a/private/cxx-public-api/check-api.sh b/scripts/cxx-api/check-api.sh similarity index 96% rename from private/cxx-public-api/check-api.sh rename to scripts/cxx-api/check-api.sh index cb4aaa4ea2bf8f..b0e550d960fa45 100755 --- a/private/cxx-public-api/check-api.sh +++ b/scripts/cxx-api/check-api.sh @@ -73,8 +73,8 @@ pushd "$FBSOURCE_ROOT/xplat/js/react-native-github" || exit $ERR_CODE_CANT_FIND_ trap cleanup EXIT # TODO: This operates in the sandbox and can't modify files in the repository, which we need for change detection -# buck2 run //xplat/js/react-native-github/private/cxx-public-api:public-api -REPO_RELATIVE_DIR="private/cxx-public-api" +# buck2 run //xplat/js/react-native-github/scripts/cxx-api:public-api +REPO_RELATIVE_DIR="scripts/cxx-api" (cd "$REPO_RELATIVE_DIR" && $YARN_BINARY install) $NODE_BINARY "$REPO_RELATIVE_DIR/public-api.js" echo diff --git a/private/cxx-public-api/public-api.conf b/scripts/cxx-api/public-api.conf similarity index 94% rename from private/cxx-public-api/public-api.conf rename to scripts/cxx-api/public-api.conf index 1abb1b3ef23d72..aba91a05099f64 100644 --- a/private/cxx-public-api/public-api.conf +++ b/scripts/cxx-api/public-api.conf @@ -22,6 +22,6 @@ packages/react-native/Libraries/WebSocket/* packages/react-native/Libraries/Wrapper/Example/* [settings] -output=private/cxx-public-api/ReactNativeCPP.api +output=scripts/cxx-api/ReactNativeCPP.api ; clang=$HOME/some/path/to/clang ; clang-format=$HOME/some/path/to/clang-format diff --git a/private/cxx-public-api/public-api.js b/scripts/cxx-api/public-api.js similarity index 98% rename from private/cxx-public-api/public-api.js rename to scripts/cxx-api/public-api.js index 2c7758bb1cd8ab..530d3a072bc12e 100644 --- a/private/cxx-public-api/public-api.js +++ b/scripts/cxx-api/public-api.js @@ -34,13 +34,13 @@ const isTTY = process.stdout.isTTY; /*:: type Config = { - include: string[], - exclude: string[], - settings: { - output: string, - clang?: string, - 'clang-format'?: string, - } + include: string[], + exclude: string[], + settings: { + output: string, + clang?: string, + 'clang-format'?: string, + }, }; type ParsedConfig = { From 918f02dcc3931a0b2931b4c84e9f291b2226c84a Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Mon, 7 Jul 2025 15:04:37 -0700 Subject: [PATCH 0017/1383] Consolidate JS API scripts under scripts/js-api/, update docs (#52469) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52469 Organise `scripts/build-types/` and `scripts/diff-api-snapshot/` into a single grouping `scripts/js-api/` parent dir — matching the newly relocated `scripts/cxx-api/`. Changelog: [Internal] Reviewed By: robhogan Differential Revision: D77865488 fbshipit-source-id: 33754d9275e65c3bda686294f18d855221ec7bff --- .../diff-js-api-breaking-changes/action.yml | 2 +- package.json | 3 +- packages/react-native/ReactNativeApi.d.ts | 4 +-- scripts/{build-types => js-api}/README.md | 30 +++++++++++++++---- .../build-types/buildApiSnapshot.js} | 6 ++-- .../build-types/buildGeneratedTypes.js | 4 +-- scripts/{ => js-api}/build-types/index.js | 6 ++-- .../build-types/resolution/getDependencies.js | 0 .../build-types/resolution/getRequireStack.js | 0 .../resolution/resolveTypeInputFile.js | 2 +- .../build-types/resolution/simpleResolve.js | 4 +-- .../templates/ReactNativeApi.d.ts-template.js | 2 +- .../build-types/templates/api-extractor.json | 0 .../translatedModule.d.ts-template.js | 2 +- .../build-types/templates/tsconfig.json | 0 .../build-types/templates/tsconfig.test.json | 0 .../__tests__/ensureNoUnprefixedProps-test.js | 0 .../__tests__/reattachDocComments-test.js | 0 .../__tests__/replaceEmptyWithNever-test.js | 0 ...aceNullablePropertiesWithUndefined-test.js | 0 .../replaceRequiresWithImports-test.js | 0 .../replaceStringishWithString-test.js | 0 .../__tests__/stripPrivateProperties-test.js | 0 .../flow/ensureNoUnprefixedProps.js | 0 .../transforms/flow/reattachDocComments.js | 0 .../transforms/flow/replaceEmptyWithNever.js | 0 .../replaceNullablePropertiesWithUndefined.js | 0 .../flow/replaceRequiresWithImports.js | 0 .../flow/replaceStringishWithString.js | 0 .../transforms/flow/stripPrivateProperties.js | 0 .../__fixtures__/organizeDeclarations.d.ts | 0 .../__fixtures__/sortProperties.d.ts | 0 .../typescript/__fixtures__/sortUnions.d.ts | 0 .../organizeDeclarations-test.js.snap | 0 .../__snapshots__/sortProperties-test.js.snap | 0 .../__snapshots__/sortUnions-test.js.snap | 0 .../__tests__/inlineTypesVisitor-test.js | 0 .../__tests__/organizeDeclarations-test.js | 0 ...removeUndefinedFromOptionalMembers-test.js | 0 .../renameDefaultExportedIdentifiers-test.js | 0 .../replaceDefaultExportName-test.js | 0 .../__tests__/simplifyTypes-test.js | 0 .../__tests__/sortProperties-test.js | 0 .../typescript/__tests__/sortUnions-test.js | 0 .../__tests__/stripUnstableApis-test.js | 0 .../__tests__/versionExportedApis-test.js | 0 .../typescript/organizeDeclarations.js | 0 .../removeUndefinedFromOptionalMembers.js | 0 .../renameDefaultExportedIdentifiers.js | 0 .../typescript/replaceDefaultExportName.js | 0 .../simplifyTypes/alignTypeParameters.js | 0 .../typescript/simplifyTypes/contextStack.js | 0 .../simplifyTypes/gatherTypeAliasesVisitor.js | 0 .../typescript/simplifyTypes/index.js | 0 .../typescript/simplifyTypes/inlineType.js | 0 .../simplifyTypes/inlineTypesVisitor.js | 0 .../simplifyTypes/resolveBuiltinType.js | 0 .../simplifyTypes/resolveIntersection.js | 0 .../typescript/simplifyTypes/resolveTSType.js | 0 .../simplifyTypes/resolveTypeOperator.js | 0 .../typescript/simplifyTypes/utils.js | 0 .../typescript/simplifyTypes/visitorState.js | 0 .../transforms/typescript/sortProperties.js | 0 .../transforms/typescript/sortUnions.js | 0 .../typescript/stripUnstableApis.js | 0 .../typescript/versionExportedApis.js | 0 .../build-types/translateSourceFile.js | 0 .../resolveCyclicImportsInDefinition-test.js | 0 .../utils/applyBabelTransformsSeq.js | 0 .../utils/resolveCyclicImportsInDefinition.js | 0 scripts/{build-types => js-api}/config.js | 0 .../__tests__/diffApiSnapshot-test.js | 0 .../diff-api-snapshot/diffApiSnapshot.js | 0 .../{ => js-api}/diff-api-snapshot/index.js | 4 +-- 74 files changed, 44 insertions(+), 25 deletions(-) rename scripts/{build-types => js-api}/README.md (72%) rename scripts/{build-types/BuildApiSnapshot.js => js-api/build-types/buildApiSnapshot.js} (98%) rename scripts/{ => js-api}/build-types/buildGeneratedTypes.js (98%) rename scripts/{ => js-api}/build-types/index.js (92%) rename scripts/{ => js-api}/build-types/resolution/getDependencies.js (100%) rename scripts/{ => js-api}/build-types/resolution/getRequireStack.js (100%) rename scripts/{ => js-api}/build-types/resolution/resolveTypeInputFile.js (97%) rename scripts/{ => js-api}/build-types/resolution/simpleResolve.js (94%) rename scripts/{ => js-api}/build-types/templates/ReactNativeApi.d.ts-template.js (94%) rename scripts/{ => js-api}/build-types/templates/api-extractor.json (100%) rename scripts/{ => js-api}/build-types/templates/translatedModule.d.ts-template.js (92%) rename scripts/{ => js-api}/build-types/templates/tsconfig.json (100%) rename scripts/{ => js-api}/build-types/templates/tsconfig.test.json (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/ensureNoUnprefixedProps-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/reattachDocComments-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/replaceEmptyWithNever-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/replaceNullablePropertiesWithUndefined-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/replaceRequiresWithImports-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/replaceStringishWithString-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/__tests__/stripPrivateProperties-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/ensureNoUnprefixedProps.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/reattachDocComments.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/replaceEmptyWithNever.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/replaceNullablePropertiesWithUndefined.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/replaceRequiresWithImports.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/replaceStringishWithString.js (100%) rename scripts/{ => js-api}/build-types/transforms/flow/stripPrivateProperties.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__fixtures__/organizeDeclarations.d.ts (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__fixtures__/sortProperties.d.ts (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__fixtures__/sortUnions.d.ts (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/__snapshots__/organizeDeclarations-test.js.snap (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/__snapshots__/sortProperties-test.js.snap (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/__snapshots__/sortUnions-test.js.snap (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/inlineTypesVisitor-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/organizeDeclarations-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/removeUndefinedFromOptionalMembers-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/renameDefaultExportedIdentifiers-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/replaceDefaultExportName-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/simplifyTypes-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/sortProperties-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/sortUnions-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/stripUnstableApis-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/__tests__/versionExportedApis-test.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/organizeDeclarations.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/removeUndefinedFromOptionalMembers.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/renameDefaultExportedIdentifiers.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/replaceDefaultExportName.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/alignTypeParameters.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/contextStack.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/gatherTypeAliasesVisitor.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/index.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/inlineType.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/inlineTypesVisitor.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/resolveBuiltinType.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/resolveIntersection.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/resolveTSType.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/resolveTypeOperator.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/utils.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/simplifyTypes/visitorState.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/sortProperties.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/sortUnions.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/stripUnstableApis.js (100%) rename scripts/{ => js-api}/build-types/transforms/typescript/versionExportedApis.js (100%) rename scripts/{ => js-api}/build-types/translateSourceFile.js (100%) rename scripts/{ => js-api}/build-types/utils/__tests__/resolveCyclicImportsInDefinition-test.js (100%) rename scripts/{ => js-api}/build-types/utils/applyBabelTransformsSeq.js (100%) rename scripts/{ => js-api}/build-types/utils/resolveCyclicImportsInDefinition.js (100%) rename scripts/{build-types => js-api}/config.js (100%) rename scripts/{ => js-api}/diff-api-snapshot/__tests__/diffApiSnapshot-test.js (100%) rename scripts/{ => js-api}/diff-api-snapshot/diffApiSnapshot.js (100%) rename scripts/{ => js-api}/diff-api-snapshot/index.js (91%) diff --git a/.github/actions/diff-js-api-breaking-changes/action.yml b/.github/actions/diff-js-api-breaking-changes/action.yml index 25ec197ab022b0..bc45b1b207aa83 100644 --- a/.github/actions/diff-js-api-breaking-changes/action.yml +++ b/.github/actions/diff-js-api-breaking-changes/action.yml @@ -17,7 +17,7 @@ runs: env: SCRATCH_DIR: ${{ runner.temp }}/diff-js-api-breaking-changes run: | - node ./scripts/diff-api-snapshot \ + node ./scripts/js-api/diff-api-snapshot \ ${{ github.workspace }}/packages/react-native/ReactNativeApi.d.ts \ $SCRATCH_DIR/ReactNativeApi-after.d.ts \ > $SCRATCH_DIR/output.json diff --git a/package.json b/package.json index e3e8f7be7a63cb..13fa73198a4cbe 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "android": "yarn --cwd packages/rn-tester android", "build-android": "./gradlew :packages:react-native:ReactAndroid:build", "build": "node ./scripts/build/build.js", - "build-types": "node ./scripts/build-types", + "build-types": "node ./scripts/js-api/build-types", "clang-format": "clang-format -i --glob=*/**/*.{h,cpp,m,mm}", "clean": "node ./scripts/build/clean.js", "cxx-api-build": "node ./scripts/cxx-api/public-api.js", @@ -17,6 +17,7 @@ "format-check": "prettier --list-different \"./**/*.{js,md,yml,ts,tsx}\"", "format": "npm run prettier && npm run clang-format", "featureflags": "yarn --cwd packages/react-native featureflags", + "js-api-diff": "node ./scripts/js-api/diff-api-snapshot", "lint-ci": "./.github/workflow-scripts/analyze_code.sh && yarn shellcheck", "lint-markdown": "markdownlint-cli2 2>&1", "lint": "eslint --max-warnings 0 .", diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index c02c6ddd74ff3c..768e0c1f96b38d 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,9 +4,9 @@ * 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<<83d07f37fd6028027511209f02e7f056>> * - * This file was generated by scripts/build-types/index.js. + * This file was generated by scripts/js-api/build-types/index.js. */ // ---------------------------------------------------------------------------- diff --git a/scripts/build-types/README.md b/scripts/js-api/README.md similarity index 72% rename from scripts/build-types/README.md rename to scripts/js-api/README.md index 861938098b15c6..d1ae3e16540b09 100644 --- a/scripts/build-types/README.md +++ b/scripts/js-api/README.md @@ -1,4 +1,4 @@ -# scripts/build-types +# scripts/js-api TypeScript build pipeline for React Native's JavaScript API. @@ -24,9 +24,9 @@ Snapshot file of the public API shape, used by maintainers\ ## Usage -`yarn build-types` is designed to be run by maintainers with minimal arguments. +#### Build generated types + API snapshot -> API snapshot generation is currently **experimental**, and will be folded into the default behaviour when ready. +Maintainers should run this script whenever making intentional API changes. ```sh # Build types + API snapshot @@ -36,11 +36,28 @@ yarn build-types [--validate] yarn build-types --skip-snapshot ``` +#### Diff API snapshot compatibility + +This script is run by CI to compare changes to `ReactNativeApi.d.ts` between commits. + +```sh +# Compare two versions of the API snapshot +yarn js-api-diff +``` +```json +{ + "result": "BREAKING", + "changedApis": [ + "ViewStyle" + ] +} +``` + #### Configuration -Sparse configuration options are defined and documented in `scripts/build-types/config.js`. +Sparse configuration options are defined and documented in `scripts/js-api/config.js`. -## About the two formats +## About the two output formats ### Generated TypeScript types @@ -63,4 +80,5 @@ Provides a human-readable, maintainable reference of the React Native's public J - Committed to the repo. - Strips `unstable_` and `experimental_` APIs. - Strips doc comments. -- Strips source file names and some un-exported type names (WIP). +- Strips source file names (types are merged into a single program). +- Versions exported APIs with an 8 char SHA hash, which will be updated when any input type dependencies change shape. diff --git a/scripts/build-types/BuildApiSnapshot.js b/scripts/js-api/build-types/buildApiSnapshot.js similarity index 98% rename from scripts/build-types/BuildApiSnapshot.js rename to scripts/js-api/build-types/buildApiSnapshot.js index 815f251b125fc1..eb9af6dce8771d 100644 --- a/scripts/build-types/BuildApiSnapshot.js +++ b/scripts/js-api/build-types/buildApiSnapshot.js @@ -11,9 +11,9 @@ import type {PluginObj} from '@babel/core'; -const {PACKAGES_DIR, REACT_NATIVE_PACKAGE_DIR} = require('../consts'); -const {isGitRepo} = require('../scm-utils'); -const {API_EXTRACTOR_CONFIG_FILE, TYPES_OUTPUT_DIR} = require('./config'); +const {PACKAGES_DIR, REACT_NATIVE_PACKAGE_DIR} = require('../../consts'); +const {isGitRepo} = require('../../scm-utils'); +const {API_EXTRACTOR_CONFIG_FILE, TYPES_OUTPUT_DIR} = require('../config'); const apiSnapshotTemplate = require('./templates/ReactNativeApi.d.ts-template.js'); const applyBabelTransformsSeq = require('./utils/applyBabelTransformsSeq'); const resolveCyclicImportsInDefinition = require('./utils/resolveCyclicImportsInDefinition'); diff --git a/scripts/build-types/buildGeneratedTypes.js b/scripts/js-api/build-types/buildGeneratedTypes.js similarity index 98% rename from scripts/build-types/buildGeneratedTypes.js rename to scripts/js-api/build-types/buildGeneratedTypes.js index b0ee9c2cda5a37..404f14c46290ca 100644 --- a/scripts/build-types/buildGeneratedTypes.js +++ b/scripts/js-api/build-types/buildGeneratedTypes.js @@ -8,8 +8,8 @@ * @format */ -const {PACKAGES_DIR, REPO_ROOT} = require('../consts'); -const {ENTRY_POINT, IGNORE_PATTERNS, TYPES_OUTPUT_DIR} = require('./config'); +const {PACKAGES_DIR, REPO_ROOT} = require('../../consts'); +const {ENTRY_POINT, IGNORE_PATTERNS, TYPES_OUTPUT_DIR} = require('../config'); const getRequireStack = require('./resolution/getRequireStack'); const translatedModuleTemplate = require('./templates/translatedModule.d.ts-template'); const translateSourceFile = require('./translateSourceFile'); diff --git a/scripts/build-types/index.js b/scripts/js-api/build-types/index.js similarity index 92% rename from scripts/build-types/index.js rename to scripts/js-api/build-types/index.js index 77b672d2655079..0a99a33bffe0a0 100644 --- a/scripts/build-types/index.js +++ b/scripts/js-api/build-types/index.js @@ -8,9 +8,9 @@ * @format */ -require('../babel-register').registerForScript(); +require('../../babel-register').registerForScript(); -const buildApiSnapshot = require('./BuildApiSnapshot'); +const buildApiSnapshot = require('./buildApiSnapshot'); const buildGeneratedTypes = require('./buildGeneratedTypes'); const debug = require('debug'); const {parseArgs, styleText} = require('util'); @@ -40,7 +40,7 @@ async function main() { if (help) { console.log(` - Usage: node ./scripts/build-types + Usage: node ./scripts/js-api/build-types Build generated TypeScript types for react-native. diff --git a/scripts/build-types/resolution/getDependencies.js b/scripts/js-api/build-types/resolution/getDependencies.js similarity index 100% rename from scripts/build-types/resolution/getDependencies.js rename to scripts/js-api/build-types/resolution/getDependencies.js diff --git a/scripts/build-types/resolution/getRequireStack.js b/scripts/js-api/build-types/resolution/getRequireStack.js similarity index 100% rename from scripts/build-types/resolution/getRequireStack.js rename to scripts/js-api/build-types/resolution/getRequireStack.js diff --git a/scripts/build-types/resolution/resolveTypeInputFile.js b/scripts/js-api/build-types/resolution/resolveTypeInputFile.js similarity index 97% rename from scripts/build-types/resolution/resolveTypeInputFile.js rename to scripts/js-api/build-types/resolution/resolveTypeInputFile.js index 3bbbae3fbecd79..f1237ca5d2d7fb 100644 --- a/scripts/build-types/resolution/resolveTypeInputFile.js +++ b/scripts/js-api/build-types/resolution/resolveTypeInputFile.js @@ -8,7 +8,7 @@ * @format */ -const {REPO_ROOT} = require('../../consts'); +const {REPO_ROOT} = require('../../../consts'); const debug = require('debug')('build-types:resolution'); const fs = require('fs'); const path = require('path'); diff --git a/scripts/build-types/resolution/simpleResolve.js b/scripts/js-api/build-types/resolution/simpleResolve.js similarity index 94% rename from scripts/build-types/resolution/simpleResolve.js rename to scripts/js-api/build-types/resolution/simpleResolve.js index 586a957cf59259..33e748af3aedf3 100644 --- a/scripts/build-types/resolution/simpleResolve.js +++ b/scripts/js-api/build-types/resolution/simpleResolve.js @@ -8,8 +8,8 @@ * @format */ -const {PACKAGES_DIR} = require('../../consts'); -const {getPackages} = require('../../utils/monorepo'); +const {PACKAGES_DIR} = require('../../../consts'); +const {getPackages} = require('../../../utils/monorepo'); const {existsSync} = require('fs'); const path = require('path'); diff --git a/scripts/build-types/templates/ReactNativeApi.d.ts-template.js b/scripts/js-api/build-types/templates/ReactNativeApi.d.ts-template.js similarity index 94% rename from scripts/build-types/templates/ReactNativeApi.d.ts-template.js rename to scripts/js-api/build-types/templates/ReactNativeApi.d.ts-template.js index c848b909bff722..1185d29fb069ad 100644 --- a/scripts/build-types/templates/ReactNativeApi.d.ts-template.js +++ b/scripts/js-api/build-types/templates/ReactNativeApi.d.ts-template.js @@ -20,7 +20,7 @@ function apiSnapshotTemplate(source: string): string { * * ${signedsource.getSigningToken()} * - * This file was generated by scripts/build-types/index.js. + * This file was generated by scripts/js-api/build-types/index.js. */ // ---------------------------------------------------------------------------- diff --git a/scripts/build-types/templates/api-extractor.json b/scripts/js-api/build-types/templates/api-extractor.json similarity index 100% rename from scripts/build-types/templates/api-extractor.json rename to scripts/js-api/build-types/templates/api-extractor.json diff --git a/scripts/build-types/templates/translatedModule.d.ts-template.js b/scripts/js-api/build-types/templates/translatedModule.d.ts-template.js similarity index 92% rename from scripts/build-types/templates/translatedModule.d.ts-template.js rename to scripts/js-api/build-types/templates/translatedModule.d.ts-template.js index 08309839f2622b..7dc0414cace199 100644 --- a/scripts/build-types/templates/translatedModule.d.ts-template.js +++ b/scripts/js-api/build-types/templates/translatedModule.d.ts-template.js @@ -28,7 +28,7 @@ function translatedModuleTemplate({ * * ${signedsource.getSigningToken()} * - * This file was translated from Flow by scripts/build-types/index.js. + * This file was translated from Flow by scripts/js-api/build-types/index.js. * Original file: ${originalFileName} */ ${tripleSlashDirectives.length > 0 ? '\n/// ' + tripleSlashDirectives.join('\n/// ') + '\n\n' : ''}${source} diff --git a/scripts/build-types/templates/tsconfig.json b/scripts/js-api/build-types/templates/tsconfig.json similarity index 100% rename from scripts/build-types/templates/tsconfig.json rename to scripts/js-api/build-types/templates/tsconfig.json diff --git a/scripts/build-types/templates/tsconfig.test.json b/scripts/js-api/build-types/templates/tsconfig.test.json similarity index 100% rename from scripts/build-types/templates/tsconfig.test.json rename to scripts/js-api/build-types/templates/tsconfig.test.json diff --git a/scripts/build-types/transforms/flow/__tests__/ensureNoUnprefixedProps-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/ensureNoUnprefixedProps-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/ensureNoUnprefixedProps-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/ensureNoUnprefixedProps-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/reattachDocComments-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/reattachDocComments-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/reattachDocComments-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/reattachDocComments-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/replaceEmptyWithNever-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/replaceEmptyWithNever-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/replaceEmptyWithNever-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/replaceEmptyWithNever-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/replaceNullablePropertiesWithUndefined-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/replaceNullablePropertiesWithUndefined-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/replaceNullablePropertiesWithUndefined-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/replaceNullablePropertiesWithUndefined-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/replaceRequiresWithImports-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/replaceRequiresWithImports-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/replaceRequiresWithImports-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/replaceRequiresWithImports-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/replaceStringishWithString-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/replaceStringishWithString-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/replaceStringishWithString-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/replaceStringishWithString-test.js diff --git a/scripts/build-types/transforms/flow/__tests__/stripPrivateProperties-test.js b/scripts/js-api/build-types/transforms/flow/__tests__/stripPrivateProperties-test.js similarity index 100% rename from scripts/build-types/transforms/flow/__tests__/stripPrivateProperties-test.js rename to scripts/js-api/build-types/transforms/flow/__tests__/stripPrivateProperties-test.js diff --git a/scripts/build-types/transforms/flow/ensureNoUnprefixedProps.js b/scripts/js-api/build-types/transforms/flow/ensureNoUnprefixedProps.js similarity index 100% rename from scripts/build-types/transforms/flow/ensureNoUnprefixedProps.js rename to scripts/js-api/build-types/transforms/flow/ensureNoUnprefixedProps.js diff --git a/scripts/build-types/transforms/flow/reattachDocComments.js b/scripts/js-api/build-types/transforms/flow/reattachDocComments.js similarity index 100% rename from scripts/build-types/transforms/flow/reattachDocComments.js rename to scripts/js-api/build-types/transforms/flow/reattachDocComments.js diff --git a/scripts/build-types/transforms/flow/replaceEmptyWithNever.js b/scripts/js-api/build-types/transforms/flow/replaceEmptyWithNever.js similarity index 100% rename from scripts/build-types/transforms/flow/replaceEmptyWithNever.js rename to scripts/js-api/build-types/transforms/flow/replaceEmptyWithNever.js diff --git a/scripts/build-types/transforms/flow/replaceNullablePropertiesWithUndefined.js b/scripts/js-api/build-types/transforms/flow/replaceNullablePropertiesWithUndefined.js similarity index 100% rename from scripts/build-types/transforms/flow/replaceNullablePropertiesWithUndefined.js rename to scripts/js-api/build-types/transforms/flow/replaceNullablePropertiesWithUndefined.js diff --git a/scripts/build-types/transforms/flow/replaceRequiresWithImports.js b/scripts/js-api/build-types/transforms/flow/replaceRequiresWithImports.js similarity index 100% rename from scripts/build-types/transforms/flow/replaceRequiresWithImports.js rename to scripts/js-api/build-types/transforms/flow/replaceRequiresWithImports.js diff --git a/scripts/build-types/transforms/flow/replaceStringishWithString.js b/scripts/js-api/build-types/transforms/flow/replaceStringishWithString.js similarity index 100% rename from scripts/build-types/transforms/flow/replaceStringishWithString.js rename to scripts/js-api/build-types/transforms/flow/replaceStringishWithString.js diff --git a/scripts/build-types/transforms/flow/stripPrivateProperties.js b/scripts/js-api/build-types/transforms/flow/stripPrivateProperties.js similarity index 100% rename from scripts/build-types/transforms/flow/stripPrivateProperties.js rename to scripts/js-api/build-types/transforms/flow/stripPrivateProperties.js diff --git a/scripts/build-types/transforms/typescript/__fixtures__/organizeDeclarations.d.ts b/scripts/js-api/build-types/transforms/typescript/__fixtures__/organizeDeclarations.d.ts similarity index 100% rename from scripts/build-types/transforms/typescript/__fixtures__/organizeDeclarations.d.ts rename to scripts/js-api/build-types/transforms/typescript/__fixtures__/organizeDeclarations.d.ts diff --git a/scripts/build-types/transforms/typescript/__fixtures__/sortProperties.d.ts b/scripts/js-api/build-types/transforms/typescript/__fixtures__/sortProperties.d.ts similarity index 100% rename from scripts/build-types/transforms/typescript/__fixtures__/sortProperties.d.ts rename to scripts/js-api/build-types/transforms/typescript/__fixtures__/sortProperties.d.ts diff --git a/scripts/build-types/transforms/typescript/__fixtures__/sortUnions.d.ts b/scripts/js-api/build-types/transforms/typescript/__fixtures__/sortUnions.d.ts similarity index 100% rename from scripts/build-types/transforms/typescript/__fixtures__/sortUnions.d.ts rename to scripts/js-api/build-types/transforms/typescript/__fixtures__/sortUnions.d.ts diff --git a/scripts/build-types/transforms/typescript/__tests__/__snapshots__/organizeDeclarations-test.js.snap b/scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/organizeDeclarations-test.js.snap similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/__snapshots__/organizeDeclarations-test.js.snap rename to scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/organizeDeclarations-test.js.snap diff --git a/scripts/build-types/transforms/typescript/__tests__/__snapshots__/sortProperties-test.js.snap b/scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/sortProperties-test.js.snap similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/__snapshots__/sortProperties-test.js.snap rename to scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/sortProperties-test.js.snap diff --git a/scripts/build-types/transforms/typescript/__tests__/__snapshots__/sortUnions-test.js.snap b/scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/sortUnions-test.js.snap similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/__snapshots__/sortUnions-test.js.snap rename to scripts/js-api/build-types/transforms/typescript/__tests__/__snapshots__/sortUnions-test.js.snap diff --git a/scripts/build-types/transforms/typescript/__tests__/inlineTypesVisitor-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/inlineTypesVisitor-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/inlineTypesVisitor-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/inlineTypesVisitor-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/organizeDeclarations-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/organizeDeclarations-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/organizeDeclarations-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/organizeDeclarations-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/removeUndefinedFromOptionalMembers-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/removeUndefinedFromOptionalMembers-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/removeUndefinedFromOptionalMembers-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/removeUndefinedFromOptionalMembers-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/renameDefaultExportedIdentifiers-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/renameDefaultExportedIdentifiers-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/renameDefaultExportedIdentifiers-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/renameDefaultExportedIdentifiers-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/replaceDefaultExportName-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/replaceDefaultExportName-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/replaceDefaultExportName-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/replaceDefaultExportName-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/simplifyTypes-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/simplifyTypes-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/simplifyTypes-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/simplifyTypes-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/sortProperties-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/sortProperties-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/sortProperties-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/sortProperties-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/sortUnions-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/sortUnions-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/sortUnions-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/sortUnions-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/stripUnstableApis-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/stripUnstableApis-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/stripUnstableApis-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/stripUnstableApis-test.js diff --git a/scripts/build-types/transforms/typescript/__tests__/versionExportedApis-test.js b/scripts/js-api/build-types/transforms/typescript/__tests__/versionExportedApis-test.js similarity index 100% rename from scripts/build-types/transforms/typescript/__tests__/versionExportedApis-test.js rename to scripts/js-api/build-types/transforms/typescript/__tests__/versionExportedApis-test.js diff --git a/scripts/build-types/transforms/typescript/organizeDeclarations.js b/scripts/js-api/build-types/transforms/typescript/organizeDeclarations.js similarity index 100% rename from scripts/build-types/transforms/typescript/organizeDeclarations.js rename to scripts/js-api/build-types/transforms/typescript/organizeDeclarations.js diff --git a/scripts/build-types/transforms/typescript/removeUndefinedFromOptionalMembers.js b/scripts/js-api/build-types/transforms/typescript/removeUndefinedFromOptionalMembers.js similarity index 100% rename from scripts/build-types/transforms/typescript/removeUndefinedFromOptionalMembers.js rename to scripts/js-api/build-types/transforms/typescript/removeUndefinedFromOptionalMembers.js diff --git a/scripts/build-types/transforms/typescript/renameDefaultExportedIdentifiers.js b/scripts/js-api/build-types/transforms/typescript/renameDefaultExportedIdentifiers.js similarity index 100% rename from scripts/build-types/transforms/typescript/renameDefaultExportedIdentifiers.js rename to scripts/js-api/build-types/transforms/typescript/renameDefaultExportedIdentifiers.js diff --git a/scripts/build-types/transforms/typescript/replaceDefaultExportName.js b/scripts/js-api/build-types/transforms/typescript/replaceDefaultExportName.js similarity index 100% rename from scripts/build-types/transforms/typescript/replaceDefaultExportName.js rename to scripts/js-api/build-types/transforms/typescript/replaceDefaultExportName.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/alignTypeParameters.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/alignTypeParameters.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/alignTypeParameters.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/alignTypeParameters.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/contextStack.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/contextStack.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/contextStack.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/contextStack.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/gatherTypeAliasesVisitor.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/gatherTypeAliasesVisitor.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/gatherTypeAliasesVisitor.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/gatherTypeAliasesVisitor.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/index.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/index.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/index.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/index.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/inlineType.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/inlineType.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/inlineType.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/inlineType.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/inlineTypesVisitor.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/inlineTypesVisitor.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/inlineTypesVisitor.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/inlineTypesVisitor.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/resolveBuiltinType.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveBuiltinType.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/resolveBuiltinType.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveBuiltinType.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/resolveIntersection.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveIntersection.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/resolveIntersection.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveIntersection.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/resolveTSType.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveTSType.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/resolveTSType.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveTSType.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/resolveTypeOperator.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveTypeOperator.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/resolveTypeOperator.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/resolveTypeOperator.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/utils.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/utils.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/utils.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/utils.js diff --git a/scripts/build-types/transforms/typescript/simplifyTypes/visitorState.js b/scripts/js-api/build-types/transforms/typescript/simplifyTypes/visitorState.js similarity index 100% rename from scripts/build-types/transforms/typescript/simplifyTypes/visitorState.js rename to scripts/js-api/build-types/transforms/typescript/simplifyTypes/visitorState.js diff --git a/scripts/build-types/transforms/typescript/sortProperties.js b/scripts/js-api/build-types/transforms/typescript/sortProperties.js similarity index 100% rename from scripts/build-types/transforms/typescript/sortProperties.js rename to scripts/js-api/build-types/transforms/typescript/sortProperties.js diff --git a/scripts/build-types/transforms/typescript/sortUnions.js b/scripts/js-api/build-types/transforms/typescript/sortUnions.js similarity index 100% rename from scripts/build-types/transforms/typescript/sortUnions.js rename to scripts/js-api/build-types/transforms/typescript/sortUnions.js diff --git a/scripts/build-types/transforms/typescript/stripUnstableApis.js b/scripts/js-api/build-types/transforms/typescript/stripUnstableApis.js similarity index 100% rename from scripts/build-types/transforms/typescript/stripUnstableApis.js rename to scripts/js-api/build-types/transforms/typescript/stripUnstableApis.js diff --git a/scripts/build-types/transforms/typescript/versionExportedApis.js b/scripts/js-api/build-types/transforms/typescript/versionExportedApis.js similarity index 100% rename from scripts/build-types/transforms/typescript/versionExportedApis.js rename to scripts/js-api/build-types/transforms/typescript/versionExportedApis.js diff --git a/scripts/build-types/translateSourceFile.js b/scripts/js-api/build-types/translateSourceFile.js similarity index 100% rename from scripts/build-types/translateSourceFile.js rename to scripts/js-api/build-types/translateSourceFile.js diff --git a/scripts/build-types/utils/__tests__/resolveCyclicImportsInDefinition-test.js b/scripts/js-api/build-types/utils/__tests__/resolveCyclicImportsInDefinition-test.js similarity index 100% rename from scripts/build-types/utils/__tests__/resolveCyclicImportsInDefinition-test.js rename to scripts/js-api/build-types/utils/__tests__/resolveCyclicImportsInDefinition-test.js diff --git a/scripts/build-types/utils/applyBabelTransformsSeq.js b/scripts/js-api/build-types/utils/applyBabelTransformsSeq.js similarity index 100% rename from scripts/build-types/utils/applyBabelTransformsSeq.js rename to scripts/js-api/build-types/utils/applyBabelTransformsSeq.js diff --git a/scripts/build-types/utils/resolveCyclicImportsInDefinition.js b/scripts/js-api/build-types/utils/resolveCyclicImportsInDefinition.js similarity index 100% rename from scripts/build-types/utils/resolveCyclicImportsInDefinition.js rename to scripts/js-api/build-types/utils/resolveCyclicImportsInDefinition.js diff --git a/scripts/build-types/config.js b/scripts/js-api/config.js similarity index 100% rename from scripts/build-types/config.js rename to scripts/js-api/config.js diff --git a/scripts/diff-api-snapshot/__tests__/diffApiSnapshot-test.js b/scripts/js-api/diff-api-snapshot/__tests__/diffApiSnapshot-test.js similarity index 100% rename from scripts/diff-api-snapshot/__tests__/diffApiSnapshot-test.js rename to scripts/js-api/diff-api-snapshot/__tests__/diffApiSnapshot-test.js diff --git a/scripts/diff-api-snapshot/diffApiSnapshot.js b/scripts/js-api/diff-api-snapshot/diffApiSnapshot.js similarity index 100% rename from scripts/diff-api-snapshot/diffApiSnapshot.js rename to scripts/js-api/diff-api-snapshot/diffApiSnapshot.js diff --git a/scripts/diff-api-snapshot/index.js b/scripts/js-api/diff-api-snapshot/index.js similarity index 91% rename from scripts/diff-api-snapshot/index.js rename to scripts/js-api/diff-api-snapshot/index.js index 478a3bd5c8bfe5..777d281461a5a6 100644 --- a/scripts/diff-api-snapshot/index.js +++ b/scripts/js-api/diff-api-snapshot/index.js @@ -9,7 +9,7 @@ * @oncall react_native */ -require('../babel-register').registerForScript(); +require('../../babel-register').registerForScript(); const {diffApiSnapshot} = require('./diffApiSnapshot'); const fs = require('fs'); @@ -32,7 +32,7 @@ async function main() { if (help) { console.log(` - Usage: node ./scripts/diff-api-snapshot + Usage: node ./scripts/js-api/diff-api-snapshot Analyze changes between two versions of React Native's JavaScript API snapshot (yarn build-types). Returns a JSON object with the following From 5ec8e60581093f6e55f0d9e0a79f6097b5722913 Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Mon, 7 Jul 2025 16:00:13 -0700 Subject: [PATCH 0018/1383] Refactor VirtualView target structure on Android (#52476) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52476 Changelog: [Internal] - Refactor package structure on Android to prepare for experimental VirtualView so that non-view related objects go under `virtual` and the native view goes under `view`. This breaks dependency circles for experimental VirtualView in upcoming change. Reviewed By: yungsters Differential Revision: D77335426 fbshipit-source-id: 3b978e9cc5ad376c71aebc039cfc74d2515d2cfa --- .../react/views/{virtualview => virtual}/VirtualViewMode.kt | 2 +- .../{virtualview => virtual}/VirtualViewModeChangeEvent.kt | 2 +- .../views/{virtualview => virtual}/VirtualViewRenderState.kt | 2 +- .../views/{virtualview => virtual/view}/ReactVirtualView.kt | 4 +++- .../{virtualview => virtual/view}/ReactVirtualViewManager.kt | 5 ++++- .../{virtualview => virtual/view}/ReactVirtualViewTest.kt | 4 +++- 6 files changed, 13 insertions(+), 6 deletions(-) rename packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/{virtualview => virtual}/VirtualViewMode.kt (86%) rename packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/{virtualview => virtual}/VirtualViewModeChangeEvent.kt (97%) rename packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/{virtualview => virtual}/VirtualViewRenderState.kt (92%) rename packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/{virtualview => virtual/view}/ReactVirtualView.kt (98%) rename packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/{virtualview => virtual/view}/ReactVirtualViewManager.kt (93%) rename packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/{virtualview => virtual/view}/ReactVirtualViewTest.kt (96%) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewMode.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewMode.kt similarity index 86% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewMode.kt rename to packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewMode.kt index a308688917b830..37a2e360657dd9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewMode.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewMode.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual internal enum class VirtualViewMode(val value: Int) { Visible(0), diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewModeChangeEvent.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewModeChangeEvent.kt similarity index 97% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewModeChangeEvent.kt rename to packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewModeChangeEvent.kt index 4244b3b82031d5..fd644ef48bf7ff 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewModeChangeEvent.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewModeChangeEvent.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual import android.graphics.Rect import androidx.annotation.VisibleForTesting diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewRenderState.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewRenderState.kt similarity index 92% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewRenderState.kt rename to packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewRenderState.kt index aa7ad65d5e27dd..0b3804a27af249 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/VirtualViewRenderState.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/VirtualViewRenderState.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual /** * Represents the the render state of children in the most recent commit. diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualView.kt similarity index 98% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualView.kt rename to packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualView.kt index 7a0d4d1f8983ab..a5def80009e1e0 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualView.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual.view import android.content.Context import android.graphics.Rect @@ -24,6 +24,8 @@ import com.facebook.react.views.scroll.ReactScrollView import com.facebook.react.views.scroll.ReactScrollViewHelper import com.facebook.react.views.scroll.ScrollEventType import com.facebook.react.views.view.ReactViewGroup +import com.facebook.react.views.virtual.VirtualViewMode +import com.facebook.react.views.virtual.VirtualViewRenderState import com.facebook.systrace.Systrace internal class ReactVirtualView(context: Context) : diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualViewManager.kt similarity index 93% rename from packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualViewManager.kt rename to packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualViewManager.kt index 9c9e2219d85667..585748f0c4e307 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtualview/ReactVirtualViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/view/ReactVirtualViewManager.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual.view import android.graphics.Rect import androidx.annotation.VisibleForTesting @@ -19,6 +19,9 @@ import com.facebook.react.uimanager.annotations.ReactProp import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.viewmanagers.VirtualViewManagerDelegate import com.facebook.react.viewmanagers.VirtualViewManagerInterface +import com.facebook.react.views.virtual.VirtualViewMode +import com.facebook.react.views.virtual.VirtualViewModeChangeEvent +import com.facebook.react.views.virtual.VirtualViewRenderState @ReactModule(name = ReactVirtualViewManager.REACT_CLASS) internal class ReactVirtualViewManager : diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtualview/ReactVirtualViewTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt similarity index 96% rename from packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtualview/ReactVirtualViewTest.kt rename to packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt index 0114d8afa72be1..34f39ee251a766 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtualview/ReactVirtualViewTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -package com.facebook.react.views.virtualview +package com.facebook.react.views.virtual.view import android.app.Activity import android.content.Context @@ -19,6 +19,8 @@ import com.facebook.react.uimanager.DisplayMetricsHolder import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.views.scroll.ReactScrollView +import com.facebook.react.views.virtual.VirtualViewMode +import com.facebook.react.views.virtual.VirtualViewModeChangeEvent import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test From 68650badd26c4a421814e3d1eee8f882aea50938 Mon Sep 17 00:00:00 2001 From: Marco Wang Date: Mon, 7 Jul 2025 20:35:08 -0700 Subject: [PATCH 0019/1383] Pre-suppress errors for null_void for xplat js (#52480) Summary: Changelog: [Internal] Pull Request resolved: https://github.com/facebook/react-native/pull/52480 Reviewed By: SamChou19815 Differential Revision: D77890434 fbshipit-source-id: cc0571e0ff1c7cec3fff8614f688d46e46970cc4 --- .../react-native/Libraries/StyleSheet/processAspectRatio.js | 2 ++ packages/rn-tester/js/examples/Touchable/TouchableExample.js | 4 +++- .../js/examples/TurboModule/SampleLegacyModuleExample.js | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/react-native/Libraries/StyleSheet/processAspectRatio.js b/packages/react-native/Libraries/StyleSheet/processAspectRatio.js index ec279d35775800..2243ae4f1ca599 100644 --- a/packages/react-native/Libraries/StyleSheet/processAspectRatio.js +++ b/packages/react-native/Libraries/StyleSheet/processAspectRatio.js @@ -19,6 +19,8 @@ function processAspectRatio(aspectRatio?: number | string): ?number { if (typeof aspectRatio !== 'string') { if (__DEV__) { invariant( + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ !aspectRatio, 'aspectRatio must either be a number, a ratio string or `auto`. You passed: %s', aspectRatio, diff --git a/packages/rn-tester/js/examples/Touchable/TouchableExample.js b/packages/rn-tester/js/examples/Touchable/TouchableExample.js index c36c53bdd882fe..3364e243247735 100644 --- a/packages/rn-tester/js/examples/Touchable/TouchableExample.js +++ b/packages/rn-tester/js/examples/Touchable/TouchableExample.js @@ -572,7 +572,9 @@ function TouchableOnFocus() { const toggleFocus = () => { isFocused ? setFocusStatus('This touchable is focused') - : setIsFocused('This touchable is not focused') && + : /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ + setIsFocused('This touchable is not focused') && setIsBlurred('This item has lost focus, onBlur called'); }; const focusTouchable = () => { diff --git a/packages/rn-tester/js/examples/TurboModule/SampleLegacyModuleExample.js b/packages/rn-tester/js/examples/TurboModule/SampleLegacyModuleExample.js index 30244914da841c..876c03da3a1e61 100644 --- a/packages/rn-tester/js/examples/TurboModule/SampleLegacyModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/SampleLegacyModuleExample.js @@ -52,10 +52,14 @@ function getSampleLegacyModule() { function stringify(obj: mixed): string { function replacer(_: string, value: mixed) { if (value instanceof Object && !(value instanceof Array)) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ return Object.keys(value ?? {}) .sort() .reduce((sorted: {[key: string]: mixed}, key: string) => { // $FlowFixMe[invalid-computed-prop] + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ sorted[key] = (value ?? {})[key]; return sorted; }, {}); From 5cf4d0899f53c96c29a53381a6788c9961ae82ef Mon Sep 17 00:00:00 2001 From: Vitali Zaidman Date: Tue, 8 Jul 2025 04:15:32 -0700 Subject: [PATCH 0020/1383] Update debugger-frontend from 51a91a2...844f225 (#52486) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52486 Changelog: [Internal] - Update `react-native/debugger-frontend` from 51a91a2...844f225 Resyncs `react-native/debugger-frontend` from GitHub - see `rn-chrome-devtools-frontend` [changelog](https://github.com/facebook/react-native-devtools-frontend/compare/51a91a2ad62e7f585912ed314a350a72de84d6ed...844f225009e6445d088ed0e431d1fc430325ed95). ### Changelog | Commit | Author | Date/Time | Subject | | ------ | ------ | --------- | ------- | | [844f22500](https://github.com/facebook/react-native-devtools-frontend/commit/844f22500) | Vitali Zaidman (vzaidman@gmail.com) | 2025-07-08T10:16:09+01:00 | [Track when the stack trace symbolication succeeds (#187)](https://github.com/facebook/react-native-devtools-frontend/commit/844f22500) | | [ffa6bb6af](https://github.com/facebook/react-native-devtools-frontend/commit/ffa6bb6af) | Vitali Zaidman (vzaidman@gmail.com) | 2025-07-07T16:21:55+01:00 | [parse "empty url" and "address at" frames as non-hyperlinked text (#188)](https://github.com/facebook/react-native-devtools-frontend/commit/ffa6bb6af) | Reviewed By: robhogan Differential Revision: D77926362 fbshipit-source-id: cbcf8b17cd175400d3d027ce2e8ebefa497f5d79 --- packages/debugger-frontend/BUILD_INFO | 4 ++-- .../dist/third-party/front_end/core/host/host.js | 2 +- .../dist/third-party/front_end/panels/console/console.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/debugger-frontend/BUILD_INFO b/packages/debugger-frontend/BUILD_INFO index 4b9c8dc6343216..8987138442a81f 100644 --- a/packages/debugger-frontend/BUILD_INFO +++ b/packages/debugger-frontend/BUILD_INFO @@ -1,5 +1,5 @@ -@generated SignedSource<<8c4db6a5e1ba269169ac93cc53f95538>> -Git revision: 51a91a2ad62e7f585912ed314a350a72de84d6ed +@generated SignedSource<<1ce3fb7dd23581737fedaf58528fe575>> +Git revision: 844f225009e6445d088ed0e431d1fc430325ed95 Built with --nohooks: false Is local checkout: false Remote URL: https://github.com/facebook/react-native-devtools-frontend diff --git a/packages/debugger-frontend/dist/third-party/front_end/core/host/host.js b/packages/debugger-frontend/dist/third-party/front_end/core/host/host.js index fb08d9e00c62d8..02fff73a5142d8 100644 --- a/packages/debugger-frontend/dist/third-party/front_end/core/host/host.js +++ b/packages/debugger-frontend/dist/third-party/front_end/core/host/host.js @@ -1 +1 @@ -import*as e from"../common/common.js";import*as r from"../root/root.js";import*as t from"../i18n/i18n.js";import*as n from"../platform/platform.js";var o;!function(e){e.AppendedToURL="appendedToURL",e.CanceledSaveURL="canceledSaveURL",e.ColorThemeChanged="colorThemeChanged",e.ContextMenuCleared="contextMenuCleared",e.ContextMenuItemSelected="contextMenuItemSelected",e.DeviceCountUpdated="deviceCountUpdated",e.DevicesDiscoveryConfigChanged="devicesDiscoveryConfigChanged",e.DevicesPortForwardingStatusChanged="devicesPortForwardingStatusChanged",e.DevicesUpdated="devicesUpdated",e.DispatchMessage="dispatchMessage",e.DispatchMessageChunk="dispatchMessageChunk",e.EnterInspectElementMode="enterInspectElementMode",e.EyeDropperPickedColor="eyeDropperPickedColor",e.FileSystemsLoaded="fileSystemsLoaded",e.FileSystemRemoved="fileSystemRemoved",e.FileSystemAdded="fileSystemAdded",e.FileSystemFilesChangedAddedRemoved="FileSystemFilesChangedAddedRemoved",e.IndexingTotalWorkCalculated="indexingTotalWorkCalculated",e.IndexingWorked="indexingWorked",e.IndexingDone="indexingDone",e.KeyEventUnhandled="keyEventUnhandled",e.ReloadInspectedPage="reloadInspectedPage",e.RevealSourceLine="revealSourceLine",e.SavedURL="savedURL",e.SearchCompleted="searchCompleted",e.SetInspectedTabId="setInspectedTabId",e.SetUseSoftMenu="setUseSoftMenu",e.ShowPanel="showPanel"}(o||(o={}));const s=[[o.AppendedToURL,"appendedToURL",["url"]],[o.CanceledSaveURL,"canceledSaveURL",["url"]],[o.ColorThemeChanged,"colorThemeChanged",[]],[o.ContextMenuCleared,"contextMenuCleared",[]],[o.ContextMenuItemSelected,"contextMenuItemSelected",["id"]],[o.DeviceCountUpdated,"deviceCountUpdated",["count"]],[o.DevicesDiscoveryConfigChanged,"devicesDiscoveryConfigChanged",["config"]],[o.DevicesPortForwardingStatusChanged,"devicesPortForwardingStatusChanged",["status"]],[o.DevicesUpdated,"devicesUpdated",["devices"]],[o.DispatchMessage,"dispatchMessage",["messageObject"]],[o.DispatchMessageChunk,"dispatchMessageChunk",["messageChunk","messageSize"]],[o.EnterInspectElementMode,"enterInspectElementMode",[]],[o.EyeDropperPickedColor,"eyeDropperPickedColor",["color"]],[o.FileSystemsLoaded,"fileSystemsLoaded",["fileSystems"]],[o.FileSystemRemoved,"fileSystemRemoved",["fileSystemPath"]],[o.FileSystemAdded,"fileSystemAdded",["errorMessage","fileSystem"]],[o.FileSystemFilesChangedAddedRemoved,"fileSystemFilesChangedAddedRemoved",["changed","added","removed"]],[o.IndexingTotalWorkCalculated,"indexingTotalWorkCalculated",["requestId","fileSystemPath","totalWork"]],[o.IndexingWorked,"indexingWorked",["requestId","fileSystemPath","worked"]],[o.IndexingDone,"indexingDone",["requestId","fileSystemPath"]],[o.KeyEventUnhandled,"keyEventUnhandled",["event"]],[o.ReloadInspectedPage,"reloadInspectedPage",["hard"]],[o.RevealSourceLine,"revealSourceLine",["url","lineNumber","columnNumber"]],[o.SavedURL,"savedURL",["url","fileSystemPath"]],[o.SearchCompleted,"searchCompleted",["requestId","fileSystemPath","files"]],[o.SetInspectedTabId,"setInspectedTabId",["tabId"]],[o.SetUseSoftMenu,"setUseSoftMenu",["useSoftMenu"]],[o.ShowPanel,"showPanel",["panelName"]]];var i=Object.freeze({__proto__:null,EventDescriptors:s,get Events(){return o}});const a={systemError:"System error",connectionError:"Connection error",certificateError:"Certificate error",httpError:"HTTP error",cacheError:"Cache error",signedExchangeError:"Signed Exchange error",ftpError:"FTP error",certificateManagerError:"Certificate manager error",dnsResolverError:"DNS resolver error",unknownError:"Unknown error",httpErrorStatusCodeSS:"HTTP error: status code {PH1}, {PH2}",invalidUrl:"Invalid URL",decodingDataUrlFailed:"Decoding Data URL failed"},d=t.i18n.registerUIStrings("core/host/ResourceLoader.ts",a),c=t.i18n.getLocalizedString.bind(void 0,d);let l=0;const u={},g=function(e){return u[++l]=e,l},m=function(e){u[e].close(),delete u[e]},p=function(e,r){u[e].write(r)};function h(e,r,t){if(void 0===e||void 0===t)return null;if(0!==e){if(function(e){return e<=-300&&e>-400}(e))return c(a.httpErrorStatusCodeSS,{PH1:String(r),PH2:t});const n=function(e){return c(e>-100?a.systemError:e>-200?a.connectionError:e>-300?a.certificateError:e>-400?a.httpError:e>-500?a.cacheError:e>-600?a.signedExchangeError:e>-700?a.ftpError:e>-800?a.certificateManagerError:e>-900?a.dnsResolverError:a.unknownError)}(e);return`${n}: ${t}`}return null}const S=function(r,t,n,o,s){const i=g(n);if(new e.ParsedURL.ParsedURL(r).isDataURL())return void(e=>new Promise(((r,t)=>{const n=new XMLHttpRequest;n.withCredentials=!1,n.open("GET",e,!0),n.onreadystatechange=function(){if(n.readyState===XMLHttpRequest.DONE){if(200!==n.status)return n.onreadystatechange=null,void t(new Error(String(n.status)));n.onreadystatechange=null,r(n.responseText)}},n.send(null)})))(r).then((function(e){p(i,e),l({statusCode:200})})).catch((function(e){l({statusCode:404,messageOverride:c(a.decodingDataUrlFailed)})}));if(!s&&function(e){try{const r=new URL(e);return"file:"===r.protocol&&""!==r.host}catch{return!1}}(r))return void(o&&o(!1,{},{statusCode:400,netError:-20,netErrorName:"net::BLOCKED_BY_CLIENT",message:"Loading from a remote file path is prohibited for security reasons."}));const d=[];if(t)for(const e in t)d.push(e+": "+t[e]);function l(e){if(o){const{success:r,description:t}=function(e){const{statusCode:r,netError:t,netErrorName:n,urlValid:o,messageOverride:s}=e;let i="";const d=r>=200&&r<300;if("string"==typeof s)i=s;else if(!d)if(void 0===t)i=c(!1===o?a.invalidUrl:a.unknownError);else{const e=h(t,r,n);e&&(i=e)}return console.assert(d===(0===i.length)),{success:d,description:{statusCode:r,netError:t,netErrorName:n,urlValid:o,message:i}}}(e);o(r,e.headers||{},t)}m(i)}E.loadNetworkResource(r,d.join("\r\n"),i,l)};var v=Object.freeze({__proto__:null,ResourceLoader:{},bindOutputStream:g,discardOutputStream:m,load:function(r,t,n,o){const s=new e.StringOutputStream.StringOutputStream;S(r,t,s,(function(e,r,t){n(e,r,s.data(),t)}),o)},loadAsStream:S,netErrorToMessage:h,streamWrite:p});const C={devtoolsS:"DevTools - {PH1}"},I=t.i18n.registerUIStrings("core/host/InspectorFrontendHost.ts",C),w=t.i18n.getLocalizedString.bind(void 0,I),k="/overrides";class f{#e=new Map;events;#r=null;recordedCountHistograms=[];recordedEnumeratedHistograms=[];recordedPerformanceHistograms=[];constructor(){function e(e){!("mac"===this.platform()?e.metaKey:e.ctrlKey)||"+"!==e.key&&"-"!==e.key||e.stopPropagation()}"undefined"!=typeof document&&document.addEventListener("keydown",(r=>{e.call(this,r)}),!0)}platform(){const e=navigator.userAgent;return e.includes("Windows NT")?"windows":e.includes("Mac OS X")?"mac":"linux"}loadCompleted(){}bringToFront(){}closeWindow(){}setIsDocked(e,r){window.setTimeout(r,0)}showSurvey(e,r){window.setTimeout((()=>r({surveyShown:!1})),0)}canShowSurvey(e,r){window.setTimeout((()=>r({canShowSurvey:!1})),0)}setInspectedPageBounds(e){}inspectElementCompleted(){}setInjectedScriptForOrigin(e,r){}inspectedURLChanged(e){document.title=w(C.devtoolsS,{PH1:e.replace(/^https?:\/\//,"")})}copyText(e){null!=e&&navigator.clipboard.writeText(e)}openInNewTab(r){e.ParsedURL.schemeIs(r,"javascript:")||window.open(r,"_blank")}openSearchResultsInNewTab(r){e.Console.Console.instance().error("Search is not enabled in hosted mode. Please inspect using chrome://inspect")}showItemInFolder(r){e.Console.Console.instance().error("Show item in folder is not enabled in hosted mode. Please inspect using chrome://inspect")}save(e,r,t,n){let s=this.#e.get(e);s||(s=[],this.#e.set(e,s)),s.push(r),this.events.dispatchEventToListeners(o.SavedURL,{url:e,fileSystemPath:e})}append(e,r){const t=this.#e.get(e);t&&(t.push(r),this.events.dispatchEventToListeners(o.AppendedToURL,e))}close(e){const r=this.#e.get(e)||[];this.#e.delete(e);let t="";if(e)try{const r=n.StringUtilities.trimURL(e);t=n.StringUtilities.removeURLFragment(r)}catch(r){t=e}const o=document.createElement("a");o.download=t;const s=new Blob([r.join("")],{type:"text/plain"}),i=URL.createObjectURL(s);o.href=i,o.click(),URL.revokeObjectURL(i)}sendMessageToBackend(e){}recordCountHistogram(e,r,t,n,o){this.recordedCountHistograms.length>=100&&this.recordedCountHistograms.shift(),this.recordedCountHistograms.push({histogramName:e,sample:r,min:t,exclusiveMax:n,bucketSize:o})}recordEnumeratedHistogram(e,r,t){this.recordedEnumeratedHistograms.length>=100&&this.recordedEnumeratedHistograms.shift(),this.recordedEnumeratedHistograms.push({actionName:e,actionCode:r})}recordPerformanceHistogram(e,r){this.recordedPerformanceHistograms.length>=100&&this.recordedPerformanceHistograms.shift(),this.recordedPerformanceHistograms.push({histogramName:e,duration:r})}recordUserMetricsAction(e){}connectAutomaticFileSystem(e,r,t,n){queueMicrotask((()=>n({success:!1})))}disconnectAutomaticFileSystem(e){}requestFileSystems(){this.events.dispatchEventToListeners(o.FileSystemsLoaded,[])}addFileSystem(e){window.webkitRequestFileSystem(window.TEMPORARY,1048576,(e=>{this.#r=e;const r={fileSystemName:"sandboxedRequestedFileSystem",fileSystemPath:k,rootURL:"filesystem:devtools://devtools/isolated/",type:"overrides"};this.events.dispatchEventToListeners(o.FileSystemAdded,{fileSystem:r})}))}removeFileSystem(e){const r=e=>{e.forEach((e=>{e.isDirectory?e.removeRecursively((()=>{})):e.isFile&&e.remove((()=>{}))}))};this.#r&&this.#r.root.createReader().readEntries(r),this.#r=null,this.events.dispatchEventToListeners(o.FileSystemRemoved,k)}isolatedFileSystem(e,r){return this.#r}loadNetworkResource(e,r,t,n){fetch(e).then((async e=>{const r=await e.arrayBuffer();let t=r;if(function(e){const r=new Uint8Array(e);return!(!r||r.length<3)&&31===r[0]&&139===r[1]&&8===r[2]}(r)){const e=new DecompressionStream("gzip"),n=e.writable.getWriter();n.write(r),n.close(),t=e.readable}return await new Response(t).text()})).then((function(e){p(t,e),n({statusCode:200,headers:void 0,messageOverride:void 0,netError:void 0,netErrorName:void 0,urlValid:void 0})})).catch((function(){n({statusCode:404,headers:void 0,messageOverride:void 0,netError:void 0,netErrorName:void 0,urlValid:void 0})}))}registerPreference(e,r){}getPreferences(e){const r={};for(const e in window.localStorage)r[e]=window.localStorage[e];e(r)}getPreference(e,r){r(window.localStorage[e])}setPreference(e,r){window.localStorage[e]=r}removePreference(e){delete window.localStorage[e]}clearPreferences(){window.localStorage.clear()}getSyncInformation(e){if("getSyncInformationForTesting"in globalThis)return e(globalThis.getSyncInformationForTesting());e({isSyncActive:!1,arePreferencesSynced:!1})}getHostConfig(e){const r={devToolsVeLogging:{enabled:!0},thirdPartyCookieControls:{thirdPartyCookieMetadataEnabled:!0,thirdPartyCookieHeuristicsEnabled:!0,managedBlockThirdPartyCookies:"Unset"}};if("hostConfigForTesting"in globalThis){const{hostConfigForTesting:e}=globalThis;for(const t of Object.keys(e)){const n=t=>{"object"==typeof r[t]&&"object"==typeof e[t]?r[t]={...r[t],...e[t]}:r[t]=e[t]??r[t]};n(t)}}e(r)}upgradeDraggedFileSystemPermissions(e){}indexPath(e,r,t){}stopIndexing(e){}searchInPath(e,r,t){}zoomFactor(){return 1}zoomIn(){}zoomOut(){}resetZoom(){}setWhitelistedShortcuts(e){}setEyeDropperActive(e){}showCertificateViewer(e){}reattach(e){e()}readyForTest(){}connectionReady(){}setOpenNewWindowForPopups(e){}setDevicesDiscoveryConfig(e){}setDevicesUpdatesEnabled(e){}openRemotePage(e,r){}openNodeFrontend(){}showContextMenuAtPoint(e,r,t,n){throw new Error("Soft context menu should be used")}isHostedMode(){return!0}setAddExtensionCallback(e){}async initialTargetId(){return null}doAidaConversation(e,r,t){t({error:"Not implemented"})}registerAidaClientEvent(e,r){r({error:"Not implemented"})}recordImpression(e){}recordResize(e){}recordClick(e){}recordHover(e){}recordDrag(e){}recordChange(e){}recordKeyDown(e){}recordSettingAccess(e){}}let E=globalThis.InspectorFrontendHost;class y{constructor(){for(const e of s)this[e[1]]=this.dispatch.bind(this,e[0],e[2],e[3])}dispatch(e,r,t,...n){if(r.length<2){try{E.events.dispatchEventToListeners(e,n[0])}catch(e){console.error(e+" "+e.stack)}return}const o={};for(let e=0;e=0&&(o.options??={},o.options.temperature=i),s&&(o.options??={},o.options.model_id=s),o}static async checkAccessPreconditions(){if(!navigator.onLine)return"no-internet";const e=await new Promise((e=>E.getSyncInformation((r=>e(r)))));return e.accountEmail?e.isSyncPaused?"sync-is-paused":"available":"no-account-email"}async*fetch(e,r){if(!E.doAidaConversation)throw new Error("doAidaConversation is not available");const t=(()=>{let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return r?.signal?.addEventListener("abort",(()=>{n(new O)}),{once:!0}),{write:async r=>{t(r),({promise:e,resolve:t,reject:n}=Promise.withResolvers())},close:async()=>{t(null)},read:()=>e,fail:e=>n(e)}})(),n=g(t);let o;E.doAidaConversation(JSON.stringify(e),n,(e=>{403===e.statusCode?t.fail(new Error("Server responded: permission denied")):e.error?t.fail(new Error(`Cannot send request: ${e.error} ${e.detail||""}`)):"net::ERR_TIMED_OUT"===e.netErrorName?t.fail(new Error("doAidaConversation timed out")):200!==e.statusCode?t.fail(new Error(`Request failed: ${JSON.stringify(e)}`)):t.close()}));const s=[];let i=!1;const a=[];let d={rpcGlobalId:0};for(;o=await t.read();){let e,r=!1;if(o.length){o.startsWith(",")&&(o=o.slice(1)),o.startsWith("[")||(o="["+o),o.endsWith("]")||(o+="]");try{e=JSON.parse(o)}catch(e){throw new Error("Cannot parse chunk: "+o,{cause:e})}for(const t of e){if("metadata"in t&&(d=t.metadata,d?.attributionMetadata?.attributionAction===T.BLOCK))throw new L;if("textChunk"in t)i&&(s.push(_),i=!1),s.push(t.textChunk.text),r=!0;else if("codeChunk"in t)i||(s.push(_),i=!0),s.push(t.codeChunk.code),r=!0;else{if(!("functionCallChunk"in t))throw"error"in t?new Error(`Server responded: ${JSON.stringify(t)}`):new Error("Unknown chunk result");a.push({name:t.functionCallChunk.functionCall.name,args:t.functionCallChunk.functionCall.args})}}r&&(yield{explanation:s.join("")+(i?_:""),metadata:d,completed:!1})}}yield{explanation:s.join("")+(i?_:""),metadata:d,functionCalls:a.length?a:void 0,completed:!0}}registerClientEvent(e){const{promise:r,resolve:t}=Promise.withResolvers();return E.registerAidaClientEvent(JSON.stringify({client:F,event_time:(new Date).toISOString(),...e}),t),r}}let D;class H extends e.ObjectWrapper.ObjectWrapper{#t;#n;constructor(){super()}static instance(){return D||(D=new H),D}addEventListener(e,r){const t=!this.hasEventListeners(e),n=super.addEventListener(e,r);return t&&(window.clearTimeout(this.#t),this.pollAidaAvailability()),n}removeEventListener(e,r){super.removeEventListener(e,r),this.hasEventListeners(e)||window.clearTimeout(this.#t)}async pollAidaAvailability(){this.#t=window.setTimeout((()=>this.pollAidaAvailability()),2e3);const e=await N.checkAccessPreconditions();if(e!==this.#n){this.#n=e;const t=await new Promise((e=>E.getHostConfig(e)));Object.assign(r.Runtime.hostConfig,t),this.dispatchEventToListeners("aidaAvailabilityChanged")}}}var U=Object.freeze({__proto__:null,AidaAbortError:O,AidaBlockError:L,AidaClient:N,CLIENT_NAME:F,get CitationSourceType(){return x},get ClientFeature(){return P},get FunctionalityType(){return A},HostConfigTracker:H,get RecitationAction(){return T},get Role(){return b},get UserTier(){return R},convertToUserTierEnum:function(e){if(e)switch(e){case"TESTERS":return R.TESTERS;case"BETA":return R.BETA;case"PUBLIC":return R.PUBLIC}return R.BETA}});let W,B,V,G,j;function q(){return W||(W=E.platform()),W}var X=Object.freeze({__proto__:null,fontFamily:function(){if(j)return j;switch(q()){case"linux":j="Roboto, Ubuntu, Arial, sans-serif";break;case"mac":j="'Lucida Grande', sans-serif";break;case"windows":j="'Segoe UI', Tahoma, sans-serif"}return j},isCustomDevtoolsFrontend:function(){return void 0===G&&(G=window.location.toString().startsWith("devtools://devtools/custom/")),G},isMac:function(){return void 0===B&&(B="mac"===q()),B},isWin:function(){return void 0===V&&(V="windows"===q()),V},platform:q,setPlatformForTests:function(e){W=e,B=void 0,V=void 0}});let z=null;function K(){return null===z&&(z=new $),z}class ${#o="error";#s=new Set;#i=null;#a=null;#d="rn_inspector";#c={};#l=new Map;addEventListener(e){this.#s.add(e);return()=>{this.#s.delete(e)}}removeAllEventListeners(){this.#s.clear()}sendEvent(e){if(!0!==globalThis.enableReactNativePerfMetrics)return;const r=this.#u(e),t=[];for(const e of this.#s)try{e(r)}catch(e){t.push(e)}if(t.length>0){const e=new AggregateError(t);console.error("Error occurred when calling event listeners",e)}}registerPerfMetricsGlobalPostMessageHandler(){!0===globalThis.enableReactNativePerfMetrics&&!0===globalThis.enableReactNativePerfMetricsGlobalPostMessage&&this.addEventListener((e=>{window.postMessage({event:e,tag:"react-native-chrome-devtools-perf-metrics"},window.location.origin)}))}registerGlobalErrorReporting(){window.addEventListener("error",(e=>{const[r,t]=Y(`[RNPerfMetrics] uncaught error: ${e.message}`,e.error);this.sendEvent({eventName:"Browser.Error",params:{type:"error",message:r,error:t}})}),{passive:!0}),window.addEventListener("unhandledrejection",(e=>{const[r,t]=Y("[RNPerfMetrics] unhandled promise rejection",e.reason);this.sendEvent({eventName:"Browser.Error",params:{type:"rejectedPromise",message:r,error:t}})}),{passive:!0});const e=globalThis.console,r=e[this.#o];e[this.#o]=(...t)=>{try{const e=t[0],[r,n]=Y("[RNPerfMetrics] console.error",e);this.sendEvent({eventName:"Browser.Error",params:{message:r,error:n,type:"consoleError"}})}catch(e){const[r,t]=Y("[RNPerfMetrics] Error handling console.error",e);this.sendEvent({eventName:"Browser.Error",params:{message:r,error:t,type:"consoleError"}})}finally{r.apply(e,t)}}}setLaunchId(e){this.#i=e}setAppId(e){this.#a=e}setTelemetryInfo(e){this.#c=e}entryPointLoadingStarted(e){this.#d=e,this.sendEvent({eventName:"Entrypoint.LoadingStarted",entryPoint:e})}entryPointLoadingFinished(e){this.sendEvent({eventName:"Entrypoint.LoadingFinished",entryPoint:e})}browserVisibilityChanged(e){this.sendEvent({eventName:"Browser.VisibilityChange",params:{visibilityState:e}})}remoteDebuggingTerminated(e={}){this.sendEvent({eventName:"Connection.DebuggingTerminated",params:e})}developerResourceLoadingStarted(e,r){const t=Q(e);this.sendEvent({eventName:"DeveloperResource.LoadingStarted",params:{url:t,loadingMethod:r}})}developerResourceLoadingFinished(e,r,t){const n=Q(e);this.sendEvent({eventName:"DeveloperResource.LoadingFinished",params:{url:n,loadingMethod:r,success:t.success,errorMessage:t.errorDescription?.message}})}fuseboxSetClientMetadataStarted(){this.sendEvent({eventName:"FuseboxSetClientMetadataStarted"})}fuseboxSetClientMetadataFinished(e,r){if(e)this.sendEvent({eventName:"FuseboxSetClientMetadataFinished",params:{success:!0}});else{const[e,t]=Y("[RNPerfMetrics] Fusebox setClientMetadata failed",r);this.sendEvent({eventName:"FuseboxSetClientMetadataFinished",params:{success:!1,error:t,errorMessage:e}})}}heapSnapshotStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"snapshot"}})}heapSnapshotFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"snapshot",success:e}})}heapProfilingStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"profiling"}})}heapProfilingFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"profiling",success:e}})}heapSamplingStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"sampling"}})}heapSamplingFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"sampling",success:e}})}stackTraceSymbolicationFailed(e,r,t){this.sendEvent({eventName:"StackTraceSymbolicationFailed",params:{stackTrace:e,line:r,reason:t}})}panelShown(e,r){}panelShownInLocation(e,r){this.sendEvent({eventName:"PanelShown",params:{location:r,newPanelName:e}}),this.#l.set(r,e)}#u(e){return{...e,...{timestamp:performance.timeOrigin+performance.now(),launchId:this.#i,appId:this.#a,entryPoint:this.#d,telemetryInfo:this.#c,currentPanels:this.#l}}}}function Q(e){const{url:r}=e;return"http"===e.scheme||"https"===e.scheme?r:`${r.slice(0,100)} …(omitted ${r.length-100} characters)`}function Y(e,r){if(r instanceof Error){return[`${e}: ${r.message}`,r]}const t=`${e}: ${String(r)}`;return[t,new Error(t,{cause:r})]}var J,Z,ee,re,te,ne,oe,se,ie,ae,de,ce,le,ue=Object.freeze({__proto__:null,getInstance:K});class ge{#g;#m;#p;constructor(){this.#g=!1,this.#m=!1,this.#p=""}panelShown(e,r){const t=Z[e]||0;E.recordEnumeratedHistogram("DevTools.PanelShown",t,Z.MAX_VALUE),E.recordUserMetricsAction("DevTools_PanelShown_"+e),r||(this.#g=!0),K().panelShown(e,r)}panelShownInLocation(e,r){const t=ee[`${e}-${r}`]||0;E.recordEnumeratedHistogram("DevTools.PanelShownInLocation",t,ee.MAX_VALUE),K().panelShownInLocation(e,r)}settingsPanelShown(e){this.panelShown("settings-"+e)}sourcesPanelFileDebugged(e){const r=e&&te[e]||te.Unknown;E.recordEnumeratedHistogram("DevTools.SourcesPanelFileDebugged",r,te.MAX_VALUE)}sourcesPanelFileOpened(e){const r=e&&te[e]||te.Unknown;E.recordEnumeratedHistogram("DevTools.SourcesPanelFileOpened",r,te.MAX_VALUE)}networkPanelResponsePreviewOpened(e){const r=e&&te[e]||te.Unknown;E.recordEnumeratedHistogram("DevTools.NetworkPanelResponsePreviewOpened",r,te.MAX_VALUE)}actionTaken(e){E.recordEnumeratedHistogram("DevTools.ActionTaken",e,J.MAX_VALUE)}panelLoaded(e,r){this.#m||e!==this.#p||(this.#m=!0,requestAnimationFrame((()=>{window.setTimeout((()=>{performance.mark(r),this.#g||E.recordPerformanceHistogram(r,performance.now())}),0)})))}setLaunchPanel(e){this.#p=e}performanceTraceLoad(e){E.recordPerformanceHistogram("DevTools.TraceLoad",e.duration)}keybindSetSettingChanged(e){const r=ne[e]||0;E.recordEnumeratedHistogram("DevTools.KeybindSetSettingChanged",r,ne.MAX_VALUE)}keyboardShortcutFired(e){const r=oe[e]||oe.OtherShortcut;E.recordEnumeratedHistogram("DevTools.KeyboardShortcutFired",r,oe.MAX_VALUE)}issuesPanelOpenedFrom(e){E.recordEnumeratedHistogram("DevTools.IssuesPanelOpenedFrom",e,6)}issuesPanelIssueExpanded(e){if(void 0===e)return;const r=ie[e];void 0!==r&&E.recordEnumeratedHistogram("DevTools.IssuesPanelIssueExpanded",r,ie.MAX_VALUE)}issuesPanelResourceOpened(e,r){const t=ae[e+r];void 0!==t&&E.recordEnumeratedHistogram("DevTools.IssuesPanelResourceOpened",t,ae.MAX_VALUE)}issueCreated(e){const r=de[e];void 0!==r&&E.recordEnumeratedHistogram("DevTools.IssueCreated",r,de.MAX_VALUE)}experimentEnabledAtLaunch(e){const r=se[e];void 0!==r&&E.recordEnumeratedHistogram("DevTools.ExperimentEnabledAtLaunch",r,se.MAX_VALUE)}navigationSettingAtFirstTimelineLoad(e){E.recordEnumeratedHistogram("DevTools.TimelineNavigationSettingState",e,4)}experimentDisabledAtLaunch(e){const r=se[e];void 0!==r&&E.recordEnumeratedHistogram("DevTools.ExperimentDisabledAtLaunch",r,se.MAX_VALUE)}experimentChanged(e,r){const t=se[e];if(void 0===t)return;const n=r?"DevTools.ExperimentEnabled":"DevTools.ExperimentDisabled";E.recordEnumeratedHistogram(n,t,se.MAX_VALUE)}developerResourceLoaded(e){e>=8||E.recordEnumeratedHistogram("DevTools.DeveloperResourceLoaded",e,8)}developerResourceScheme(e){e>=9||E.recordEnumeratedHistogram("DevTools.DeveloperResourceScheme",e,9)}language(e){const r=ce[e];void 0!==r&&E.recordEnumeratedHistogram("DevTools.Language",r,ce.MAX_VALUE)}syncSetting(e){E.getSyncInformation((r=>{let t=1;r.isSyncActive&&!r.arePreferencesSynced?t=2:r.isSyncActive&&r.arePreferencesSynced&&(t=e?4:3),E.recordEnumeratedHistogram("DevTools.SyncSetting",t,5)}))}recordingAssertion(e){E.recordEnumeratedHistogram("DevTools.RecordingAssertion",e,4)}recordingToggled(e){E.recordEnumeratedHistogram("DevTools.RecordingToggled",e,3)}recordingReplayFinished(e){E.recordEnumeratedHistogram("DevTools.RecordingReplayFinished",e,5)}recordingReplaySpeed(e){E.recordEnumeratedHistogram("DevTools.RecordingReplaySpeed",e,5)}recordingReplayStarted(e){E.recordEnumeratedHistogram("DevTools.RecordingReplayStarted",e,4)}recordingEdited(e){E.recordEnumeratedHistogram("DevTools.RecordingEdited",e,11)}recordingExported(e){E.recordEnumeratedHistogram("DevTools.RecordingExported",e,6)}recordingCodeToggled(e){E.recordEnumeratedHistogram("DevTools.RecordingCodeToggled",e,3)}recordingCopiedToClipboard(e){E.recordEnumeratedHistogram("DevTools.RecordingCopiedToClipboard",e,9)}cssHintShown(e){E.recordEnumeratedHistogram("DevTools.CSSHintShown",e,14)}lighthouseModeRun(e){E.recordEnumeratedHistogram("DevTools.LighthouseModeRun",e,4)}lighthouseCategoryUsed(e){E.recordEnumeratedHistogram("DevTools.LighthouseCategoryUsed",e,6)}swatchActivated(e){E.recordEnumeratedHistogram("DevTools.SwatchActivated",e,11)}animationPlaybackRateChanged(e){E.recordEnumeratedHistogram("DevTools.AnimationPlaybackRateChanged",e,4)}animationPointDragged(e){E.recordEnumeratedHistogram("DevTools.AnimationPointDragged",e,5)}workspacesPopulated(e){E.recordPerformanceHistogram("DevTools.Workspaces.PopulateWallClocktime",e)}visualLoggingProcessingDone(e){E.recordPerformanceHistogram("DevTools.VisualLogging.ProcessingTime",e)}freestylerQueryLength(e){E.recordCountHistogram("DevTools.Freestyler.QueryLength",e,0,1e5,100)}freestylerEvalResponseSize(e){E.recordCountHistogram("DevTools.Freestyler.EvalResponseSize",e,0,1e5,100)}}!function(e){e[e.WindowDocked=1]="WindowDocked",e[e.WindowUndocked=2]="WindowUndocked",e[e.ScriptsBreakpointSet=3]="ScriptsBreakpointSet",e[e.TimelineStarted=4]="TimelineStarted",e[e.ProfilesCPUProfileTaken=5]="ProfilesCPUProfileTaken",e[e.ProfilesHeapProfileTaken=6]="ProfilesHeapProfileTaken",e[e.ConsoleEvaluated=8]="ConsoleEvaluated",e[e.FileSavedInWorkspace=9]="FileSavedInWorkspace",e[e.DeviceModeEnabled=10]="DeviceModeEnabled",e[e.AnimationsPlaybackRateChanged=11]="AnimationsPlaybackRateChanged",e[e.RevisionApplied=12]="RevisionApplied",e[e.FileSystemDirectoryContentReceived=13]="FileSystemDirectoryContentReceived",e[e.StyleRuleEdited=14]="StyleRuleEdited",e[e.CommandEvaluatedInConsolePanel=15]="CommandEvaluatedInConsolePanel",e[e.DOMPropertiesExpanded=16]="DOMPropertiesExpanded",e[e.ResizedViewInResponsiveMode=17]="ResizedViewInResponsiveMode",e[e.TimelinePageReloadStarted=18]="TimelinePageReloadStarted",e[e.ConnectToNodeJSFromFrontend=19]="ConnectToNodeJSFromFrontend",e[e.ConnectToNodeJSDirectly=20]="ConnectToNodeJSDirectly",e[e.CpuThrottlingEnabled=21]="CpuThrottlingEnabled",e[e.CpuProfileNodeFocused=22]="CpuProfileNodeFocused",e[e.CpuProfileNodeExcluded=23]="CpuProfileNodeExcluded",e[e.SelectFileFromFilePicker=24]="SelectFileFromFilePicker",e[e.SelectCommandFromCommandMenu=25]="SelectCommandFromCommandMenu",e[e.ChangeInspectedNodeInElementsPanel=26]="ChangeInspectedNodeInElementsPanel",e[e.StyleRuleCopied=27]="StyleRuleCopied",e[e.CoverageStarted=28]="CoverageStarted",e[e.LighthouseStarted=29]="LighthouseStarted",e[e.LighthouseFinished=30]="LighthouseFinished",e[e.ShowedThirdPartyBadges=31]="ShowedThirdPartyBadges",e[e.LighthouseViewTrace=32]="LighthouseViewTrace",e[e.FilmStripStartedRecording=33]="FilmStripStartedRecording",e[e.CoverageReportFiltered=34]="CoverageReportFiltered",e[e.CoverageStartedPerBlock=35]="CoverageStartedPerBlock",e[e["SettingsOpenedFromGear-deprecated"]=36]="SettingsOpenedFromGear-deprecated",e[e["SettingsOpenedFromMenu-deprecated"]=37]="SettingsOpenedFromMenu-deprecated",e[e["SettingsOpenedFromCommandMenu-deprecated"]=38]="SettingsOpenedFromCommandMenu-deprecated",e[e.TabMovedToDrawer=39]="TabMovedToDrawer",e[e.TabMovedToMainPanel=40]="TabMovedToMainPanel",e[e.CaptureCssOverviewClicked=41]="CaptureCssOverviewClicked",e[e.VirtualAuthenticatorEnvironmentEnabled=42]="VirtualAuthenticatorEnvironmentEnabled",e[e.SourceOrderViewActivated=43]="SourceOrderViewActivated",e[e.UserShortcutAdded=44]="UserShortcutAdded",e[e.ShortcutRemoved=45]="ShortcutRemoved",e[e.ShortcutModified=46]="ShortcutModified",e[e.CustomPropertyLinkClicked=47]="CustomPropertyLinkClicked",e[e.CustomPropertyEdited=48]="CustomPropertyEdited",e[e.ServiceWorkerNetworkRequestClicked=49]="ServiceWorkerNetworkRequestClicked",e[e.ServiceWorkerNetworkRequestClosedQuickly=50]="ServiceWorkerNetworkRequestClosedQuickly",e[e.NetworkPanelServiceWorkerRespondWith=51]="NetworkPanelServiceWorkerRespondWith",e[e.NetworkPanelCopyValue=52]="NetworkPanelCopyValue",e[e.ConsoleSidebarOpened=53]="ConsoleSidebarOpened",e[e.PerfPanelTraceImported=54]="PerfPanelTraceImported",e[e.PerfPanelTraceExported=55]="PerfPanelTraceExported",e[e.StackFrameRestarted=56]="StackFrameRestarted",e[e.CaptureTestProtocolClicked=57]="CaptureTestProtocolClicked",e[e.BreakpointRemovedFromRemoveButton=58]="BreakpointRemovedFromRemoveButton",e[e.BreakpointGroupExpandedStateChanged=59]="BreakpointGroupExpandedStateChanged",e[e.HeaderOverrideFileCreated=60]="HeaderOverrideFileCreated",e[e.HeaderOverrideEnableEditingClicked=61]="HeaderOverrideEnableEditingClicked",e[e.HeaderOverrideHeaderAdded=62]="HeaderOverrideHeaderAdded",e[e.HeaderOverrideHeaderEdited=63]="HeaderOverrideHeaderEdited",e[e.HeaderOverrideHeaderRemoved=64]="HeaderOverrideHeaderRemoved",e[e.HeaderOverrideHeadersFileEdited=65]="HeaderOverrideHeadersFileEdited",e[e.PersistenceNetworkOverridesEnabled=66]="PersistenceNetworkOverridesEnabled",e[e.PersistenceNetworkOverridesDisabled=67]="PersistenceNetworkOverridesDisabled",e[e.BreakpointRemovedFromContextMenu=68]="BreakpointRemovedFromContextMenu",e[e.BreakpointsInFileRemovedFromRemoveButton=69]="BreakpointsInFileRemovedFromRemoveButton",e[e.BreakpointsInFileRemovedFromContextMenu=70]="BreakpointsInFileRemovedFromContextMenu",e[e.BreakpointsInFileCheckboxToggled=71]="BreakpointsInFileCheckboxToggled",e[e.BreakpointsInFileEnabledDisabledFromContextMenu=72]="BreakpointsInFileEnabledDisabledFromContextMenu",e[e.BreakpointConditionEditedFromSidebar=73]="BreakpointConditionEditedFromSidebar",e[e.WorkspaceTabAddFolder=74]="WorkspaceTabAddFolder",e[e.WorkspaceTabRemoveFolder=75]="WorkspaceTabRemoveFolder",e[e.OverrideTabAddFolder=76]="OverrideTabAddFolder",e[e.OverrideTabRemoveFolder=77]="OverrideTabRemoveFolder",e[e.WorkspaceSourceSelected=78]="WorkspaceSourceSelected",e[e.OverridesSourceSelected=79]="OverridesSourceSelected",e[e.StyleSheetInitiatorLinkClicked=80]="StyleSheetInitiatorLinkClicked",e[e.BreakpointRemovedFromGutterContextMenu=81]="BreakpointRemovedFromGutterContextMenu",e[e.BreakpointRemovedFromGutterToggle=82]="BreakpointRemovedFromGutterToggle",e[e.StylePropertyInsideKeyframeEdited=83]="StylePropertyInsideKeyframeEdited",e[e.OverrideContentFromSourcesContextMenu=84]="OverrideContentFromSourcesContextMenu",e[e.OverrideContentFromNetworkContextMenu=85]="OverrideContentFromNetworkContextMenu",e[e.OverrideScript=86]="OverrideScript",e[e.OverrideStyleSheet=87]="OverrideStyleSheet",e[e.OverrideDocument=88]="OverrideDocument",e[e.OverrideFetchXHR=89]="OverrideFetchXHR",e[e.OverrideImage=90]="OverrideImage",e[e.OverrideFont=91]="OverrideFont",e[e.OverrideContentContextMenuSetup=92]="OverrideContentContextMenuSetup",e[e.OverrideContentContextMenuAbandonSetup=93]="OverrideContentContextMenuAbandonSetup",e[e.OverrideContentContextMenuActivateDisabled=94]="OverrideContentContextMenuActivateDisabled",e[e.OverrideContentContextMenuOpenExistingFile=95]="OverrideContentContextMenuOpenExistingFile",e[e.OverrideContentContextMenuSaveNewFile=96]="OverrideContentContextMenuSaveNewFile",e[e.ShowAllOverridesFromSourcesContextMenu=97]="ShowAllOverridesFromSourcesContextMenu",e[e.ShowAllOverridesFromNetworkContextMenu=98]="ShowAllOverridesFromNetworkContextMenu",e[e.AnimationGroupsCleared=99]="AnimationGroupsCleared",e[e.AnimationsPaused=100]="AnimationsPaused",e[e.AnimationsResumed=101]="AnimationsResumed",e[e.AnimatedNodeDescriptionClicked=102]="AnimatedNodeDescriptionClicked",e[e.AnimationGroupScrubbed=103]="AnimationGroupScrubbed",e[e.AnimationGroupReplayed=104]="AnimationGroupReplayed",e[e.OverrideTabDeleteFolderContextMenu=105]="OverrideTabDeleteFolderContextMenu",e[e.WorkspaceDropFolder=107]="WorkspaceDropFolder",e[e.WorkspaceSelectFolder=108]="WorkspaceSelectFolder",e[e.OverrideContentContextMenuSourceMappedWarning=109]="OverrideContentContextMenuSourceMappedWarning",e[e.OverrideContentContextMenuRedirectToDeployed=110]="OverrideContentContextMenuRedirectToDeployed",e[e.NewStyleRuleAdded=111]="NewStyleRuleAdded",e[e.TraceExpanded=112]="TraceExpanded",e[e.InsightConsoleMessageShown=113]="InsightConsoleMessageShown",e[e.InsightRequestedViaContextMenu=114]="InsightRequestedViaContextMenu",e[e.InsightRequestedViaHoverButton=115]="InsightRequestedViaHoverButton",e[e.InsightRatedPositive=117]="InsightRatedPositive",e[e.InsightRatedNegative=118]="InsightRatedNegative",e[e.InsightClosed=119]="InsightClosed",e[e.InsightErrored=120]="InsightErrored",e[e.InsightHoverButtonShown=121]="InsightHoverButtonShown",e[e.SelfXssWarningConsoleMessageShown=122]="SelfXssWarningConsoleMessageShown",e[e.SelfXssWarningDialogShown=123]="SelfXssWarningDialogShown",e[e.SelfXssAllowPastingInConsole=124]="SelfXssAllowPastingInConsole",e[e.SelfXssAllowPastingInDialog=125]="SelfXssAllowPastingInDialog",e[e.ToggleEmulateFocusedPageFromStylesPaneOn=126]="ToggleEmulateFocusedPageFromStylesPaneOn",e[e.ToggleEmulateFocusedPageFromStylesPaneOff=127]="ToggleEmulateFocusedPageFromStylesPaneOff",e[e.ToggleEmulateFocusedPageFromRenderingTab=128]="ToggleEmulateFocusedPageFromRenderingTab",e[e.ToggleEmulateFocusedPageFromCommandMenu=129]="ToggleEmulateFocusedPageFromCommandMenu",e[e.InsightGenerated=130]="InsightGenerated",e[e.InsightErroredApi=131]="InsightErroredApi",e[e.InsightErroredMarkdown=132]="InsightErroredMarkdown",e[e.ToggleShowWebVitals=133]="ToggleShowWebVitals",e[e.InsightErroredPermissionDenied=134]="InsightErroredPermissionDenied",e[e.InsightErroredCannotSend=135]="InsightErroredCannotSend",e[e.InsightErroredRequestFailed=136]="InsightErroredRequestFailed",e[e.InsightErroredCannotParseChunk=137]="InsightErroredCannotParseChunk",e[e.InsightErroredUnknownChunk=138]="InsightErroredUnknownChunk",e[e.InsightErroredOther=139]="InsightErroredOther",e[e.AutofillReceived=140]="AutofillReceived",e[e.AutofillReceivedAndTabAutoOpened=141]="AutofillReceivedAndTabAutoOpened",e[e.AnimationGroupSelected=142]="AnimationGroupSelected",e[e.ScrollDrivenAnimationGroupSelected=143]="ScrollDrivenAnimationGroupSelected",e[e.ScrollDrivenAnimationGroupScrubbed=144]="ScrollDrivenAnimationGroupScrubbed",e[e.AiAssistanceOpenedFromElementsPanel=145]="AiAssistanceOpenedFromElementsPanel",e[e.AiAssistanceOpenedFromStylesTab=146]="AiAssistanceOpenedFromStylesTab",e[e.ConsoleFilterByContext=147]="ConsoleFilterByContext",e[e.ConsoleFilterBySource=148]="ConsoleFilterBySource",e[e.ConsoleFilterByUrl=149]="ConsoleFilterByUrl",e[e.InsightConsentReminderShown=150]="InsightConsentReminderShown",e[e.InsightConsentReminderCanceled=151]="InsightConsentReminderCanceled",e[e.InsightConsentReminderConfirmed=152]="InsightConsentReminderConfirmed",e[e.InsightsOnboardingShown=153]="InsightsOnboardingShown",e[e.InsightsOnboardingCanceledOnPage1=154]="InsightsOnboardingCanceledOnPage1",e[e.InsightsOnboardingCanceledOnPage2=155]="InsightsOnboardingCanceledOnPage2",e[e.InsightsOnboardingConfirmed=156]="InsightsOnboardingConfirmed",e[e.InsightsOnboardingNextPage=157]="InsightsOnboardingNextPage",e[e.InsightsOnboardingPrevPage=158]="InsightsOnboardingPrevPage",e[e.InsightsOnboardingFeatureDisabled=159]="InsightsOnboardingFeatureDisabled",e[e.InsightsOptInTeaserShown=160]="InsightsOptInTeaserShown",e[e.InsightsOptInTeaserSettingsLinkClicked=161]="InsightsOptInTeaserSettingsLinkClicked",e[e.InsightsOptInTeaserConfirmedInSettings=162]="InsightsOptInTeaserConfirmedInSettings",e[e.InsightsReminderTeaserShown=163]="InsightsReminderTeaserShown",e[e.InsightsReminderTeaserConfirmed=164]="InsightsReminderTeaserConfirmed",e[e.InsightsReminderTeaserCanceled=165]="InsightsReminderTeaserCanceled",e[e.InsightsReminderTeaserSettingsLinkClicked=166]="InsightsReminderTeaserSettingsLinkClicked",e[e.InsightsReminderTeaserAbortedInSettings=167]="InsightsReminderTeaserAbortedInSettings",e[e.GeneratingInsightWithoutDisclaimer=168]="GeneratingInsightWithoutDisclaimer",e[e.AiAssistanceOpenedFromElementsPanelFloatingButton=169]="AiAssistanceOpenedFromElementsPanelFloatingButton",e[e.AiAssistanceOpenedFromNetworkPanel=170]="AiAssistanceOpenedFromNetworkPanel",e[e.AiAssistanceOpenedFromSourcesPanel=171]="AiAssistanceOpenedFromSourcesPanel",e[e.AiAssistanceOpenedFromSourcesPanelFloatingButton=172]="AiAssistanceOpenedFromSourcesPanelFloatingButton",e[e.AiAssistanceOpenedFromPerformancePanel=173]="AiAssistanceOpenedFromPerformancePanel",e[e.AiAssistanceOpenedFromNetworkPanelFloatingButton=174]="AiAssistanceOpenedFromNetworkPanelFloatingButton",e[e.AiAssistancePanelOpened=175]="AiAssistancePanelOpened",e[e.AiAssistanceQuerySubmitted=176]="AiAssistanceQuerySubmitted",e[e.AiAssistanceAnswerReceived=177]="AiAssistanceAnswerReceived",e[e.AiAssistanceDynamicSuggestionClicked=178]="AiAssistanceDynamicSuggestionClicked",e[e.AiAssistanceSideEffectConfirmed=179]="AiAssistanceSideEffectConfirmed",e[e.AiAssistanceSideEffectRejected=180]="AiAssistanceSideEffectRejected",e[e.AiAssistanceError=181]="AiAssistanceError",e[e.AiAssistanceOpenedFromPerformanceInsight=182]="AiAssistanceOpenedFromPerformanceInsight",e[e.MAX_VALUE=183]="MAX_VALUE"}(J||(J={})),function(e){e[e.elements=1]="elements",e[e.resources=2]="resources",e[e.network=3]="network",e[e.sources=4]="sources",e[e.timeline=5]="timeline",e[e["heap-profiler"]=6]="heap-profiler",e[e.console=8]="console",e[e.layers=9]="layers",e[e["console-view"]=10]="console-view",e[e.animations=11]="animations",e[e["network.config"]=12]="network.config",e[e.rendering=13]="rendering",e[e.sensors=14]="sensors",e[e["sources.search"]=15]="sources.search",e[e.security=16]="security",e[e["js-profiler"]=17]="js-profiler",e[e.lighthouse=18]="lighthouse",e[e.coverage=19]="coverage",e[e["protocol-monitor"]=20]="protocol-monitor",e[e["remote-devices"]=21]="remote-devices",e[e["web-audio"]=22]="web-audio",e[e["changes.changes"]=23]="changes.changes",e[e["performance.monitor"]=24]="performance.monitor",e[e["release-note"]=25]="release-note",e[e["live-heap-profile"]=26]="live-heap-profile",e[e["sources.quick"]=27]="sources.quick",e[e["network.blocked-urls"]=28]="network.blocked-urls",e[e["settings-preferences"]=29]="settings-preferences",e[e["settings-workspace"]=30]="settings-workspace",e[e["settings-experiments"]=31]="settings-experiments",e[e["settings-blackbox"]=32]="settings-blackbox",e[e["settings-devices"]=33]="settings-devices",e[e["settings-throttling-conditions"]=34]="settings-throttling-conditions",e[e["settings-emulation-locations"]=35]="settings-emulation-locations",e[e["settings-shortcuts"]=36]="settings-shortcuts",e[e["issues-pane"]=37]="issues-pane",e[e["settings-keybinds"]=38]="settings-keybinds",e[e.cssoverview=39]="cssoverview",e[e["chrome-recorder"]=40]="chrome-recorder",e[e["trust-tokens"]=41]="trust-tokens",e[e["reporting-api"]=42]="reporting-api",e[e["interest-groups"]=43]="interest-groups",e[e["back-forward-cache"]=44]="back-forward-cache",e[e["service-worker-cache"]=45]="service-worker-cache",e[e["background-service-background-fetch"]=46]="background-service-background-fetch",e[e["background-service-background-sync"]=47]="background-service-background-sync",e[e["background-service-push-messaging"]=48]="background-service-push-messaging",e[e["background-service-notifications"]=49]="background-service-notifications",e[e["background-service-payment-handler"]=50]="background-service-payment-handler",e[e["background-service-periodic-background-sync"]=51]="background-service-periodic-background-sync",e[e["service-workers"]=52]="service-workers",e[e["app-manifest"]=53]="app-manifest",e[e.storage=54]="storage",e[e.cookies=55]="cookies",e[e["frame-details"]=56]="frame-details",e[e["frame-resource"]=57]="frame-resource",e[e["frame-window"]=58]="frame-window",e[e["frame-worker"]=59]="frame-worker",e[e["dom-storage"]=60]="dom-storage",e[e["indexed-db"]=61]="indexed-db",e[e["web-sql"]=62]="web-sql",e[e["performance-insights"]=63]="performance-insights",e[e.preloading=64]="preloading",e[e["bounce-tracking-mitigations"]=65]="bounce-tracking-mitigations",e[e["developer-resources"]=66]="developer-resources",e[e["autofill-view"]=67]="autofill-view",e[e.MAX_VALUE=68]="MAX_VALUE"}(Z||(Z={})),function(e){e[e["elements-main"]=1]="elements-main",e[e["elements-drawer"]=2]="elements-drawer",e[e["resources-main"]=3]="resources-main",e[e["resources-drawer"]=4]="resources-drawer",e[e["network-main"]=5]="network-main",e[e["network-drawer"]=6]="network-drawer",e[e["sources-main"]=7]="sources-main",e[e["sources-drawer"]=8]="sources-drawer",e[e["timeline-main"]=9]="timeline-main",e[e["timeline-drawer"]=10]="timeline-drawer",e[e["heap_profiler-main"]=11]="heap_profiler-main",e[e["heap_profiler-drawer"]=12]="heap_profiler-drawer",e[e["console-main"]=13]="console-main",e[e["console-drawer"]=14]="console-drawer",e[e["layers-main"]=15]="layers-main",e[e["layers-drawer"]=16]="layers-drawer",e[e["console-view-main"]=17]="console-view-main",e[e["console-view-drawer"]=18]="console-view-drawer",e[e["animations-main"]=19]="animations-main",e[e["animations-drawer"]=20]="animations-drawer",e[e["network.config-main"]=21]="network.config-main",e[e["network.config-drawer"]=22]="network.config-drawer",e[e["rendering-main"]=23]="rendering-main",e[e["rendering-drawer"]=24]="rendering-drawer",e[e["sensors-main"]=25]="sensors-main",e[e["sensors-drawer"]=26]="sensors-drawer",e[e["sources.search-main"]=27]="sources.search-main",e[e["sources.search-drawer"]=28]="sources.search-drawer",e[e["security-main"]=29]="security-main",e[e["security-drawer"]=30]="security-drawer",e[e["lighthouse-main"]=33]="lighthouse-main",e[e["lighthouse-drawer"]=34]="lighthouse-drawer",e[e["coverage-main"]=35]="coverage-main",e[e["coverage-drawer"]=36]="coverage-drawer",e[e["protocol-monitor-main"]=37]="protocol-monitor-main",e[e["protocol-monitor-drawer"]=38]="protocol-monitor-drawer",e[e["remote-devices-main"]=39]="remote-devices-main",e[e["remote-devices-drawer"]=40]="remote-devices-drawer",e[e["web-audio-main"]=41]="web-audio-main",e[e["web-audio-drawer"]=42]="web-audio-drawer",e[e["changes.changes-main"]=43]="changes.changes-main",e[e["changes.changes-drawer"]=44]="changes.changes-drawer",e[e["performance.monitor-main"]=45]="performance.monitor-main",e[e["performance.monitor-drawer"]=46]="performance.monitor-drawer",e[e["release-note-main"]=47]="release-note-main",e[e["release-note-drawer"]=48]="release-note-drawer",e[e["live_heap_profile-main"]=49]="live_heap_profile-main",e[e["live_heap_profile-drawer"]=50]="live_heap_profile-drawer",e[e["sources.quick-main"]=51]="sources.quick-main",e[e["sources.quick-drawer"]=52]="sources.quick-drawer",e[e["network.blocked-urls-main"]=53]="network.blocked-urls-main",e[e["network.blocked-urls-drawer"]=54]="network.blocked-urls-drawer",e[e["settings-preferences-main"]=55]="settings-preferences-main",e[e["settings-preferences-drawer"]=56]="settings-preferences-drawer",e[e["settings-workspace-main"]=57]="settings-workspace-main",e[e["settings-workspace-drawer"]=58]="settings-workspace-drawer",e[e["settings-experiments-main"]=59]="settings-experiments-main",e[e["settings-experiments-drawer"]=60]="settings-experiments-drawer",e[e["settings-blackbox-main"]=61]="settings-blackbox-main",e[e["settings-blackbox-drawer"]=62]="settings-blackbox-drawer",e[e["settings-devices-main"]=63]="settings-devices-main",e[e["settings-devices-drawer"]=64]="settings-devices-drawer",e[e["settings-throttling-conditions-main"]=65]="settings-throttling-conditions-main",e[e["settings-throttling-conditions-drawer"]=66]="settings-throttling-conditions-drawer",e[e["settings-emulation-locations-main"]=67]="settings-emulation-locations-main",e[e["settings-emulation-locations-drawer"]=68]="settings-emulation-locations-drawer",e[e["settings-shortcuts-main"]=69]="settings-shortcuts-main",e[e["settings-shortcuts-drawer"]=70]="settings-shortcuts-drawer",e[e["issues-pane-main"]=71]="issues-pane-main",e[e["issues-pane-drawer"]=72]="issues-pane-drawer",e[e["settings-keybinds-main"]=73]="settings-keybinds-main",e[e["settings-keybinds-drawer"]=74]="settings-keybinds-drawer",e[e["cssoverview-main"]=75]="cssoverview-main",e[e["cssoverview-drawer"]=76]="cssoverview-drawer",e[e["chrome_recorder-main"]=77]="chrome_recorder-main",e[e["chrome_recorder-drawer"]=78]="chrome_recorder-drawer",e[e["trust_tokens-main"]=79]="trust_tokens-main",e[e["trust_tokens-drawer"]=80]="trust_tokens-drawer",e[e["reporting_api-main"]=81]="reporting_api-main",e[e["reporting_api-drawer"]=82]="reporting_api-drawer",e[e["interest_groups-main"]=83]="interest_groups-main",e[e["interest_groups-drawer"]=84]="interest_groups-drawer",e[e["back_forward_cache-main"]=85]="back_forward_cache-main",e[e["back_forward_cache-drawer"]=86]="back_forward_cache-drawer",e[e["service_worker_cache-main"]=87]="service_worker_cache-main",e[e["service_worker_cache-drawer"]=88]="service_worker_cache-drawer",e[e["background_service_backgroundFetch-main"]=89]="background_service_backgroundFetch-main",e[e["background_service_backgroundFetch-drawer"]=90]="background_service_backgroundFetch-drawer",e[e["background_service_backgroundSync-main"]=91]="background_service_backgroundSync-main",e[e["background_service_backgroundSync-drawer"]=92]="background_service_backgroundSync-drawer",e[e["background_service_pushMessaging-main"]=93]="background_service_pushMessaging-main",e[e["background_service_pushMessaging-drawer"]=94]="background_service_pushMessaging-drawer",e[e["background_service_notifications-main"]=95]="background_service_notifications-main",e[e["background_service_notifications-drawer"]=96]="background_service_notifications-drawer",e[e["background_service_paymentHandler-main"]=97]="background_service_paymentHandler-main",e[e["background_service_paymentHandler-drawer"]=98]="background_service_paymentHandler-drawer",e[e["background_service_periodicBackgroundSync-main"]=99]="background_service_periodicBackgroundSync-main",e[e["background_service_periodicBackgroundSync-drawer"]=100]="background_service_periodicBackgroundSync-drawer",e[e["service_workers-main"]=101]="service_workers-main",e[e["service_workers-drawer"]=102]="service_workers-drawer",e[e["app_manifest-main"]=103]="app_manifest-main",e[e["app_manifest-drawer"]=104]="app_manifest-drawer",e[e["storage-main"]=105]="storage-main",e[e["storage-drawer"]=106]="storage-drawer",e[e["cookies-main"]=107]="cookies-main",e[e["cookies-drawer"]=108]="cookies-drawer",e[e["frame_details-main"]=109]="frame_details-main",e[e["frame_details-drawer"]=110]="frame_details-drawer",e[e["frame_resource-main"]=111]="frame_resource-main",e[e["frame_resource-drawer"]=112]="frame_resource-drawer",e[e["frame_window-main"]=113]="frame_window-main",e[e["frame_window-drawer"]=114]="frame_window-drawer",e[e["frame_worker-main"]=115]="frame_worker-main",e[e["frame_worker-drawer"]=116]="frame_worker-drawer",e[e["dom_storage-main"]=117]="dom_storage-main",e[e["dom_storage-drawer"]=118]="dom_storage-drawer",e[e["indexed_db-main"]=119]="indexed_db-main",e[e["indexed_db-drawer"]=120]="indexed_db-drawer",e[e["web_sql-main"]=121]="web_sql-main",e[e["web_sql-drawer"]=122]="web_sql-drawer",e[e["performance_insights-main"]=123]="performance_insights-main",e[e["performance_insights-drawer"]=124]="performance_insights-drawer",e[e["preloading-main"]=125]="preloading-main",e[e["preloading-drawer"]=126]="preloading-drawer",e[e["bounce_tracking_mitigations-main"]=127]="bounce_tracking_mitigations-main",e[e["bounce_tracking_mitigations-drawer"]=128]="bounce_tracking_mitigations-drawer",e[e["developer-resources-main"]=129]="developer-resources-main",e[e["developer-resources-drawer"]=130]="developer-resources-drawer",e[e["autofill-view-main"]=131]="autofill-view-main",e[e["autofill-view-drawer"]=132]="autofill-view-drawer",e[e.MAX_VALUE=133]="MAX_VALUE"}(ee||(ee={})),function(e){e[e.OtherSidebarPane=0]="OtherSidebarPane",e[e.styles=1]="styles",e[e.computed=2]="computed",e[e["elements.layout"]=3]="elements.layout",e[e["elements.event-listeners"]=4]="elements.event-listeners",e[e["elements.dom-breakpoints"]=5]="elements.dom-breakpoints",e[e["elements.dom-properties"]=6]="elements.dom-properties",e[e["accessibility.view"]=7]="accessibility.view",e[e.MAX_VALUE=8]="MAX_VALUE"}(re||(re={})),function(e){e[e.Unknown=0]="Unknown",e[e["text/css"]=2]="text/css",e[e["text/html"]=3]="text/html",e[e["application/xml"]=4]="application/xml",e[e["application/wasm"]=5]="application/wasm",e[e["application/manifest+json"]=6]="application/manifest+json",e[e["application/x-aspx"]=7]="application/x-aspx",e[e["application/jsp"]=8]="application/jsp",e[e["text/x-c++src"]=9]="text/x-c++src",e[e["text/x-coffeescript"]=10]="text/x-coffeescript",e[e["application/vnd.dart"]=11]="application/vnd.dart",e[e["text/typescript"]=12]="text/typescript",e[e["text/typescript-jsx"]=13]="text/typescript-jsx",e[e["application/json"]=14]="application/json",e[e["text/x-csharp"]=15]="text/x-csharp",e[e["text/x-java"]=16]="text/x-java",e[e["text/x-less"]=17]="text/x-less",e[e["application/x-httpd-php"]=18]="application/x-httpd-php",e[e["text/x-python"]=19]="text/x-python",e[e["text/x-sh"]=20]="text/x-sh",e[e["text/x-gss"]=21]="text/x-gss",e[e["text/x-sass"]=22]="text/x-sass",e[e["text/x-scss"]=23]="text/x-scss",e[e["text/markdown"]=24]="text/markdown",e[e["text/x-clojure"]=25]="text/x-clojure",e[e["text/jsx"]=26]="text/jsx",e[e["text/x-go"]=27]="text/x-go",e[e["text/x-kotlin"]=28]="text/x-kotlin",e[e["text/x-scala"]=29]="text/x-scala",e[e["text/x.svelte"]=30]="text/x.svelte",e[e["text/javascript+plain"]=31]="text/javascript+plain",e[e["text/javascript+minified"]=32]="text/javascript+minified",e[e["text/javascript+sourcemapped"]=33]="text/javascript+sourcemapped",e[e["text/x.angular"]=34]="text/x.angular",e[e["text/x.vue"]=35]="text/x.vue",e[e["text/javascript+snippet"]=36]="text/javascript+snippet",e[e["text/javascript+eval"]=37]="text/javascript+eval",e[e.MAX_VALUE=38]="MAX_VALUE"}(te||(te={})),function(e){e[e.devToolsDefault=0]="devToolsDefault",e[e.vsCode=1]="vsCode",e[e.MAX_VALUE=2]="MAX_VALUE"}(ne||(ne={})),function(e){e[e.OtherShortcut=0]="OtherShortcut",e[e["quick-open.show-command-menu"]=1]="quick-open.show-command-menu",e[e["console.clear"]=2]="console.clear",e[e["console.toggle"]=3]="console.toggle",e[e["debugger.step"]=4]="debugger.step",e[e["debugger.step-into"]=5]="debugger.step-into",e[e["debugger.step-out"]=6]="debugger.step-out",e[e["debugger.step-over"]=7]="debugger.step-over",e[e["debugger.toggle-breakpoint"]=8]="debugger.toggle-breakpoint",e[e["debugger.toggle-breakpoint-enabled"]=9]="debugger.toggle-breakpoint-enabled",e[e["debugger.toggle-pause"]=10]="debugger.toggle-pause",e[e["elements.edit-as-html"]=11]="elements.edit-as-html",e[e["elements.hide-element"]=12]="elements.hide-element",e[e["elements.redo"]=13]="elements.redo",e[e["elements.toggle-element-search"]=14]="elements.toggle-element-search",e[e["elements.undo"]=15]="elements.undo",e[e["main.search-in-panel.find"]=16]="main.search-in-panel.find",e[e["main.toggle-drawer"]=17]="main.toggle-drawer",e[e["network.hide-request-details"]=18]="network.hide-request-details",e[e["network.search"]=19]="network.search",e[e["network.toggle-recording"]=20]="network.toggle-recording",e[e["quick-open.show"]=21]="quick-open.show",e[e["settings.show"]=22]="settings.show",e[e["sources.search"]=23]="sources.search",e[e["background-service.toggle-recording"]=24]="background-service.toggle-recording",e[e["components.collect-garbage"]=25]="components.collect-garbage",e[e["console.clear.history"]=26]="console.clear.history",e[e["console.create-pin"]=27]="console.create-pin",e[e["coverage.start-with-reload"]=28]="coverage.start-with-reload",e[e["coverage.toggle-recording"]=29]="coverage.toggle-recording",e[e["debugger.breakpoint-input-window"]=30]="debugger.breakpoint-input-window",e[e["debugger.evaluate-selection"]=31]="debugger.evaluate-selection",e[e["debugger.next-call-frame"]=32]="debugger.next-call-frame",e[e["debugger.previous-call-frame"]=33]="debugger.previous-call-frame",e[e["debugger.run-snippet"]=34]="debugger.run-snippet",e[e["debugger.toggle-breakpoints-active"]=35]="debugger.toggle-breakpoints-active",e[e["elements.capture-area-screenshot"]=36]="elements.capture-area-screenshot",e[e["emulation.capture-full-height-screenshot"]=37]="emulation.capture-full-height-screenshot",e[e["emulation.capture-node-screenshot"]=38]="emulation.capture-node-screenshot",e[e["emulation.capture-screenshot"]=39]="emulation.capture-screenshot",e[e["emulation.show-sensors"]=40]="emulation.show-sensors",e[e["emulation.toggle-device-mode"]=41]="emulation.toggle-device-mode",e[e["help.release-notes"]=42]="help.release-notes",e[e["help.report-issue"]=43]="help.report-issue",e[e["input.start-replaying"]=44]="input.start-replaying",e[e["input.toggle-pause"]=45]="input.toggle-pause",e[e["input.toggle-recording"]=46]="input.toggle-recording",e[e["inspector-main.focus-debuggee"]=47]="inspector-main.focus-debuggee",e[e["inspector-main.hard-reload"]=48]="inspector-main.hard-reload",e[e["inspector-main.reload"]=49]="inspector-main.reload",e[e["live-heap-profile.start-with-reload"]=50]="live-heap-profile.start-with-reload",e[e["live-heap-profile.toggle-recording"]=51]="live-heap-profile.toggle-recording",e[e["main.debug-reload"]=52]="main.debug-reload",e[e["main.next-tab"]=53]="main.next-tab",e[e["main.previous-tab"]=54]="main.previous-tab",e[e["main.search-in-panel.cancel"]=55]="main.search-in-panel.cancel",e[e["main.search-in-panel.find-next"]=56]="main.search-in-panel.find-next",e[e["main.search-in-panel.find-previous"]=57]="main.search-in-panel.find-previous",e[e["main.toggle-dock"]=58]="main.toggle-dock",e[e["main.zoom-in"]=59]="main.zoom-in",e[e["main.zoom-out"]=60]="main.zoom-out",e[e["main.zoom-reset"]=61]="main.zoom-reset",e[e["network-conditions.network-low-end-mobile"]=62]="network-conditions.network-low-end-mobile",e[e["network-conditions.network-mid-tier-mobile"]=63]="network-conditions.network-mid-tier-mobile",e[e["network-conditions.network-offline"]=64]="network-conditions.network-offline",e[e["network-conditions.network-online"]=65]="network-conditions.network-online",e[e["profiler.heap-toggle-recording"]=66]="profiler.heap-toggle-recording",e[e["profiler.js-toggle-recording"]=67]="profiler.js-toggle-recording",e[e["resources.clear"]=68]="resources.clear",e[e["settings.documentation"]=69]="settings.documentation",e[e["settings.shortcuts"]=70]="settings.shortcuts",e[e["sources.add-folder-to-workspace"]=71]="sources.add-folder-to-workspace",e[e["sources.add-to-watch"]=72]="sources.add-to-watch",e[e["sources.close-all"]=73]="sources.close-all",e[e["sources.close-editor-tab"]=74]="sources.close-editor-tab",e[e["sources.create-snippet"]=75]="sources.create-snippet",e[e["sources.go-to-line"]=76]="sources.go-to-line",e[e["sources.go-to-member"]=77]="sources.go-to-member",e[e["sources.jump-to-next-location"]=78]="sources.jump-to-next-location",e[e["sources.jump-to-previous-location"]=79]="sources.jump-to-previous-location",e[e["sources.rename"]=80]="sources.rename",e[e["sources.save"]=81]="sources.save",e[e["sources.save-all"]=82]="sources.save-all",e[e["sources.switch-file"]=83]="sources.switch-file",e[e["timeline.jump-to-next-frame"]=84]="timeline.jump-to-next-frame",e[e["timeline.jump-to-previous-frame"]=85]="timeline.jump-to-previous-frame",e[e["timeline.load-from-file"]=86]="timeline.load-from-file",e[e["timeline.next-recording"]=87]="timeline.next-recording",e[e["timeline.previous-recording"]=88]="timeline.previous-recording",e[e["timeline.record-reload"]=89]="timeline.record-reload",e[e["timeline.save-to-file"]=90]="timeline.save-to-file",e[e["timeline.show-history"]=91]="timeline.show-history",e[e["timeline.toggle-recording"]=92]="timeline.toggle-recording",e[e["sources.increment-css"]=93]="sources.increment-css",e[e["sources.increment-css-by-ten"]=94]="sources.increment-css-by-ten",e[e["sources.decrement-css"]=95]="sources.decrement-css",e[e["sources.decrement-css-by-ten"]=96]="sources.decrement-css-by-ten",e[e["layers.reset-view"]=97]="layers.reset-view",e[e["layers.pan-mode"]=98]="layers.pan-mode",e[e["layers.rotate-mode"]=99]="layers.rotate-mode",e[e["layers.zoom-in"]=100]="layers.zoom-in",e[e["layers.zoom-out"]=101]="layers.zoom-out",e[e["layers.up"]=102]="layers.up",e[e["layers.down"]=103]="layers.down",e[e["layers.left"]=104]="layers.left",e[e["layers.right"]=105]="layers.right",e[e["help.report-translation-issue"]=106]="help.report-translation-issue",e[e["rendering.toggle-prefers-color-scheme"]=107]="rendering.toggle-prefers-color-scheme",e[e["chrome-recorder.start-recording"]=108]="chrome-recorder.start-recording",e[e["chrome-recorder.replay-recording"]=109]="chrome-recorder.replay-recording",e[e["chrome-recorder.toggle-code-view"]=110]="chrome-recorder.toggle-code-view",e[e["chrome-recorder.copy-recording-or-step"]=111]="chrome-recorder.copy-recording-or-step",e[e["changes.revert"]=112]="changes.revert",e[e["changes.copy"]=113]="changes.copy",e[e["elements.new-style-rule"]=114]="elements.new-style-rule",e[e["elements.refresh-event-listeners"]=115]="elements.refresh-event-listeners",e[e["coverage.clear"]=116]="coverage.clear",e[e["coverage.export"]=117]="coverage.export",e[e["timeline.dim-third-parties"]=118]="timeline.dim-third-parties",e[e.MAX_VALUE=119]="MAX_VALUE"}(oe||(oe={})),function(e){e[e["capture-node-creation-stacks"]=1]="capture-node-creation-stacks",e[e["live-heap-profile"]=11]="live-heap-profile",e[e["protocol-monitor"]=13]="protocol-monitor",e[e["sampling-heap-profiler-timeline"]=17]="sampling-heap-profiler-timeline",e[e["show-option-tp-expose-internals-in-heap-snapshot"]=18]="show-option-tp-expose-internals-in-heap-snapshot",e[e["timeline-invalidation-tracking"]=26]="timeline-invalidation-tracking",e[e["timeline-show-all-events"]=27]="timeline-show-all-events",e[e["timeline-v8-runtime-call-stats"]=28]="timeline-v8-runtime-call-stats",e[e.apca=39]="apca",e[e["font-editor"]=41]="font-editor",e[e["full-accessibility-tree"]=42]="full-accessibility-tree",e[e["contrast-issues"]=44]="contrast-issues",e[e["experimental-cookie-features"]=45]="experimental-cookie-features",e[e["instrumentation-breakpoints"]=61]="instrumentation-breakpoints",e[e["authored-deployed-grouping"]=63]="authored-deployed-grouping",e[e["just-my-code"]=65]="just-my-code",e[e["highlight-errors-elements-panel"]=73]="highlight-errors-elements-panel",e[e["use-source-map-scopes"]=76]="use-source-map-scopes",e[e["network-panel-filter-bar-redesign"]=79]="network-panel-filter-bar-redesign",e[e["timeline-show-postmessage-events"]=86]="timeline-show-postmessage-events",e[e["timeline-enhanced-traces"]=90]="timeline-enhanced-traces",e[e["timeline-compiled-sources"]=91]="timeline-compiled-sources",e[e["timeline-debug-mode"]=93]="timeline-debug-mode",e[e["timeline-experimental-insights"]=102]="timeline-experimental-insights",e[e["timeline-dim-unrelated-events"]=103]="timeline-dim-unrelated-events",e[e["timeline-alternative-navigation"]=104]="timeline-alternative-navigation",e[e.MAX_VALUE=106]="MAX_VALUE"}(se||(se={})),function(e){e[e.CrossOriginEmbedderPolicy=0]="CrossOriginEmbedderPolicy",e[e.MixedContent=1]="MixedContent",e[e.SameSiteCookie=2]="SameSiteCookie",e[e.HeavyAd=3]="HeavyAd",e[e.ContentSecurityPolicy=4]="ContentSecurityPolicy",e[e.Other=5]="Other",e[e.Generic=6]="Generic",e[e.ThirdPartyPhaseoutCookie=7]="ThirdPartyPhaseoutCookie",e[e.GenericCookie=8]="GenericCookie",e[e.MAX_VALUE=9]="MAX_VALUE"}(ie||(ie={})),function(e){e[e.CrossOriginEmbedderPolicyRequest=0]="CrossOriginEmbedderPolicyRequest",e[e.CrossOriginEmbedderPolicyElement=1]="CrossOriginEmbedderPolicyElement",e[e.MixedContentRequest=2]="MixedContentRequest",e[e.SameSiteCookieCookie=3]="SameSiteCookieCookie",e[e.SameSiteCookieRequest=4]="SameSiteCookieRequest",e[e.HeavyAdElement=5]="HeavyAdElement",e[e.ContentSecurityPolicyDirective=6]="ContentSecurityPolicyDirective",e[e.ContentSecurityPolicyElement=7]="ContentSecurityPolicyElement",e[e.MAX_VALUE=13]="MAX_VALUE"}(ae||(ae={})),function(e){e[e.MixedContentIssue=0]="MixedContentIssue",e[e["ContentSecurityPolicyIssue::kInlineViolation"]=1]="ContentSecurityPolicyIssue::kInlineViolation",e[e["ContentSecurityPolicyIssue::kEvalViolation"]=2]="ContentSecurityPolicyIssue::kEvalViolation",e[e["ContentSecurityPolicyIssue::kURLViolation"]=3]="ContentSecurityPolicyIssue::kURLViolation",e[e["ContentSecurityPolicyIssue::kTrustedTypesSinkViolation"]=4]="ContentSecurityPolicyIssue::kTrustedTypesSinkViolation",e[e["ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation"]=5]="ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation",e[e["HeavyAdIssue::NetworkTotalLimit"]=6]="HeavyAdIssue::NetworkTotalLimit",e[e["HeavyAdIssue::CpuTotalLimit"]=7]="HeavyAdIssue::CpuTotalLimit",e[e["HeavyAdIssue::CpuPeakLimit"]=8]="HeavyAdIssue::CpuPeakLimit",e[e["CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader"]=9]="CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader",e[e["CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage"]=10]="CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin"]=11]="CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep"]=12]="CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameSite"]=13]="CrossOriginEmbedderPolicyIssue::CorpNotSameSite",e[e["CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie"]=14]="CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie",e[e["CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie"]=15]="CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie",e[e["CookieIssue::WarnSameSiteNoneInsecure::ReadCookie"]=16]="CookieIssue::WarnSameSiteNoneInsecure::ReadCookie",e[e["CookieIssue::WarnSameSiteNoneInsecure::SetCookie"]=17]="CookieIssue::WarnSameSiteNoneInsecure::SetCookie",e[e["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure"]=18]="CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure",e[e["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure"]=19]="CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure",e[e["CookieIssue::WarnCrossDowngrade::ReadCookie::Secure"]=20]="CookieIssue::WarnCrossDowngrade::ReadCookie::Secure",e[e["CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure"]=21]="CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure",e[e["CookieIssue::WarnCrossDowngrade::SetCookie::Secure"]=22]="CookieIssue::WarnCrossDowngrade::SetCookie::Secure",e[e["CookieIssue::WarnCrossDowngrade::SetCookie::Insecure"]=23]="CookieIssue::WarnCrossDowngrade::SetCookie::Insecure",e[e["CookieIssue::ExcludeNavigationContextDowngrade::Secure"]=24]="CookieIssue::ExcludeNavigationContextDowngrade::Secure",e[e["CookieIssue::ExcludeNavigationContextDowngrade::Insecure"]=25]="CookieIssue::ExcludeNavigationContextDowngrade::Insecure",e[e["CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure"]=26]="CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure",e[e["CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure"]=27]="CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure",e[e["CookieIssue::ExcludeContextDowngrade::SetCookie::Secure"]=28]="CookieIssue::ExcludeContextDowngrade::SetCookie::Secure",e[e["CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure"]=29]="CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure",e[e["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie"]=30]="CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie",e[e["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie"]=31]="CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie"]=32]="CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie"]=33]="CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie"]=34]="CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie"]=35]="CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie",e[e["SharedArrayBufferIssue::TransferIssue"]=36]="SharedArrayBufferIssue::TransferIssue",e[e["SharedArrayBufferIssue::CreationIssue"]=37]="SharedArrayBufferIssue::CreationIssue",e[e.LowTextContrastIssue=41]="LowTextContrastIssue",e[e["CorsIssue::InsecurePrivateNetwork"]=42]="CorsIssue::InsecurePrivateNetwork",e[e["CorsIssue::InvalidHeaders"]=44]="CorsIssue::InvalidHeaders",e[e["CorsIssue::WildcardOriginWithCredentials"]=45]="CorsIssue::WildcardOriginWithCredentials",e[e["CorsIssue::PreflightResponseInvalid"]=46]="CorsIssue::PreflightResponseInvalid",e[e["CorsIssue::OriginMismatch"]=47]="CorsIssue::OriginMismatch",e[e["CorsIssue::AllowCredentialsRequired"]=48]="CorsIssue::AllowCredentialsRequired",e[e["CorsIssue::MethodDisallowedByPreflightResponse"]=49]="CorsIssue::MethodDisallowedByPreflightResponse",e[e["CorsIssue::HeaderDisallowedByPreflightResponse"]=50]="CorsIssue::HeaderDisallowedByPreflightResponse",e[e["CorsIssue::RedirectContainsCredentials"]=51]="CorsIssue::RedirectContainsCredentials",e[e["CorsIssue::DisallowedByMode"]=52]="CorsIssue::DisallowedByMode",e[e["CorsIssue::CorsDisabledScheme"]=53]="CorsIssue::CorsDisabledScheme",e[e["CorsIssue::PreflightMissingAllowExternal"]=54]="CorsIssue::PreflightMissingAllowExternal",e[e["CorsIssue::PreflightInvalidAllowExternal"]=55]="CorsIssue::PreflightInvalidAllowExternal",e[e["CorsIssue::NoCorsRedirectModeNotFollow"]=57]="CorsIssue::NoCorsRedirectModeNotFollow",e[e["QuirksModeIssue::QuirksMode"]=58]="QuirksModeIssue::QuirksMode",e[e["QuirksModeIssue::LimitedQuirksMode"]=59]="QuirksModeIssue::LimitedQuirksMode",e[e.DeprecationIssue=60]="DeprecationIssue",e[e["ClientHintIssue::MetaTagAllowListInvalidOrigin"]=61]="ClientHintIssue::MetaTagAllowListInvalidOrigin",e[e["ClientHintIssue::MetaTagModifiedHTML"]=62]="ClientHintIssue::MetaTagModifiedHTML",e[e["CorsIssue::PreflightAllowPrivateNetworkError"]=63]="CorsIssue::PreflightAllowPrivateNetworkError",e[e["GenericIssue::CrossOriginPortalPostMessageError"]=64]="GenericIssue::CrossOriginPortalPostMessageError",e[e["GenericIssue::FormLabelForNameError"]=65]="GenericIssue::FormLabelForNameError",e[e["GenericIssue::FormDuplicateIdForInputError"]=66]="GenericIssue::FormDuplicateIdForInputError",e[e["GenericIssue::FormInputWithNoLabelError"]=67]="GenericIssue::FormInputWithNoLabelError",e[e["GenericIssue::FormAutocompleteAttributeEmptyError"]=68]="GenericIssue::FormAutocompleteAttributeEmptyError",e[e["GenericIssue::FormEmptyIdAndNameAttributesForInputError"]=69]="GenericIssue::FormEmptyIdAndNameAttributesForInputError",e[e["GenericIssue::FormAriaLabelledByToNonExistingId"]=70]="GenericIssue::FormAriaLabelledByToNonExistingId",e[e["GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError"]=71]="GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError",e[e["GenericIssue::FormLabelHasNeitherForNorNestedInput"]=72]="GenericIssue::FormLabelHasNeitherForNorNestedInput",e[e["GenericIssue::FormLabelForMatchesNonExistingIdError"]=73]="GenericIssue::FormLabelForMatchesNonExistingIdError",e[e["GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError"]=74]="GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError",e[e["GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError"]=75]="GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError",e[e["StylesheetLoadingIssue::LateImportRule"]=76]="StylesheetLoadingIssue::LateImportRule",e[e["StylesheetLoadingIssue::RequestFailed"]=77]="StylesheetLoadingIssue::RequestFailed",e[e["CorsIssue::PreflightMissingPrivateNetworkAccessId"]=78]="CorsIssue::PreflightMissingPrivateNetworkAccessId",e[e["CorsIssue::PreflightMissingPrivateNetworkAccessName"]=79]="CorsIssue::PreflightMissingPrivateNetworkAccessName",e[e["CorsIssue::PrivateNetworkAccessPermissionUnavailable"]=80]="CorsIssue::PrivateNetworkAccessPermissionUnavailable",e[e["CorsIssue::PrivateNetworkAccessPermissionDenied"]=81]="CorsIssue::PrivateNetworkAccessPermissionDenied",e[e["CookieIssue::WarnThirdPartyPhaseout::ReadCookie"]=82]="CookieIssue::WarnThirdPartyPhaseout::ReadCookie",e[e["CookieIssue::WarnThirdPartyPhaseout::SetCookie"]=83]="CookieIssue::WarnThirdPartyPhaseout::SetCookie",e[e["CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie"]=84]="CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie",e[e["CookieIssue::ExcludeThirdPartyPhaseout::SetCookie"]=85]="CookieIssue::ExcludeThirdPartyPhaseout::SetCookie",e[e["SelectElementAccessibilityIssue::DisallowedSelectChild"]=86]="SelectElementAccessibilityIssue::DisallowedSelectChild",e[e["SelectElementAccessibilityIssue::DisallowedOptGroupChild"]=87]="SelectElementAccessibilityIssue::DisallowedOptGroupChild",e[e["SelectElementAccessibilityIssue::NonPhrasingContentOptionChild"]=88]="SelectElementAccessibilityIssue::NonPhrasingContentOptionChild",e[e["SelectElementAccessibilityIssue::InteractiveContentOptionChild"]=89]="SelectElementAccessibilityIssue::InteractiveContentOptionChild",e[e["SelectElementAccessibilityIssue::InteractiveContentLegendChild"]=90]="SelectElementAccessibilityIssue::InteractiveContentLegendChild",e[e["SRIMessageSignatureIssue::MissingSignatureHeader"]=91]="SRIMessageSignatureIssue::MissingSignatureHeader",e[e["SRIMessageSignatureIssue::MissingSignatureInputHeader"]=92]="SRIMessageSignatureIssue::MissingSignatureInputHeader",e[e["SRIMessageSignatureIssue::InvalidSignatureHeader"]=93]="SRIMessageSignatureIssue::InvalidSignatureHeader",e[e["SRIMessageSignatureIssue::InvalidSignatureInputHeader"]=94]="SRIMessageSignatureIssue::InvalidSignatureInputHeader",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence"]=95]="SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized"]=96]="SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength"]=97]="SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength",e[e["SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel"]=98]="SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel",e[e["SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList"]=99]="SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList",e[e["SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents"]=100]="SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType"]=101]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName"]=102]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter"]=103]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter"]=104]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength"]=105]="SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter"]=106]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters"]=107]="SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters",e[e["SRIMessageSignatureIssue::ValidationFailedSignatureExpired"]=108]="SRIMessageSignatureIssue::ValidationFailedSignatureExpired",e[e["SRIMessageSignatureIssue::ValidationFailedInvalidLength"]=109]="SRIMessageSignatureIssue::ValidationFailedInvalidLength",e[e["SRIMessageSignatureIssue::ValidationFailedSignatureMismatch"]=110]="SRIMessageSignatureIssue::ValidationFailedSignatureMismatch",e[e["CorsIssue::LocalNetworkAccessPermissionDenied"]=111]="CorsIssue::LocalNetworkAccessPermissionDenied",e[e["SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch"]=112]="SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch",e[e.MAX_VALUE=113]="MAX_VALUE"}(de||(de={})),function(e){e[e.af=1]="af",e[e.am=2]="am",e[e.ar=3]="ar",e[e.as=4]="as",e[e.az=5]="az",e[e.be=6]="be",e[e.bg=7]="bg",e[e.bn=8]="bn",e[e.bs=9]="bs",e[e.ca=10]="ca",e[e.cs=11]="cs",e[e.cy=12]="cy",e[e.da=13]="da",e[e.de=14]="de",e[e.el=15]="el",e[e["en-GB"]=16]="en-GB",e[e["en-US"]=17]="en-US",e[e["es-419"]=18]="es-419",e[e.es=19]="es",e[e.et=20]="et",e[e.eu=21]="eu",e[e.fa=22]="fa",e[e.fi=23]="fi",e[e.fil=24]="fil",e[e["fr-CA"]=25]="fr-CA",e[e.fr=26]="fr",e[e.gl=27]="gl",e[e.gu=28]="gu",e[e.he=29]="he",e[e.hi=30]="hi",e[e.hr=31]="hr",e[e.hu=32]="hu",e[e.hy=33]="hy",e[e.id=34]="id",e[e.is=35]="is",e[e.it=36]="it",e[e.ja=37]="ja",e[e.ka=38]="ka",e[e.kk=39]="kk",e[e.km=40]="km",e[e.kn=41]="kn",e[e.ko=42]="ko",e[e.ky=43]="ky",e[e.lo=44]="lo",e[e.lt=45]="lt",e[e.lv=46]="lv",e[e.mk=47]="mk",e[e.ml=48]="ml",e[e.mn=49]="mn",e[e.mr=50]="mr",e[e.ms=51]="ms",e[e.my=52]="my",e[e.ne=53]="ne",e[e.nl=54]="nl",e[e.no=55]="no",e[e.or=56]="or",e[e.pa=57]="pa",e[e.pl=58]="pl",e[e["pt-PT"]=59]="pt-PT",e[e.pt=60]="pt",e[e.ro=61]="ro",e[e.ru=62]="ru",e[e.si=63]="si",e[e.sk=64]="sk",e[e.sl=65]="sl",e[e.sq=66]="sq",e[e["sr-Latn"]=67]="sr-Latn",e[e.sr=68]="sr",e[e.sv=69]="sv",e[e.sw=70]="sw",e[e.ta=71]="ta",e[e.te=72]="te",e[e.th=73]="th",e[e.tr=74]="tr",e[e.uk=75]="uk",e[e.ur=76]="ur",e[e.uz=77]="uz",e[e.vi=78]="vi",e[e.zh=79]="zh",e[e["zh-HK"]=80]="zh-HK",e[e["zh-TW"]=81]="zh-TW",e[e.zu=82]="zu",e[e.MAX_VALUE=83]="MAX_VALUE"}(ce||(ce={})),function(e){e[e.OtherSection=0]="OtherSection",e[e.Identity=1]="Identity",e[e.Presentation=2]="Presentation",e[e["Protocol Handlers"]=3]="Protocol Handlers",e[e.Icons=4]="Icons",e[e["Window Controls Overlay"]=5]="Window Controls Overlay",e[e.MAX_VALUE=6]="MAX_VALUE"}(le||(le={}));var me=Object.freeze({__proto__:null,get Action(){return J},get DevtoolsExperiments(){return se},get ElementsSidebarTabCodes(){return re},get IssueCreated(){return de},get IssueExpanded(){return ie},get IssueResourceOpened(){return ae},get KeybindSetSettings(){return ne},get KeyboardShortcutAction(){return oe},get Language(){return ce},get ManifestSectionCodes(){return le},get MediaTypes(){return te},get PanelCodes(){return Z},get PanelWithLocation(){return ee},UserMetrics:ge});const pe=new ge,he=K();export{U as AidaClient,M as InspectorFrontendHost,i as InspectorFrontendHostAPI,X as Platform,ue as RNPerfMetrics,v as ResourceLoader,me as UserMetrics,he as rnPerfMetrics,pe as userMetrics}; +import*as e from"../common/common.js";import*as r from"../root/root.js";import*as t from"../i18n/i18n.js";import*as n from"../platform/platform.js";var o;!function(e){e.AppendedToURL="appendedToURL",e.CanceledSaveURL="canceledSaveURL",e.ColorThemeChanged="colorThemeChanged",e.ContextMenuCleared="contextMenuCleared",e.ContextMenuItemSelected="contextMenuItemSelected",e.DeviceCountUpdated="deviceCountUpdated",e.DevicesDiscoveryConfigChanged="devicesDiscoveryConfigChanged",e.DevicesPortForwardingStatusChanged="devicesPortForwardingStatusChanged",e.DevicesUpdated="devicesUpdated",e.DispatchMessage="dispatchMessage",e.DispatchMessageChunk="dispatchMessageChunk",e.EnterInspectElementMode="enterInspectElementMode",e.EyeDropperPickedColor="eyeDropperPickedColor",e.FileSystemsLoaded="fileSystemsLoaded",e.FileSystemRemoved="fileSystemRemoved",e.FileSystemAdded="fileSystemAdded",e.FileSystemFilesChangedAddedRemoved="FileSystemFilesChangedAddedRemoved",e.IndexingTotalWorkCalculated="indexingTotalWorkCalculated",e.IndexingWorked="indexingWorked",e.IndexingDone="indexingDone",e.KeyEventUnhandled="keyEventUnhandled",e.ReloadInspectedPage="reloadInspectedPage",e.RevealSourceLine="revealSourceLine",e.SavedURL="savedURL",e.SearchCompleted="searchCompleted",e.SetInspectedTabId="setInspectedTabId",e.SetUseSoftMenu="setUseSoftMenu",e.ShowPanel="showPanel"}(o||(o={}));const s=[[o.AppendedToURL,"appendedToURL",["url"]],[o.CanceledSaveURL,"canceledSaveURL",["url"]],[o.ColorThemeChanged,"colorThemeChanged",[]],[o.ContextMenuCleared,"contextMenuCleared",[]],[o.ContextMenuItemSelected,"contextMenuItemSelected",["id"]],[o.DeviceCountUpdated,"deviceCountUpdated",["count"]],[o.DevicesDiscoveryConfigChanged,"devicesDiscoveryConfigChanged",["config"]],[o.DevicesPortForwardingStatusChanged,"devicesPortForwardingStatusChanged",["status"]],[o.DevicesUpdated,"devicesUpdated",["devices"]],[o.DispatchMessage,"dispatchMessage",["messageObject"]],[o.DispatchMessageChunk,"dispatchMessageChunk",["messageChunk","messageSize"]],[o.EnterInspectElementMode,"enterInspectElementMode",[]],[o.EyeDropperPickedColor,"eyeDropperPickedColor",["color"]],[o.FileSystemsLoaded,"fileSystemsLoaded",["fileSystems"]],[o.FileSystemRemoved,"fileSystemRemoved",["fileSystemPath"]],[o.FileSystemAdded,"fileSystemAdded",["errorMessage","fileSystem"]],[o.FileSystemFilesChangedAddedRemoved,"fileSystemFilesChangedAddedRemoved",["changed","added","removed"]],[o.IndexingTotalWorkCalculated,"indexingTotalWorkCalculated",["requestId","fileSystemPath","totalWork"]],[o.IndexingWorked,"indexingWorked",["requestId","fileSystemPath","worked"]],[o.IndexingDone,"indexingDone",["requestId","fileSystemPath"]],[o.KeyEventUnhandled,"keyEventUnhandled",["event"]],[o.ReloadInspectedPage,"reloadInspectedPage",["hard"]],[o.RevealSourceLine,"revealSourceLine",["url","lineNumber","columnNumber"]],[o.SavedURL,"savedURL",["url","fileSystemPath"]],[o.SearchCompleted,"searchCompleted",["requestId","fileSystemPath","files"]],[o.SetInspectedTabId,"setInspectedTabId",["tabId"]],[o.SetUseSoftMenu,"setUseSoftMenu",["useSoftMenu"]],[o.ShowPanel,"showPanel",["panelName"]]];var i=Object.freeze({__proto__:null,EventDescriptors:s,get Events(){return o}});const a={systemError:"System error",connectionError:"Connection error",certificateError:"Certificate error",httpError:"HTTP error",cacheError:"Cache error",signedExchangeError:"Signed Exchange error",ftpError:"FTP error",certificateManagerError:"Certificate manager error",dnsResolverError:"DNS resolver error",unknownError:"Unknown error",httpErrorStatusCodeSS:"HTTP error: status code {PH1}, {PH2}",invalidUrl:"Invalid URL",decodingDataUrlFailed:"Decoding Data URL failed"},d=t.i18n.registerUIStrings("core/host/ResourceLoader.ts",a),c=t.i18n.getLocalizedString.bind(void 0,d);let l=0;const u={},g=function(e){return u[++l]=e,l},m=function(e){u[e].close(),delete u[e]},p=function(e,r){u[e].write(r)};function h(e,r,t){if(void 0===e||void 0===t)return null;if(0!==e){if(function(e){return e<=-300&&e>-400}(e))return c(a.httpErrorStatusCodeSS,{PH1:String(r),PH2:t});const n=function(e){return c(e>-100?a.systemError:e>-200?a.connectionError:e>-300?a.certificateError:e>-400?a.httpError:e>-500?a.cacheError:e>-600?a.signedExchangeError:e>-700?a.ftpError:e>-800?a.certificateManagerError:e>-900?a.dnsResolverError:a.unknownError)}(e);return`${n}: ${t}`}return null}const S=function(r,t,n,o,s){const i=g(n);if(new e.ParsedURL.ParsedURL(r).isDataURL())return void(e=>new Promise(((r,t)=>{const n=new XMLHttpRequest;n.withCredentials=!1,n.open("GET",e,!0),n.onreadystatechange=function(){if(n.readyState===XMLHttpRequest.DONE){if(200!==n.status)return n.onreadystatechange=null,void t(new Error(String(n.status)));n.onreadystatechange=null,r(n.responseText)}},n.send(null)})))(r).then((function(e){p(i,e),l({statusCode:200})})).catch((function(e){l({statusCode:404,messageOverride:c(a.decodingDataUrlFailed)})}));if(!s&&function(e){try{const r=new URL(e);return"file:"===r.protocol&&""!==r.host}catch{return!1}}(r))return void(o&&o(!1,{},{statusCode:400,netError:-20,netErrorName:"net::BLOCKED_BY_CLIENT",message:"Loading from a remote file path is prohibited for security reasons."}));const d=[];if(t)for(const e in t)d.push(e+": "+t[e]);function l(e){if(o){const{success:r,description:t}=function(e){const{statusCode:r,netError:t,netErrorName:n,urlValid:o,messageOverride:s}=e;let i="";const d=r>=200&&r<300;if("string"==typeof s)i=s;else if(!d)if(void 0===t)i=c(!1===o?a.invalidUrl:a.unknownError);else{const e=h(t,r,n);e&&(i=e)}return console.assert(d===(0===i.length)),{success:d,description:{statusCode:r,netError:t,netErrorName:n,urlValid:o,message:i}}}(e);o(r,e.headers||{},t)}m(i)}f.loadNetworkResource(r,d.join("\r\n"),i,l)};var v=Object.freeze({__proto__:null,ResourceLoader:{},bindOutputStream:g,discardOutputStream:m,load:function(r,t,n,o){const s=new e.StringOutputStream.StringOutputStream;S(r,t,s,(function(e,r,t){n(e,r,s.data(),t)}),o)},loadAsStream:S,netErrorToMessage:h,streamWrite:p});const C={devtoolsS:"DevTools - {PH1}"},I=t.i18n.registerUIStrings("core/host/InspectorFrontendHost.ts",C),w=t.i18n.getLocalizedString.bind(void 0,I),k="/overrides";class E{#e=new Map;events;#r=null;recordedCountHistograms=[];recordedEnumeratedHistograms=[];recordedPerformanceHistograms=[];constructor(){function e(e){!("mac"===this.platform()?e.metaKey:e.ctrlKey)||"+"!==e.key&&"-"!==e.key||e.stopPropagation()}"undefined"!=typeof document&&document.addEventListener("keydown",(r=>{e.call(this,r)}),!0)}platform(){const e=navigator.userAgent;return e.includes("Windows NT")?"windows":e.includes("Mac OS X")?"mac":"linux"}loadCompleted(){}bringToFront(){}closeWindow(){}setIsDocked(e,r){window.setTimeout(r,0)}showSurvey(e,r){window.setTimeout((()=>r({surveyShown:!1})),0)}canShowSurvey(e,r){window.setTimeout((()=>r({canShowSurvey:!1})),0)}setInspectedPageBounds(e){}inspectElementCompleted(){}setInjectedScriptForOrigin(e,r){}inspectedURLChanged(e){document.title=w(C.devtoolsS,{PH1:e.replace(/^https?:\/\//,"")})}copyText(e){null!=e&&navigator.clipboard.writeText(e)}openInNewTab(r){e.ParsedURL.schemeIs(r,"javascript:")||window.open(r,"_blank")}openSearchResultsInNewTab(r){e.Console.Console.instance().error("Search is not enabled in hosted mode. Please inspect using chrome://inspect")}showItemInFolder(r){e.Console.Console.instance().error("Show item in folder is not enabled in hosted mode. Please inspect using chrome://inspect")}save(e,r,t,n){let s=this.#e.get(e);s||(s=[],this.#e.set(e,s)),s.push(r),this.events.dispatchEventToListeners(o.SavedURL,{url:e,fileSystemPath:e})}append(e,r){const t=this.#e.get(e);t&&(t.push(r),this.events.dispatchEventToListeners(o.AppendedToURL,e))}close(e){const r=this.#e.get(e)||[];this.#e.delete(e);let t="";if(e)try{const r=n.StringUtilities.trimURL(e);t=n.StringUtilities.removeURLFragment(r)}catch(r){t=e}const o=document.createElement("a");o.download=t;const s=new Blob([r.join("")],{type:"text/plain"}),i=URL.createObjectURL(s);o.href=i,o.click(),URL.revokeObjectURL(i)}sendMessageToBackend(e){}recordCountHistogram(e,r,t,n,o){this.recordedCountHistograms.length>=100&&this.recordedCountHistograms.shift(),this.recordedCountHistograms.push({histogramName:e,sample:r,min:t,exclusiveMax:n,bucketSize:o})}recordEnumeratedHistogram(e,r,t){this.recordedEnumeratedHistograms.length>=100&&this.recordedEnumeratedHistograms.shift(),this.recordedEnumeratedHistograms.push({actionName:e,actionCode:r})}recordPerformanceHistogram(e,r){this.recordedPerformanceHistograms.length>=100&&this.recordedPerformanceHistograms.shift(),this.recordedPerformanceHistograms.push({histogramName:e,duration:r})}recordUserMetricsAction(e){}connectAutomaticFileSystem(e,r,t,n){queueMicrotask((()=>n({success:!1})))}disconnectAutomaticFileSystem(e){}requestFileSystems(){this.events.dispatchEventToListeners(o.FileSystemsLoaded,[])}addFileSystem(e){window.webkitRequestFileSystem(window.TEMPORARY,1048576,(e=>{this.#r=e;const r={fileSystemName:"sandboxedRequestedFileSystem",fileSystemPath:k,rootURL:"filesystem:devtools://devtools/isolated/",type:"overrides"};this.events.dispatchEventToListeners(o.FileSystemAdded,{fileSystem:r})}))}removeFileSystem(e){const r=e=>{e.forEach((e=>{e.isDirectory?e.removeRecursively((()=>{})):e.isFile&&e.remove((()=>{}))}))};this.#r&&this.#r.root.createReader().readEntries(r),this.#r=null,this.events.dispatchEventToListeners(o.FileSystemRemoved,k)}isolatedFileSystem(e,r){return this.#r}loadNetworkResource(e,r,t,n){fetch(e).then((async e=>{const r=await e.arrayBuffer();let t=r;if(function(e){const r=new Uint8Array(e);return!(!r||r.length<3)&&31===r[0]&&139===r[1]&&8===r[2]}(r)){const e=new DecompressionStream("gzip"),n=e.writable.getWriter();n.write(r),n.close(),t=e.readable}return await new Response(t).text()})).then((function(e){p(t,e),n({statusCode:200,headers:void 0,messageOverride:void 0,netError:void 0,netErrorName:void 0,urlValid:void 0})})).catch((function(){n({statusCode:404,headers:void 0,messageOverride:void 0,netError:void 0,netErrorName:void 0,urlValid:void 0})}))}registerPreference(e,r){}getPreferences(e){const r={};for(const e in window.localStorage)r[e]=window.localStorage[e];e(r)}getPreference(e,r){r(window.localStorage[e])}setPreference(e,r){window.localStorage[e]=r}removePreference(e){delete window.localStorage[e]}clearPreferences(){window.localStorage.clear()}getSyncInformation(e){if("getSyncInformationForTesting"in globalThis)return e(globalThis.getSyncInformationForTesting());e({isSyncActive:!1,arePreferencesSynced:!1})}getHostConfig(e){const r={devToolsVeLogging:{enabled:!0},thirdPartyCookieControls:{thirdPartyCookieMetadataEnabled:!0,thirdPartyCookieHeuristicsEnabled:!0,managedBlockThirdPartyCookies:"Unset"}};if("hostConfigForTesting"in globalThis){const{hostConfigForTesting:e}=globalThis;for(const t of Object.keys(e)){const n=t=>{"object"==typeof r[t]&&"object"==typeof e[t]?r[t]={...r[t],...e[t]}:r[t]=e[t]??r[t]};n(t)}}e(r)}upgradeDraggedFileSystemPermissions(e){}indexPath(e,r,t){}stopIndexing(e){}searchInPath(e,r,t){}zoomFactor(){return 1}zoomIn(){}zoomOut(){}resetZoom(){}setWhitelistedShortcuts(e){}setEyeDropperActive(e){}showCertificateViewer(e){}reattach(e){e()}readyForTest(){}connectionReady(){}setOpenNewWindowForPopups(e){}setDevicesDiscoveryConfig(e){}setDevicesUpdatesEnabled(e){}openRemotePage(e,r){}openNodeFrontend(){}showContextMenuAtPoint(e,r,t,n){throw new Error("Soft context menu should be used")}isHostedMode(){return!0}setAddExtensionCallback(e){}async initialTargetId(){return null}doAidaConversation(e,r,t){t({error:"Not implemented"})}registerAidaClientEvent(e,r){r({error:"Not implemented"})}recordImpression(e){}recordResize(e){}recordClick(e){}recordHover(e){}recordDrag(e){}recordChange(e){}recordKeyDown(e){}recordSettingAccess(e){}}let f=globalThis.InspectorFrontendHost;class y{constructor(){for(const e of s)this[e[1]]=this.dispatch.bind(this,e[0],e[2],e[3])}dispatch(e,r,t,...n){if(r.length<2){try{f.events.dispatchEventToListeners(e,n[0])}catch(e){console.error(e+" "+e.stack)}return}const o={};for(let e=0;e=0&&(o.options??={},o.options.temperature=i),s&&(o.options??={},o.options.model_id=s),o}static async checkAccessPreconditions(){if(!navigator.onLine)return"no-internet";const e=await new Promise((e=>f.getSyncInformation((r=>e(r)))));return e.accountEmail?e.isSyncPaused?"sync-is-paused":"available":"no-account-email"}async*fetch(e,r){if(!f.doAidaConversation)throw new Error("doAidaConversation is not available");const t=(()=>{let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return r?.signal?.addEventListener("abort",(()=>{n(new O)}),{once:!0}),{write:async r=>{t(r),({promise:e,resolve:t,reject:n}=Promise.withResolvers())},close:async()=>{t(null)},read:()=>e,fail:e=>n(e)}})(),n=g(t);let o;f.doAidaConversation(JSON.stringify(e),n,(e=>{403===e.statusCode?t.fail(new Error("Server responded: permission denied")):e.error?t.fail(new Error(`Cannot send request: ${e.error} ${e.detail||""}`)):"net::ERR_TIMED_OUT"===e.netErrorName?t.fail(new Error("doAidaConversation timed out")):200!==e.statusCode?t.fail(new Error(`Request failed: ${JSON.stringify(e)}`)):t.close()}));const s=[];let i=!1;const a=[];let d={rpcGlobalId:0};for(;o=await t.read();){let e,r=!1;if(o.length){o.startsWith(",")&&(o=o.slice(1)),o.startsWith("[")||(o="["+o),o.endsWith("]")||(o+="]");try{e=JSON.parse(o)}catch(e){throw new Error("Cannot parse chunk: "+o,{cause:e})}for(const t of e){if("metadata"in t&&(d=t.metadata,d?.attributionMetadata?.attributionAction===T.BLOCK))throw new L;if("textChunk"in t)i&&(s.push(_),i=!1),s.push(t.textChunk.text),r=!0;else if("codeChunk"in t)i||(s.push(_),i=!0),s.push(t.codeChunk.code),r=!0;else{if(!("functionCallChunk"in t))throw"error"in t?new Error(`Server responded: ${JSON.stringify(t)}`):new Error("Unknown chunk result");a.push({name:t.functionCallChunk.functionCall.name,args:t.functionCallChunk.functionCall.args})}}r&&(yield{explanation:s.join("")+(i?_:""),metadata:d,completed:!1})}}yield{explanation:s.join("")+(i?_:""),metadata:d,functionCalls:a.length?a:void 0,completed:!0}}registerClientEvent(e){const{promise:r,resolve:t}=Promise.withResolvers();return f.registerAidaClientEvent(JSON.stringify({client:F,event_time:(new Date).toISOString(),...e}),t),r}}let D;class H extends e.ObjectWrapper.ObjectWrapper{#t;#n;constructor(){super()}static instance(){return D||(D=new H),D}addEventListener(e,r){const t=!this.hasEventListeners(e),n=super.addEventListener(e,r);return t&&(window.clearTimeout(this.#t),this.pollAidaAvailability()),n}removeEventListener(e,r){super.removeEventListener(e,r),this.hasEventListeners(e)||window.clearTimeout(this.#t)}async pollAidaAvailability(){this.#t=window.setTimeout((()=>this.pollAidaAvailability()),2e3);const e=await N.checkAccessPreconditions();if(e!==this.#n){this.#n=e;const t=await new Promise((e=>f.getHostConfig(e)));Object.assign(r.Runtime.hostConfig,t),this.dispatchEventToListeners("aidaAvailabilityChanged")}}}var U=Object.freeze({__proto__:null,AidaAbortError:O,AidaBlockError:L,AidaClient:N,CLIENT_NAME:F,get CitationSourceType(){return x},get ClientFeature(){return P},get FunctionalityType(){return A},HostConfigTracker:H,get RecitationAction(){return T},get Role(){return b},get UserTier(){return R},convertToUserTierEnum:function(e){if(e)switch(e){case"TESTERS":return R.TESTERS;case"BETA":return R.BETA;case"PUBLIC":return R.PUBLIC}return R.BETA}});let W,B,V,G,j;function q(){return W||(W=f.platform()),W}var X=Object.freeze({__proto__:null,fontFamily:function(){if(j)return j;switch(q()){case"linux":j="Roboto, Ubuntu, Arial, sans-serif";break;case"mac":j="'Lucida Grande', sans-serif";break;case"windows":j="'Segoe UI', Tahoma, sans-serif"}return j},isCustomDevtoolsFrontend:function(){return void 0===G&&(G=window.location.toString().startsWith("devtools://devtools/custom/")),G},isMac:function(){return void 0===B&&(B="mac"===q()),B},isWin:function(){return void 0===V&&(V="windows"===q()),V},platform:q,setPlatformForTests:function(e){W=e,B=void 0,V=void 0}});let z=null;function K(){return null===z&&(z=new $),z}class ${#o="error";#s=new Set;#i=null;#a=null;#d="rn_inspector";#c={};#l=new Map;addEventListener(e){this.#s.add(e);return()=>{this.#s.delete(e)}}removeAllEventListeners(){this.#s.clear()}sendEvent(e){if(!0!==globalThis.enableReactNativePerfMetrics)return;const r=this.#u(e),t=[];for(const e of this.#s)try{e(r)}catch(e){t.push(e)}if(t.length>0){const e=new AggregateError(t);console.error("Error occurred when calling event listeners",e)}}registerPerfMetricsGlobalPostMessageHandler(){!0===globalThis.enableReactNativePerfMetrics&&!0===globalThis.enableReactNativePerfMetricsGlobalPostMessage&&this.addEventListener((e=>{window.postMessage({event:e,tag:"react-native-chrome-devtools-perf-metrics"},window.location.origin)}))}registerGlobalErrorReporting(){window.addEventListener("error",(e=>{const[r,t]=Y(`[RNPerfMetrics] uncaught error: ${e.message}`,e.error);this.sendEvent({eventName:"Browser.Error",params:{type:"error",message:r,error:t}})}),{passive:!0}),window.addEventListener("unhandledrejection",(e=>{const[r,t]=Y("[RNPerfMetrics] unhandled promise rejection",e.reason);this.sendEvent({eventName:"Browser.Error",params:{type:"rejectedPromise",message:r,error:t}})}),{passive:!0});const e=globalThis.console,r=e[this.#o];e[this.#o]=(...t)=>{try{const e=t[0],[r,n]=Y("[RNPerfMetrics] console.error",e);this.sendEvent({eventName:"Browser.Error",params:{message:r,error:n,type:"consoleError"}})}catch(e){const[r,t]=Y("[RNPerfMetrics] Error handling console.error",e);this.sendEvent({eventName:"Browser.Error",params:{message:r,error:t,type:"consoleError"}})}finally{r.apply(e,t)}}}setLaunchId(e){this.#i=e}setAppId(e){this.#a=e}setTelemetryInfo(e){this.#c=e}entryPointLoadingStarted(e){this.#d=e,this.sendEvent({eventName:"Entrypoint.LoadingStarted",entryPoint:e})}entryPointLoadingFinished(e){this.sendEvent({eventName:"Entrypoint.LoadingFinished",entryPoint:e})}browserVisibilityChanged(e){this.sendEvent({eventName:"Browser.VisibilityChange",params:{visibilityState:e}})}remoteDebuggingTerminated(e={}){this.sendEvent({eventName:"Connection.DebuggingTerminated",params:e})}developerResourceLoadingStarted(e,r){const t=Q(e);this.sendEvent({eventName:"DeveloperResource.LoadingStarted",params:{url:t,loadingMethod:r}})}developerResourceLoadingFinished(e,r,t){const n=Q(e);this.sendEvent({eventName:"DeveloperResource.LoadingFinished",params:{url:n,loadingMethod:r,success:t.success,errorMessage:t.errorDescription?.message}})}fuseboxSetClientMetadataStarted(){this.sendEvent({eventName:"FuseboxSetClientMetadataStarted"})}fuseboxSetClientMetadataFinished(e,r){if(e)this.sendEvent({eventName:"FuseboxSetClientMetadataFinished",params:{success:!0}});else{const[e,t]=Y("[RNPerfMetrics] Fusebox setClientMetadata failed",r);this.sendEvent({eventName:"FuseboxSetClientMetadataFinished",params:{success:!1,error:t,errorMessage:e}})}}heapSnapshotStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"snapshot"}})}heapSnapshotFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"snapshot",success:e}})}heapProfilingStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"profiling"}})}heapProfilingFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"profiling",success:e}})}heapSamplingStarted(){this.sendEvent({eventName:"MemoryPanelActionStarted",params:{action:"sampling"}})}heapSamplingFinished(e){this.sendEvent({eventName:"MemoryPanelActionFinished",params:{action:"sampling",success:e}})}stackTraceSymbolicationFailed(e,r,t){this.sendEvent({eventName:"StackTraceSymbolicationFailed",params:{stackTrace:e,line:r,reason:t}})}stackTraceSymbolicationSucceeded(e){this.sendEvent({eventName:"StackTraceSymbolicationSucceeded",params:{specialHermesFrameTypes:e}})}panelShown(e,r){}panelShownInLocation(e,r){this.sendEvent({eventName:"PanelShown",params:{location:r,newPanelName:e}}),this.#l.set(r,e)}#u(e){return{...e,...{timestamp:performance.timeOrigin+performance.now(),launchId:this.#i,appId:this.#a,entryPoint:this.#d,telemetryInfo:this.#c,currentPanels:this.#l}}}}function Q(e){const{url:r}=e;return"http"===e.scheme||"https"===e.scheme?r:`${r.slice(0,100)} …(omitted ${r.length-100} characters)`}function Y(e,r){if(r instanceof Error){return[`${e}: ${r.message}`,r]}const t=`${e}: ${String(r)}`;return[t,new Error(t,{cause:r})]}var J,Z,ee,re,te,ne,oe,se,ie,ae,de,ce,le,ue=Object.freeze({__proto__:null,getInstance:K});class ge{#g;#m;#p;constructor(){this.#g=!1,this.#m=!1,this.#p=""}panelShown(e,r){const t=Z[e]||0;f.recordEnumeratedHistogram("DevTools.PanelShown",t,Z.MAX_VALUE),f.recordUserMetricsAction("DevTools_PanelShown_"+e),r||(this.#g=!0),K().panelShown(e,r)}panelShownInLocation(e,r){const t=ee[`${e}-${r}`]||0;f.recordEnumeratedHistogram("DevTools.PanelShownInLocation",t,ee.MAX_VALUE),K().panelShownInLocation(e,r)}settingsPanelShown(e){this.panelShown("settings-"+e)}sourcesPanelFileDebugged(e){const r=e&&te[e]||te.Unknown;f.recordEnumeratedHistogram("DevTools.SourcesPanelFileDebugged",r,te.MAX_VALUE)}sourcesPanelFileOpened(e){const r=e&&te[e]||te.Unknown;f.recordEnumeratedHistogram("DevTools.SourcesPanelFileOpened",r,te.MAX_VALUE)}networkPanelResponsePreviewOpened(e){const r=e&&te[e]||te.Unknown;f.recordEnumeratedHistogram("DevTools.NetworkPanelResponsePreviewOpened",r,te.MAX_VALUE)}actionTaken(e){f.recordEnumeratedHistogram("DevTools.ActionTaken",e,J.MAX_VALUE)}panelLoaded(e,r){this.#m||e!==this.#p||(this.#m=!0,requestAnimationFrame((()=>{window.setTimeout((()=>{performance.mark(r),this.#g||f.recordPerformanceHistogram(r,performance.now())}),0)})))}setLaunchPanel(e){this.#p=e}performanceTraceLoad(e){f.recordPerformanceHistogram("DevTools.TraceLoad",e.duration)}keybindSetSettingChanged(e){const r=ne[e]||0;f.recordEnumeratedHistogram("DevTools.KeybindSetSettingChanged",r,ne.MAX_VALUE)}keyboardShortcutFired(e){const r=oe[e]||oe.OtherShortcut;f.recordEnumeratedHistogram("DevTools.KeyboardShortcutFired",r,oe.MAX_VALUE)}issuesPanelOpenedFrom(e){f.recordEnumeratedHistogram("DevTools.IssuesPanelOpenedFrom",e,6)}issuesPanelIssueExpanded(e){if(void 0===e)return;const r=ie[e];void 0!==r&&f.recordEnumeratedHistogram("DevTools.IssuesPanelIssueExpanded",r,ie.MAX_VALUE)}issuesPanelResourceOpened(e,r){const t=ae[e+r];void 0!==t&&f.recordEnumeratedHistogram("DevTools.IssuesPanelResourceOpened",t,ae.MAX_VALUE)}issueCreated(e){const r=de[e];void 0!==r&&f.recordEnumeratedHistogram("DevTools.IssueCreated",r,de.MAX_VALUE)}experimentEnabledAtLaunch(e){const r=se[e];void 0!==r&&f.recordEnumeratedHistogram("DevTools.ExperimentEnabledAtLaunch",r,se.MAX_VALUE)}navigationSettingAtFirstTimelineLoad(e){f.recordEnumeratedHistogram("DevTools.TimelineNavigationSettingState",e,4)}experimentDisabledAtLaunch(e){const r=se[e];void 0!==r&&f.recordEnumeratedHistogram("DevTools.ExperimentDisabledAtLaunch",r,se.MAX_VALUE)}experimentChanged(e,r){const t=se[e];if(void 0===t)return;const n=r?"DevTools.ExperimentEnabled":"DevTools.ExperimentDisabled";f.recordEnumeratedHistogram(n,t,se.MAX_VALUE)}developerResourceLoaded(e){e>=8||f.recordEnumeratedHistogram("DevTools.DeveloperResourceLoaded",e,8)}developerResourceScheme(e){e>=9||f.recordEnumeratedHistogram("DevTools.DeveloperResourceScheme",e,9)}language(e){const r=ce[e];void 0!==r&&f.recordEnumeratedHistogram("DevTools.Language",r,ce.MAX_VALUE)}syncSetting(e){f.getSyncInformation((r=>{let t=1;r.isSyncActive&&!r.arePreferencesSynced?t=2:r.isSyncActive&&r.arePreferencesSynced&&(t=e?4:3),f.recordEnumeratedHistogram("DevTools.SyncSetting",t,5)}))}recordingAssertion(e){f.recordEnumeratedHistogram("DevTools.RecordingAssertion",e,4)}recordingToggled(e){f.recordEnumeratedHistogram("DevTools.RecordingToggled",e,3)}recordingReplayFinished(e){f.recordEnumeratedHistogram("DevTools.RecordingReplayFinished",e,5)}recordingReplaySpeed(e){f.recordEnumeratedHistogram("DevTools.RecordingReplaySpeed",e,5)}recordingReplayStarted(e){f.recordEnumeratedHistogram("DevTools.RecordingReplayStarted",e,4)}recordingEdited(e){f.recordEnumeratedHistogram("DevTools.RecordingEdited",e,11)}recordingExported(e){f.recordEnumeratedHistogram("DevTools.RecordingExported",e,6)}recordingCodeToggled(e){f.recordEnumeratedHistogram("DevTools.RecordingCodeToggled",e,3)}recordingCopiedToClipboard(e){f.recordEnumeratedHistogram("DevTools.RecordingCopiedToClipboard",e,9)}cssHintShown(e){f.recordEnumeratedHistogram("DevTools.CSSHintShown",e,14)}lighthouseModeRun(e){f.recordEnumeratedHistogram("DevTools.LighthouseModeRun",e,4)}lighthouseCategoryUsed(e){f.recordEnumeratedHistogram("DevTools.LighthouseCategoryUsed",e,6)}swatchActivated(e){f.recordEnumeratedHistogram("DevTools.SwatchActivated",e,11)}animationPlaybackRateChanged(e){f.recordEnumeratedHistogram("DevTools.AnimationPlaybackRateChanged",e,4)}animationPointDragged(e){f.recordEnumeratedHistogram("DevTools.AnimationPointDragged",e,5)}workspacesPopulated(e){f.recordPerformanceHistogram("DevTools.Workspaces.PopulateWallClocktime",e)}visualLoggingProcessingDone(e){f.recordPerformanceHistogram("DevTools.VisualLogging.ProcessingTime",e)}freestylerQueryLength(e){f.recordCountHistogram("DevTools.Freestyler.QueryLength",e,0,1e5,100)}freestylerEvalResponseSize(e){f.recordCountHistogram("DevTools.Freestyler.EvalResponseSize",e,0,1e5,100)}}!function(e){e[e.WindowDocked=1]="WindowDocked",e[e.WindowUndocked=2]="WindowUndocked",e[e.ScriptsBreakpointSet=3]="ScriptsBreakpointSet",e[e.TimelineStarted=4]="TimelineStarted",e[e.ProfilesCPUProfileTaken=5]="ProfilesCPUProfileTaken",e[e.ProfilesHeapProfileTaken=6]="ProfilesHeapProfileTaken",e[e.ConsoleEvaluated=8]="ConsoleEvaluated",e[e.FileSavedInWorkspace=9]="FileSavedInWorkspace",e[e.DeviceModeEnabled=10]="DeviceModeEnabled",e[e.AnimationsPlaybackRateChanged=11]="AnimationsPlaybackRateChanged",e[e.RevisionApplied=12]="RevisionApplied",e[e.FileSystemDirectoryContentReceived=13]="FileSystemDirectoryContentReceived",e[e.StyleRuleEdited=14]="StyleRuleEdited",e[e.CommandEvaluatedInConsolePanel=15]="CommandEvaluatedInConsolePanel",e[e.DOMPropertiesExpanded=16]="DOMPropertiesExpanded",e[e.ResizedViewInResponsiveMode=17]="ResizedViewInResponsiveMode",e[e.TimelinePageReloadStarted=18]="TimelinePageReloadStarted",e[e.ConnectToNodeJSFromFrontend=19]="ConnectToNodeJSFromFrontend",e[e.ConnectToNodeJSDirectly=20]="ConnectToNodeJSDirectly",e[e.CpuThrottlingEnabled=21]="CpuThrottlingEnabled",e[e.CpuProfileNodeFocused=22]="CpuProfileNodeFocused",e[e.CpuProfileNodeExcluded=23]="CpuProfileNodeExcluded",e[e.SelectFileFromFilePicker=24]="SelectFileFromFilePicker",e[e.SelectCommandFromCommandMenu=25]="SelectCommandFromCommandMenu",e[e.ChangeInspectedNodeInElementsPanel=26]="ChangeInspectedNodeInElementsPanel",e[e.StyleRuleCopied=27]="StyleRuleCopied",e[e.CoverageStarted=28]="CoverageStarted",e[e.LighthouseStarted=29]="LighthouseStarted",e[e.LighthouseFinished=30]="LighthouseFinished",e[e.ShowedThirdPartyBadges=31]="ShowedThirdPartyBadges",e[e.LighthouseViewTrace=32]="LighthouseViewTrace",e[e.FilmStripStartedRecording=33]="FilmStripStartedRecording",e[e.CoverageReportFiltered=34]="CoverageReportFiltered",e[e.CoverageStartedPerBlock=35]="CoverageStartedPerBlock",e[e["SettingsOpenedFromGear-deprecated"]=36]="SettingsOpenedFromGear-deprecated",e[e["SettingsOpenedFromMenu-deprecated"]=37]="SettingsOpenedFromMenu-deprecated",e[e["SettingsOpenedFromCommandMenu-deprecated"]=38]="SettingsOpenedFromCommandMenu-deprecated",e[e.TabMovedToDrawer=39]="TabMovedToDrawer",e[e.TabMovedToMainPanel=40]="TabMovedToMainPanel",e[e.CaptureCssOverviewClicked=41]="CaptureCssOverviewClicked",e[e.VirtualAuthenticatorEnvironmentEnabled=42]="VirtualAuthenticatorEnvironmentEnabled",e[e.SourceOrderViewActivated=43]="SourceOrderViewActivated",e[e.UserShortcutAdded=44]="UserShortcutAdded",e[e.ShortcutRemoved=45]="ShortcutRemoved",e[e.ShortcutModified=46]="ShortcutModified",e[e.CustomPropertyLinkClicked=47]="CustomPropertyLinkClicked",e[e.CustomPropertyEdited=48]="CustomPropertyEdited",e[e.ServiceWorkerNetworkRequestClicked=49]="ServiceWorkerNetworkRequestClicked",e[e.ServiceWorkerNetworkRequestClosedQuickly=50]="ServiceWorkerNetworkRequestClosedQuickly",e[e.NetworkPanelServiceWorkerRespondWith=51]="NetworkPanelServiceWorkerRespondWith",e[e.NetworkPanelCopyValue=52]="NetworkPanelCopyValue",e[e.ConsoleSidebarOpened=53]="ConsoleSidebarOpened",e[e.PerfPanelTraceImported=54]="PerfPanelTraceImported",e[e.PerfPanelTraceExported=55]="PerfPanelTraceExported",e[e.StackFrameRestarted=56]="StackFrameRestarted",e[e.CaptureTestProtocolClicked=57]="CaptureTestProtocolClicked",e[e.BreakpointRemovedFromRemoveButton=58]="BreakpointRemovedFromRemoveButton",e[e.BreakpointGroupExpandedStateChanged=59]="BreakpointGroupExpandedStateChanged",e[e.HeaderOverrideFileCreated=60]="HeaderOverrideFileCreated",e[e.HeaderOverrideEnableEditingClicked=61]="HeaderOverrideEnableEditingClicked",e[e.HeaderOverrideHeaderAdded=62]="HeaderOverrideHeaderAdded",e[e.HeaderOverrideHeaderEdited=63]="HeaderOverrideHeaderEdited",e[e.HeaderOverrideHeaderRemoved=64]="HeaderOverrideHeaderRemoved",e[e.HeaderOverrideHeadersFileEdited=65]="HeaderOverrideHeadersFileEdited",e[e.PersistenceNetworkOverridesEnabled=66]="PersistenceNetworkOverridesEnabled",e[e.PersistenceNetworkOverridesDisabled=67]="PersistenceNetworkOverridesDisabled",e[e.BreakpointRemovedFromContextMenu=68]="BreakpointRemovedFromContextMenu",e[e.BreakpointsInFileRemovedFromRemoveButton=69]="BreakpointsInFileRemovedFromRemoveButton",e[e.BreakpointsInFileRemovedFromContextMenu=70]="BreakpointsInFileRemovedFromContextMenu",e[e.BreakpointsInFileCheckboxToggled=71]="BreakpointsInFileCheckboxToggled",e[e.BreakpointsInFileEnabledDisabledFromContextMenu=72]="BreakpointsInFileEnabledDisabledFromContextMenu",e[e.BreakpointConditionEditedFromSidebar=73]="BreakpointConditionEditedFromSidebar",e[e.WorkspaceTabAddFolder=74]="WorkspaceTabAddFolder",e[e.WorkspaceTabRemoveFolder=75]="WorkspaceTabRemoveFolder",e[e.OverrideTabAddFolder=76]="OverrideTabAddFolder",e[e.OverrideTabRemoveFolder=77]="OverrideTabRemoveFolder",e[e.WorkspaceSourceSelected=78]="WorkspaceSourceSelected",e[e.OverridesSourceSelected=79]="OverridesSourceSelected",e[e.StyleSheetInitiatorLinkClicked=80]="StyleSheetInitiatorLinkClicked",e[e.BreakpointRemovedFromGutterContextMenu=81]="BreakpointRemovedFromGutterContextMenu",e[e.BreakpointRemovedFromGutterToggle=82]="BreakpointRemovedFromGutterToggle",e[e.StylePropertyInsideKeyframeEdited=83]="StylePropertyInsideKeyframeEdited",e[e.OverrideContentFromSourcesContextMenu=84]="OverrideContentFromSourcesContextMenu",e[e.OverrideContentFromNetworkContextMenu=85]="OverrideContentFromNetworkContextMenu",e[e.OverrideScript=86]="OverrideScript",e[e.OverrideStyleSheet=87]="OverrideStyleSheet",e[e.OverrideDocument=88]="OverrideDocument",e[e.OverrideFetchXHR=89]="OverrideFetchXHR",e[e.OverrideImage=90]="OverrideImage",e[e.OverrideFont=91]="OverrideFont",e[e.OverrideContentContextMenuSetup=92]="OverrideContentContextMenuSetup",e[e.OverrideContentContextMenuAbandonSetup=93]="OverrideContentContextMenuAbandonSetup",e[e.OverrideContentContextMenuActivateDisabled=94]="OverrideContentContextMenuActivateDisabled",e[e.OverrideContentContextMenuOpenExistingFile=95]="OverrideContentContextMenuOpenExistingFile",e[e.OverrideContentContextMenuSaveNewFile=96]="OverrideContentContextMenuSaveNewFile",e[e.ShowAllOverridesFromSourcesContextMenu=97]="ShowAllOverridesFromSourcesContextMenu",e[e.ShowAllOverridesFromNetworkContextMenu=98]="ShowAllOverridesFromNetworkContextMenu",e[e.AnimationGroupsCleared=99]="AnimationGroupsCleared",e[e.AnimationsPaused=100]="AnimationsPaused",e[e.AnimationsResumed=101]="AnimationsResumed",e[e.AnimatedNodeDescriptionClicked=102]="AnimatedNodeDescriptionClicked",e[e.AnimationGroupScrubbed=103]="AnimationGroupScrubbed",e[e.AnimationGroupReplayed=104]="AnimationGroupReplayed",e[e.OverrideTabDeleteFolderContextMenu=105]="OverrideTabDeleteFolderContextMenu",e[e.WorkspaceDropFolder=107]="WorkspaceDropFolder",e[e.WorkspaceSelectFolder=108]="WorkspaceSelectFolder",e[e.OverrideContentContextMenuSourceMappedWarning=109]="OverrideContentContextMenuSourceMappedWarning",e[e.OverrideContentContextMenuRedirectToDeployed=110]="OverrideContentContextMenuRedirectToDeployed",e[e.NewStyleRuleAdded=111]="NewStyleRuleAdded",e[e.TraceExpanded=112]="TraceExpanded",e[e.InsightConsoleMessageShown=113]="InsightConsoleMessageShown",e[e.InsightRequestedViaContextMenu=114]="InsightRequestedViaContextMenu",e[e.InsightRequestedViaHoverButton=115]="InsightRequestedViaHoverButton",e[e.InsightRatedPositive=117]="InsightRatedPositive",e[e.InsightRatedNegative=118]="InsightRatedNegative",e[e.InsightClosed=119]="InsightClosed",e[e.InsightErrored=120]="InsightErrored",e[e.InsightHoverButtonShown=121]="InsightHoverButtonShown",e[e.SelfXssWarningConsoleMessageShown=122]="SelfXssWarningConsoleMessageShown",e[e.SelfXssWarningDialogShown=123]="SelfXssWarningDialogShown",e[e.SelfXssAllowPastingInConsole=124]="SelfXssAllowPastingInConsole",e[e.SelfXssAllowPastingInDialog=125]="SelfXssAllowPastingInDialog",e[e.ToggleEmulateFocusedPageFromStylesPaneOn=126]="ToggleEmulateFocusedPageFromStylesPaneOn",e[e.ToggleEmulateFocusedPageFromStylesPaneOff=127]="ToggleEmulateFocusedPageFromStylesPaneOff",e[e.ToggleEmulateFocusedPageFromRenderingTab=128]="ToggleEmulateFocusedPageFromRenderingTab",e[e.ToggleEmulateFocusedPageFromCommandMenu=129]="ToggleEmulateFocusedPageFromCommandMenu",e[e.InsightGenerated=130]="InsightGenerated",e[e.InsightErroredApi=131]="InsightErroredApi",e[e.InsightErroredMarkdown=132]="InsightErroredMarkdown",e[e.ToggleShowWebVitals=133]="ToggleShowWebVitals",e[e.InsightErroredPermissionDenied=134]="InsightErroredPermissionDenied",e[e.InsightErroredCannotSend=135]="InsightErroredCannotSend",e[e.InsightErroredRequestFailed=136]="InsightErroredRequestFailed",e[e.InsightErroredCannotParseChunk=137]="InsightErroredCannotParseChunk",e[e.InsightErroredUnknownChunk=138]="InsightErroredUnknownChunk",e[e.InsightErroredOther=139]="InsightErroredOther",e[e.AutofillReceived=140]="AutofillReceived",e[e.AutofillReceivedAndTabAutoOpened=141]="AutofillReceivedAndTabAutoOpened",e[e.AnimationGroupSelected=142]="AnimationGroupSelected",e[e.ScrollDrivenAnimationGroupSelected=143]="ScrollDrivenAnimationGroupSelected",e[e.ScrollDrivenAnimationGroupScrubbed=144]="ScrollDrivenAnimationGroupScrubbed",e[e.AiAssistanceOpenedFromElementsPanel=145]="AiAssistanceOpenedFromElementsPanel",e[e.AiAssistanceOpenedFromStylesTab=146]="AiAssistanceOpenedFromStylesTab",e[e.ConsoleFilterByContext=147]="ConsoleFilterByContext",e[e.ConsoleFilterBySource=148]="ConsoleFilterBySource",e[e.ConsoleFilterByUrl=149]="ConsoleFilterByUrl",e[e.InsightConsentReminderShown=150]="InsightConsentReminderShown",e[e.InsightConsentReminderCanceled=151]="InsightConsentReminderCanceled",e[e.InsightConsentReminderConfirmed=152]="InsightConsentReminderConfirmed",e[e.InsightsOnboardingShown=153]="InsightsOnboardingShown",e[e.InsightsOnboardingCanceledOnPage1=154]="InsightsOnboardingCanceledOnPage1",e[e.InsightsOnboardingCanceledOnPage2=155]="InsightsOnboardingCanceledOnPage2",e[e.InsightsOnboardingConfirmed=156]="InsightsOnboardingConfirmed",e[e.InsightsOnboardingNextPage=157]="InsightsOnboardingNextPage",e[e.InsightsOnboardingPrevPage=158]="InsightsOnboardingPrevPage",e[e.InsightsOnboardingFeatureDisabled=159]="InsightsOnboardingFeatureDisabled",e[e.InsightsOptInTeaserShown=160]="InsightsOptInTeaserShown",e[e.InsightsOptInTeaserSettingsLinkClicked=161]="InsightsOptInTeaserSettingsLinkClicked",e[e.InsightsOptInTeaserConfirmedInSettings=162]="InsightsOptInTeaserConfirmedInSettings",e[e.InsightsReminderTeaserShown=163]="InsightsReminderTeaserShown",e[e.InsightsReminderTeaserConfirmed=164]="InsightsReminderTeaserConfirmed",e[e.InsightsReminderTeaserCanceled=165]="InsightsReminderTeaserCanceled",e[e.InsightsReminderTeaserSettingsLinkClicked=166]="InsightsReminderTeaserSettingsLinkClicked",e[e.InsightsReminderTeaserAbortedInSettings=167]="InsightsReminderTeaserAbortedInSettings",e[e.GeneratingInsightWithoutDisclaimer=168]="GeneratingInsightWithoutDisclaimer",e[e.AiAssistanceOpenedFromElementsPanelFloatingButton=169]="AiAssistanceOpenedFromElementsPanelFloatingButton",e[e.AiAssistanceOpenedFromNetworkPanel=170]="AiAssistanceOpenedFromNetworkPanel",e[e.AiAssistanceOpenedFromSourcesPanel=171]="AiAssistanceOpenedFromSourcesPanel",e[e.AiAssistanceOpenedFromSourcesPanelFloatingButton=172]="AiAssistanceOpenedFromSourcesPanelFloatingButton",e[e.AiAssistanceOpenedFromPerformancePanel=173]="AiAssistanceOpenedFromPerformancePanel",e[e.AiAssistanceOpenedFromNetworkPanelFloatingButton=174]="AiAssistanceOpenedFromNetworkPanelFloatingButton",e[e.AiAssistancePanelOpened=175]="AiAssistancePanelOpened",e[e.AiAssistanceQuerySubmitted=176]="AiAssistanceQuerySubmitted",e[e.AiAssistanceAnswerReceived=177]="AiAssistanceAnswerReceived",e[e.AiAssistanceDynamicSuggestionClicked=178]="AiAssistanceDynamicSuggestionClicked",e[e.AiAssistanceSideEffectConfirmed=179]="AiAssistanceSideEffectConfirmed",e[e.AiAssistanceSideEffectRejected=180]="AiAssistanceSideEffectRejected",e[e.AiAssistanceError=181]="AiAssistanceError",e[e.AiAssistanceOpenedFromPerformanceInsight=182]="AiAssistanceOpenedFromPerformanceInsight",e[e.MAX_VALUE=183]="MAX_VALUE"}(J||(J={})),function(e){e[e.elements=1]="elements",e[e.resources=2]="resources",e[e.network=3]="network",e[e.sources=4]="sources",e[e.timeline=5]="timeline",e[e["heap-profiler"]=6]="heap-profiler",e[e.console=8]="console",e[e.layers=9]="layers",e[e["console-view"]=10]="console-view",e[e.animations=11]="animations",e[e["network.config"]=12]="network.config",e[e.rendering=13]="rendering",e[e.sensors=14]="sensors",e[e["sources.search"]=15]="sources.search",e[e.security=16]="security",e[e["js-profiler"]=17]="js-profiler",e[e.lighthouse=18]="lighthouse",e[e.coverage=19]="coverage",e[e["protocol-monitor"]=20]="protocol-monitor",e[e["remote-devices"]=21]="remote-devices",e[e["web-audio"]=22]="web-audio",e[e["changes.changes"]=23]="changes.changes",e[e["performance.monitor"]=24]="performance.monitor",e[e["release-note"]=25]="release-note",e[e["live-heap-profile"]=26]="live-heap-profile",e[e["sources.quick"]=27]="sources.quick",e[e["network.blocked-urls"]=28]="network.blocked-urls",e[e["settings-preferences"]=29]="settings-preferences",e[e["settings-workspace"]=30]="settings-workspace",e[e["settings-experiments"]=31]="settings-experiments",e[e["settings-blackbox"]=32]="settings-blackbox",e[e["settings-devices"]=33]="settings-devices",e[e["settings-throttling-conditions"]=34]="settings-throttling-conditions",e[e["settings-emulation-locations"]=35]="settings-emulation-locations",e[e["settings-shortcuts"]=36]="settings-shortcuts",e[e["issues-pane"]=37]="issues-pane",e[e["settings-keybinds"]=38]="settings-keybinds",e[e.cssoverview=39]="cssoverview",e[e["chrome-recorder"]=40]="chrome-recorder",e[e["trust-tokens"]=41]="trust-tokens",e[e["reporting-api"]=42]="reporting-api",e[e["interest-groups"]=43]="interest-groups",e[e["back-forward-cache"]=44]="back-forward-cache",e[e["service-worker-cache"]=45]="service-worker-cache",e[e["background-service-background-fetch"]=46]="background-service-background-fetch",e[e["background-service-background-sync"]=47]="background-service-background-sync",e[e["background-service-push-messaging"]=48]="background-service-push-messaging",e[e["background-service-notifications"]=49]="background-service-notifications",e[e["background-service-payment-handler"]=50]="background-service-payment-handler",e[e["background-service-periodic-background-sync"]=51]="background-service-periodic-background-sync",e[e["service-workers"]=52]="service-workers",e[e["app-manifest"]=53]="app-manifest",e[e.storage=54]="storage",e[e.cookies=55]="cookies",e[e["frame-details"]=56]="frame-details",e[e["frame-resource"]=57]="frame-resource",e[e["frame-window"]=58]="frame-window",e[e["frame-worker"]=59]="frame-worker",e[e["dom-storage"]=60]="dom-storage",e[e["indexed-db"]=61]="indexed-db",e[e["web-sql"]=62]="web-sql",e[e["performance-insights"]=63]="performance-insights",e[e.preloading=64]="preloading",e[e["bounce-tracking-mitigations"]=65]="bounce-tracking-mitigations",e[e["developer-resources"]=66]="developer-resources",e[e["autofill-view"]=67]="autofill-view",e[e.MAX_VALUE=68]="MAX_VALUE"}(Z||(Z={})),function(e){e[e["elements-main"]=1]="elements-main",e[e["elements-drawer"]=2]="elements-drawer",e[e["resources-main"]=3]="resources-main",e[e["resources-drawer"]=4]="resources-drawer",e[e["network-main"]=5]="network-main",e[e["network-drawer"]=6]="network-drawer",e[e["sources-main"]=7]="sources-main",e[e["sources-drawer"]=8]="sources-drawer",e[e["timeline-main"]=9]="timeline-main",e[e["timeline-drawer"]=10]="timeline-drawer",e[e["heap_profiler-main"]=11]="heap_profiler-main",e[e["heap_profiler-drawer"]=12]="heap_profiler-drawer",e[e["console-main"]=13]="console-main",e[e["console-drawer"]=14]="console-drawer",e[e["layers-main"]=15]="layers-main",e[e["layers-drawer"]=16]="layers-drawer",e[e["console-view-main"]=17]="console-view-main",e[e["console-view-drawer"]=18]="console-view-drawer",e[e["animations-main"]=19]="animations-main",e[e["animations-drawer"]=20]="animations-drawer",e[e["network.config-main"]=21]="network.config-main",e[e["network.config-drawer"]=22]="network.config-drawer",e[e["rendering-main"]=23]="rendering-main",e[e["rendering-drawer"]=24]="rendering-drawer",e[e["sensors-main"]=25]="sensors-main",e[e["sensors-drawer"]=26]="sensors-drawer",e[e["sources.search-main"]=27]="sources.search-main",e[e["sources.search-drawer"]=28]="sources.search-drawer",e[e["security-main"]=29]="security-main",e[e["security-drawer"]=30]="security-drawer",e[e["lighthouse-main"]=33]="lighthouse-main",e[e["lighthouse-drawer"]=34]="lighthouse-drawer",e[e["coverage-main"]=35]="coverage-main",e[e["coverage-drawer"]=36]="coverage-drawer",e[e["protocol-monitor-main"]=37]="protocol-monitor-main",e[e["protocol-monitor-drawer"]=38]="protocol-monitor-drawer",e[e["remote-devices-main"]=39]="remote-devices-main",e[e["remote-devices-drawer"]=40]="remote-devices-drawer",e[e["web-audio-main"]=41]="web-audio-main",e[e["web-audio-drawer"]=42]="web-audio-drawer",e[e["changes.changes-main"]=43]="changes.changes-main",e[e["changes.changes-drawer"]=44]="changes.changes-drawer",e[e["performance.monitor-main"]=45]="performance.monitor-main",e[e["performance.monitor-drawer"]=46]="performance.monitor-drawer",e[e["release-note-main"]=47]="release-note-main",e[e["release-note-drawer"]=48]="release-note-drawer",e[e["live_heap_profile-main"]=49]="live_heap_profile-main",e[e["live_heap_profile-drawer"]=50]="live_heap_profile-drawer",e[e["sources.quick-main"]=51]="sources.quick-main",e[e["sources.quick-drawer"]=52]="sources.quick-drawer",e[e["network.blocked-urls-main"]=53]="network.blocked-urls-main",e[e["network.blocked-urls-drawer"]=54]="network.blocked-urls-drawer",e[e["settings-preferences-main"]=55]="settings-preferences-main",e[e["settings-preferences-drawer"]=56]="settings-preferences-drawer",e[e["settings-workspace-main"]=57]="settings-workspace-main",e[e["settings-workspace-drawer"]=58]="settings-workspace-drawer",e[e["settings-experiments-main"]=59]="settings-experiments-main",e[e["settings-experiments-drawer"]=60]="settings-experiments-drawer",e[e["settings-blackbox-main"]=61]="settings-blackbox-main",e[e["settings-blackbox-drawer"]=62]="settings-blackbox-drawer",e[e["settings-devices-main"]=63]="settings-devices-main",e[e["settings-devices-drawer"]=64]="settings-devices-drawer",e[e["settings-throttling-conditions-main"]=65]="settings-throttling-conditions-main",e[e["settings-throttling-conditions-drawer"]=66]="settings-throttling-conditions-drawer",e[e["settings-emulation-locations-main"]=67]="settings-emulation-locations-main",e[e["settings-emulation-locations-drawer"]=68]="settings-emulation-locations-drawer",e[e["settings-shortcuts-main"]=69]="settings-shortcuts-main",e[e["settings-shortcuts-drawer"]=70]="settings-shortcuts-drawer",e[e["issues-pane-main"]=71]="issues-pane-main",e[e["issues-pane-drawer"]=72]="issues-pane-drawer",e[e["settings-keybinds-main"]=73]="settings-keybinds-main",e[e["settings-keybinds-drawer"]=74]="settings-keybinds-drawer",e[e["cssoverview-main"]=75]="cssoverview-main",e[e["cssoverview-drawer"]=76]="cssoverview-drawer",e[e["chrome_recorder-main"]=77]="chrome_recorder-main",e[e["chrome_recorder-drawer"]=78]="chrome_recorder-drawer",e[e["trust_tokens-main"]=79]="trust_tokens-main",e[e["trust_tokens-drawer"]=80]="trust_tokens-drawer",e[e["reporting_api-main"]=81]="reporting_api-main",e[e["reporting_api-drawer"]=82]="reporting_api-drawer",e[e["interest_groups-main"]=83]="interest_groups-main",e[e["interest_groups-drawer"]=84]="interest_groups-drawer",e[e["back_forward_cache-main"]=85]="back_forward_cache-main",e[e["back_forward_cache-drawer"]=86]="back_forward_cache-drawer",e[e["service_worker_cache-main"]=87]="service_worker_cache-main",e[e["service_worker_cache-drawer"]=88]="service_worker_cache-drawer",e[e["background_service_backgroundFetch-main"]=89]="background_service_backgroundFetch-main",e[e["background_service_backgroundFetch-drawer"]=90]="background_service_backgroundFetch-drawer",e[e["background_service_backgroundSync-main"]=91]="background_service_backgroundSync-main",e[e["background_service_backgroundSync-drawer"]=92]="background_service_backgroundSync-drawer",e[e["background_service_pushMessaging-main"]=93]="background_service_pushMessaging-main",e[e["background_service_pushMessaging-drawer"]=94]="background_service_pushMessaging-drawer",e[e["background_service_notifications-main"]=95]="background_service_notifications-main",e[e["background_service_notifications-drawer"]=96]="background_service_notifications-drawer",e[e["background_service_paymentHandler-main"]=97]="background_service_paymentHandler-main",e[e["background_service_paymentHandler-drawer"]=98]="background_service_paymentHandler-drawer",e[e["background_service_periodicBackgroundSync-main"]=99]="background_service_periodicBackgroundSync-main",e[e["background_service_periodicBackgroundSync-drawer"]=100]="background_service_periodicBackgroundSync-drawer",e[e["service_workers-main"]=101]="service_workers-main",e[e["service_workers-drawer"]=102]="service_workers-drawer",e[e["app_manifest-main"]=103]="app_manifest-main",e[e["app_manifest-drawer"]=104]="app_manifest-drawer",e[e["storage-main"]=105]="storage-main",e[e["storage-drawer"]=106]="storage-drawer",e[e["cookies-main"]=107]="cookies-main",e[e["cookies-drawer"]=108]="cookies-drawer",e[e["frame_details-main"]=109]="frame_details-main",e[e["frame_details-drawer"]=110]="frame_details-drawer",e[e["frame_resource-main"]=111]="frame_resource-main",e[e["frame_resource-drawer"]=112]="frame_resource-drawer",e[e["frame_window-main"]=113]="frame_window-main",e[e["frame_window-drawer"]=114]="frame_window-drawer",e[e["frame_worker-main"]=115]="frame_worker-main",e[e["frame_worker-drawer"]=116]="frame_worker-drawer",e[e["dom_storage-main"]=117]="dom_storage-main",e[e["dom_storage-drawer"]=118]="dom_storage-drawer",e[e["indexed_db-main"]=119]="indexed_db-main",e[e["indexed_db-drawer"]=120]="indexed_db-drawer",e[e["web_sql-main"]=121]="web_sql-main",e[e["web_sql-drawer"]=122]="web_sql-drawer",e[e["performance_insights-main"]=123]="performance_insights-main",e[e["performance_insights-drawer"]=124]="performance_insights-drawer",e[e["preloading-main"]=125]="preloading-main",e[e["preloading-drawer"]=126]="preloading-drawer",e[e["bounce_tracking_mitigations-main"]=127]="bounce_tracking_mitigations-main",e[e["bounce_tracking_mitigations-drawer"]=128]="bounce_tracking_mitigations-drawer",e[e["developer-resources-main"]=129]="developer-resources-main",e[e["developer-resources-drawer"]=130]="developer-resources-drawer",e[e["autofill-view-main"]=131]="autofill-view-main",e[e["autofill-view-drawer"]=132]="autofill-view-drawer",e[e.MAX_VALUE=133]="MAX_VALUE"}(ee||(ee={})),function(e){e[e.OtherSidebarPane=0]="OtherSidebarPane",e[e.styles=1]="styles",e[e.computed=2]="computed",e[e["elements.layout"]=3]="elements.layout",e[e["elements.event-listeners"]=4]="elements.event-listeners",e[e["elements.dom-breakpoints"]=5]="elements.dom-breakpoints",e[e["elements.dom-properties"]=6]="elements.dom-properties",e[e["accessibility.view"]=7]="accessibility.view",e[e.MAX_VALUE=8]="MAX_VALUE"}(re||(re={})),function(e){e[e.Unknown=0]="Unknown",e[e["text/css"]=2]="text/css",e[e["text/html"]=3]="text/html",e[e["application/xml"]=4]="application/xml",e[e["application/wasm"]=5]="application/wasm",e[e["application/manifest+json"]=6]="application/manifest+json",e[e["application/x-aspx"]=7]="application/x-aspx",e[e["application/jsp"]=8]="application/jsp",e[e["text/x-c++src"]=9]="text/x-c++src",e[e["text/x-coffeescript"]=10]="text/x-coffeescript",e[e["application/vnd.dart"]=11]="application/vnd.dart",e[e["text/typescript"]=12]="text/typescript",e[e["text/typescript-jsx"]=13]="text/typescript-jsx",e[e["application/json"]=14]="application/json",e[e["text/x-csharp"]=15]="text/x-csharp",e[e["text/x-java"]=16]="text/x-java",e[e["text/x-less"]=17]="text/x-less",e[e["application/x-httpd-php"]=18]="application/x-httpd-php",e[e["text/x-python"]=19]="text/x-python",e[e["text/x-sh"]=20]="text/x-sh",e[e["text/x-gss"]=21]="text/x-gss",e[e["text/x-sass"]=22]="text/x-sass",e[e["text/x-scss"]=23]="text/x-scss",e[e["text/markdown"]=24]="text/markdown",e[e["text/x-clojure"]=25]="text/x-clojure",e[e["text/jsx"]=26]="text/jsx",e[e["text/x-go"]=27]="text/x-go",e[e["text/x-kotlin"]=28]="text/x-kotlin",e[e["text/x-scala"]=29]="text/x-scala",e[e["text/x.svelte"]=30]="text/x.svelte",e[e["text/javascript+plain"]=31]="text/javascript+plain",e[e["text/javascript+minified"]=32]="text/javascript+minified",e[e["text/javascript+sourcemapped"]=33]="text/javascript+sourcemapped",e[e["text/x.angular"]=34]="text/x.angular",e[e["text/x.vue"]=35]="text/x.vue",e[e["text/javascript+snippet"]=36]="text/javascript+snippet",e[e["text/javascript+eval"]=37]="text/javascript+eval",e[e.MAX_VALUE=38]="MAX_VALUE"}(te||(te={})),function(e){e[e.devToolsDefault=0]="devToolsDefault",e[e.vsCode=1]="vsCode",e[e.MAX_VALUE=2]="MAX_VALUE"}(ne||(ne={})),function(e){e[e.OtherShortcut=0]="OtherShortcut",e[e["quick-open.show-command-menu"]=1]="quick-open.show-command-menu",e[e["console.clear"]=2]="console.clear",e[e["console.toggle"]=3]="console.toggle",e[e["debugger.step"]=4]="debugger.step",e[e["debugger.step-into"]=5]="debugger.step-into",e[e["debugger.step-out"]=6]="debugger.step-out",e[e["debugger.step-over"]=7]="debugger.step-over",e[e["debugger.toggle-breakpoint"]=8]="debugger.toggle-breakpoint",e[e["debugger.toggle-breakpoint-enabled"]=9]="debugger.toggle-breakpoint-enabled",e[e["debugger.toggle-pause"]=10]="debugger.toggle-pause",e[e["elements.edit-as-html"]=11]="elements.edit-as-html",e[e["elements.hide-element"]=12]="elements.hide-element",e[e["elements.redo"]=13]="elements.redo",e[e["elements.toggle-element-search"]=14]="elements.toggle-element-search",e[e["elements.undo"]=15]="elements.undo",e[e["main.search-in-panel.find"]=16]="main.search-in-panel.find",e[e["main.toggle-drawer"]=17]="main.toggle-drawer",e[e["network.hide-request-details"]=18]="network.hide-request-details",e[e["network.search"]=19]="network.search",e[e["network.toggle-recording"]=20]="network.toggle-recording",e[e["quick-open.show"]=21]="quick-open.show",e[e["settings.show"]=22]="settings.show",e[e["sources.search"]=23]="sources.search",e[e["background-service.toggle-recording"]=24]="background-service.toggle-recording",e[e["components.collect-garbage"]=25]="components.collect-garbage",e[e["console.clear.history"]=26]="console.clear.history",e[e["console.create-pin"]=27]="console.create-pin",e[e["coverage.start-with-reload"]=28]="coverage.start-with-reload",e[e["coverage.toggle-recording"]=29]="coverage.toggle-recording",e[e["debugger.breakpoint-input-window"]=30]="debugger.breakpoint-input-window",e[e["debugger.evaluate-selection"]=31]="debugger.evaluate-selection",e[e["debugger.next-call-frame"]=32]="debugger.next-call-frame",e[e["debugger.previous-call-frame"]=33]="debugger.previous-call-frame",e[e["debugger.run-snippet"]=34]="debugger.run-snippet",e[e["debugger.toggle-breakpoints-active"]=35]="debugger.toggle-breakpoints-active",e[e["elements.capture-area-screenshot"]=36]="elements.capture-area-screenshot",e[e["emulation.capture-full-height-screenshot"]=37]="emulation.capture-full-height-screenshot",e[e["emulation.capture-node-screenshot"]=38]="emulation.capture-node-screenshot",e[e["emulation.capture-screenshot"]=39]="emulation.capture-screenshot",e[e["emulation.show-sensors"]=40]="emulation.show-sensors",e[e["emulation.toggle-device-mode"]=41]="emulation.toggle-device-mode",e[e["help.release-notes"]=42]="help.release-notes",e[e["help.report-issue"]=43]="help.report-issue",e[e["input.start-replaying"]=44]="input.start-replaying",e[e["input.toggle-pause"]=45]="input.toggle-pause",e[e["input.toggle-recording"]=46]="input.toggle-recording",e[e["inspector-main.focus-debuggee"]=47]="inspector-main.focus-debuggee",e[e["inspector-main.hard-reload"]=48]="inspector-main.hard-reload",e[e["inspector-main.reload"]=49]="inspector-main.reload",e[e["live-heap-profile.start-with-reload"]=50]="live-heap-profile.start-with-reload",e[e["live-heap-profile.toggle-recording"]=51]="live-heap-profile.toggle-recording",e[e["main.debug-reload"]=52]="main.debug-reload",e[e["main.next-tab"]=53]="main.next-tab",e[e["main.previous-tab"]=54]="main.previous-tab",e[e["main.search-in-panel.cancel"]=55]="main.search-in-panel.cancel",e[e["main.search-in-panel.find-next"]=56]="main.search-in-panel.find-next",e[e["main.search-in-panel.find-previous"]=57]="main.search-in-panel.find-previous",e[e["main.toggle-dock"]=58]="main.toggle-dock",e[e["main.zoom-in"]=59]="main.zoom-in",e[e["main.zoom-out"]=60]="main.zoom-out",e[e["main.zoom-reset"]=61]="main.zoom-reset",e[e["network-conditions.network-low-end-mobile"]=62]="network-conditions.network-low-end-mobile",e[e["network-conditions.network-mid-tier-mobile"]=63]="network-conditions.network-mid-tier-mobile",e[e["network-conditions.network-offline"]=64]="network-conditions.network-offline",e[e["network-conditions.network-online"]=65]="network-conditions.network-online",e[e["profiler.heap-toggle-recording"]=66]="profiler.heap-toggle-recording",e[e["profiler.js-toggle-recording"]=67]="profiler.js-toggle-recording",e[e["resources.clear"]=68]="resources.clear",e[e["settings.documentation"]=69]="settings.documentation",e[e["settings.shortcuts"]=70]="settings.shortcuts",e[e["sources.add-folder-to-workspace"]=71]="sources.add-folder-to-workspace",e[e["sources.add-to-watch"]=72]="sources.add-to-watch",e[e["sources.close-all"]=73]="sources.close-all",e[e["sources.close-editor-tab"]=74]="sources.close-editor-tab",e[e["sources.create-snippet"]=75]="sources.create-snippet",e[e["sources.go-to-line"]=76]="sources.go-to-line",e[e["sources.go-to-member"]=77]="sources.go-to-member",e[e["sources.jump-to-next-location"]=78]="sources.jump-to-next-location",e[e["sources.jump-to-previous-location"]=79]="sources.jump-to-previous-location",e[e["sources.rename"]=80]="sources.rename",e[e["sources.save"]=81]="sources.save",e[e["sources.save-all"]=82]="sources.save-all",e[e["sources.switch-file"]=83]="sources.switch-file",e[e["timeline.jump-to-next-frame"]=84]="timeline.jump-to-next-frame",e[e["timeline.jump-to-previous-frame"]=85]="timeline.jump-to-previous-frame",e[e["timeline.load-from-file"]=86]="timeline.load-from-file",e[e["timeline.next-recording"]=87]="timeline.next-recording",e[e["timeline.previous-recording"]=88]="timeline.previous-recording",e[e["timeline.record-reload"]=89]="timeline.record-reload",e[e["timeline.save-to-file"]=90]="timeline.save-to-file",e[e["timeline.show-history"]=91]="timeline.show-history",e[e["timeline.toggle-recording"]=92]="timeline.toggle-recording",e[e["sources.increment-css"]=93]="sources.increment-css",e[e["sources.increment-css-by-ten"]=94]="sources.increment-css-by-ten",e[e["sources.decrement-css"]=95]="sources.decrement-css",e[e["sources.decrement-css-by-ten"]=96]="sources.decrement-css-by-ten",e[e["layers.reset-view"]=97]="layers.reset-view",e[e["layers.pan-mode"]=98]="layers.pan-mode",e[e["layers.rotate-mode"]=99]="layers.rotate-mode",e[e["layers.zoom-in"]=100]="layers.zoom-in",e[e["layers.zoom-out"]=101]="layers.zoom-out",e[e["layers.up"]=102]="layers.up",e[e["layers.down"]=103]="layers.down",e[e["layers.left"]=104]="layers.left",e[e["layers.right"]=105]="layers.right",e[e["help.report-translation-issue"]=106]="help.report-translation-issue",e[e["rendering.toggle-prefers-color-scheme"]=107]="rendering.toggle-prefers-color-scheme",e[e["chrome-recorder.start-recording"]=108]="chrome-recorder.start-recording",e[e["chrome-recorder.replay-recording"]=109]="chrome-recorder.replay-recording",e[e["chrome-recorder.toggle-code-view"]=110]="chrome-recorder.toggle-code-view",e[e["chrome-recorder.copy-recording-or-step"]=111]="chrome-recorder.copy-recording-or-step",e[e["changes.revert"]=112]="changes.revert",e[e["changes.copy"]=113]="changes.copy",e[e["elements.new-style-rule"]=114]="elements.new-style-rule",e[e["elements.refresh-event-listeners"]=115]="elements.refresh-event-listeners",e[e["coverage.clear"]=116]="coverage.clear",e[e["coverage.export"]=117]="coverage.export",e[e["timeline.dim-third-parties"]=118]="timeline.dim-third-parties",e[e.MAX_VALUE=119]="MAX_VALUE"}(oe||(oe={})),function(e){e[e["capture-node-creation-stacks"]=1]="capture-node-creation-stacks",e[e["live-heap-profile"]=11]="live-heap-profile",e[e["protocol-monitor"]=13]="protocol-monitor",e[e["sampling-heap-profiler-timeline"]=17]="sampling-heap-profiler-timeline",e[e["show-option-tp-expose-internals-in-heap-snapshot"]=18]="show-option-tp-expose-internals-in-heap-snapshot",e[e["timeline-invalidation-tracking"]=26]="timeline-invalidation-tracking",e[e["timeline-show-all-events"]=27]="timeline-show-all-events",e[e["timeline-v8-runtime-call-stats"]=28]="timeline-v8-runtime-call-stats",e[e.apca=39]="apca",e[e["font-editor"]=41]="font-editor",e[e["full-accessibility-tree"]=42]="full-accessibility-tree",e[e["contrast-issues"]=44]="contrast-issues",e[e["experimental-cookie-features"]=45]="experimental-cookie-features",e[e["instrumentation-breakpoints"]=61]="instrumentation-breakpoints",e[e["authored-deployed-grouping"]=63]="authored-deployed-grouping",e[e["just-my-code"]=65]="just-my-code",e[e["highlight-errors-elements-panel"]=73]="highlight-errors-elements-panel",e[e["use-source-map-scopes"]=76]="use-source-map-scopes",e[e["network-panel-filter-bar-redesign"]=79]="network-panel-filter-bar-redesign",e[e["timeline-show-postmessage-events"]=86]="timeline-show-postmessage-events",e[e["timeline-enhanced-traces"]=90]="timeline-enhanced-traces",e[e["timeline-compiled-sources"]=91]="timeline-compiled-sources",e[e["timeline-debug-mode"]=93]="timeline-debug-mode",e[e["timeline-experimental-insights"]=102]="timeline-experimental-insights",e[e["timeline-dim-unrelated-events"]=103]="timeline-dim-unrelated-events",e[e["timeline-alternative-navigation"]=104]="timeline-alternative-navigation",e[e.MAX_VALUE=106]="MAX_VALUE"}(se||(se={})),function(e){e[e.CrossOriginEmbedderPolicy=0]="CrossOriginEmbedderPolicy",e[e.MixedContent=1]="MixedContent",e[e.SameSiteCookie=2]="SameSiteCookie",e[e.HeavyAd=3]="HeavyAd",e[e.ContentSecurityPolicy=4]="ContentSecurityPolicy",e[e.Other=5]="Other",e[e.Generic=6]="Generic",e[e.ThirdPartyPhaseoutCookie=7]="ThirdPartyPhaseoutCookie",e[e.GenericCookie=8]="GenericCookie",e[e.MAX_VALUE=9]="MAX_VALUE"}(ie||(ie={})),function(e){e[e.CrossOriginEmbedderPolicyRequest=0]="CrossOriginEmbedderPolicyRequest",e[e.CrossOriginEmbedderPolicyElement=1]="CrossOriginEmbedderPolicyElement",e[e.MixedContentRequest=2]="MixedContentRequest",e[e.SameSiteCookieCookie=3]="SameSiteCookieCookie",e[e.SameSiteCookieRequest=4]="SameSiteCookieRequest",e[e.HeavyAdElement=5]="HeavyAdElement",e[e.ContentSecurityPolicyDirective=6]="ContentSecurityPolicyDirective",e[e.ContentSecurityPolicyElement=7]="ContentSecurityPolicyElement",e[e.MAX_VALUE=13]="MAX_VALUE"}(ae||(ae={})),function(e){e[e.MixedContentIssue=0]="MixedContentIssue",e[e["ContentSecurityPolicyIssue::kInlineViolation"]=1]="ContentSecurityPolicyIssue::kInlineViolation",e[e["ContentSecurityPolicyIssue::kEvalViolation"]=2]="ContentSecurityPolicyIssue::kEvalViolation",e[e["ContentSecurityPolicyIssue::kURLViolation"]=3]="ContentSecurityPolicyIssue::kURLViolation",e[e["ContentSecurityPolicyIssue::kTrustedTypesSinkViolation"]=4]="ContentSecurityPolicyIssue::kTrustedTypesSinkViolation",e[e["ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation"]=5]="ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation",e[e["HeavyAdIssue::NetworkTotalLimit"]=6]="HeavyAdIssue::NetworkTotalLimit",e[e["HeavyAdIssue::CpuTotalLimit"]=7]="HeavyAdIssue::CpuTotalLimit",e[e["HeavyAdIssue::CpuPeakLimit"]=8]="HeavyAdIssue::CpuPeakLimit",e[e["CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader"]=9]="CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader",e[e["CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage"]=10]="CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin"]=11]="CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep"]=12]="CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep",e[e["CrossOriginEmbedderPolicyIssue::CorpNotSameSite"]=13]="CrossOriginEmbedderPolicyIssue::CorpNotSameSite",e[e["CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie"]=14]="CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie",e[e["CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie"]=15]="CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie",e[e["CookieIssue::WarnSameSiteNoneInsecure::ReadCookie"]=16]="CookieIssue::WarnSameSiteNoneInsecure::ReadCookie",e[e["CookieIssue::WarnSameSiteNoneInsecure::SetCookie"]=17]="CookieIssue::WarnSameSiteNoneInsecure::SetCookie",e[e["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure"]=18]="CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure",e[e["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure"]=19]="CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure",e[e["CookieIssue::WarnCrossDowngrade::ReadCookie::Secure"]=20]="CookieIssue::WarnCrossDowngrade::ReadCookie::Secure",e[e["CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure"]=21]="CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure",e[e["CookieIssue::WarnCrossDowngrade::SetCookie::Secure"]=22]="CookieIssue::WarnCrossDowngrade::SetCookie::Secure",e[e["CookieIssue::WarnCrossDowngrade::SetCookie::Insecure"]=23]="CookieIssue::WarnCrossDowngrade::SetCookie::Insecure",e[e["CookieIssue::ExcludeNavigationContextDowngrade::Secure"]=24]="CookieIssue::ExcludeNavigationContextDowngrade::Secure",e[e["CookieIssue::ExcludeNavigationContextDowngrade::Insecure"]=25]="CookieIssue::ExcludeNavigationContextDowngrade::Insecure",e[e["CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure"]=26]="CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure",e[e["CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure"]=27]="CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure",e[e["CookieIssue::ExcludeContextDowngrade::SetCookie::Secure"]=28]="CookieIssue::ExcludeContextDowngrade::SetCookie::Secure",e[e["CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure"]=29]="CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure",e[e["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie"]=30]="CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie",e[e["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie"]=31]="CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie"]=32]="CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie"]=33]="CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie"]=34]="CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie",e[e["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie"]=35]="CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie",e[e["SharedArrayBufferIssue::TransferIssue"]=36]="SharedArrayBufferIssue::TransferIssue",e[e["SharedArrayBufferIssue::CreationIssue"]=37]="SharedArrayBufferIssue::CreationIssue",e[e.LowTextContrastIssue=41]="LowTextContrastIssue",e[e["CorsIssue::InsecurePrivateNetwork"]=42]="CorsIssue::InsecurePrivateNetwork",e[e["CorsIssue::InvalidHeaders"]=44]="CorsIssue::InvalidHeaders",e[e["CorsIssue::WildcardOriginWithCredentials"]=45]="CorsIssue::WildcardOriginWithCredentials",e[e["CorsIssue::PreflightResponseInvalid"]=46]="CorsIssue::PreflightResponseInvalid",e[e["CorsIssue::OriginMismatch"]=47]="CorsIssue::OriginMismatch",e[e["CorsIssue::AllowCredentialsRequired"]=48]="CorsIssue::AllowCredentialsRequired",e[e["CorsIssue::MethodDisallowedByPreflightResponse"]=49]="CorsIssue::MethodDisallowedByPreflightResponse",e[e["CorsIssue::HeaderDisallowedByPreflightResponse"]=50]="CorsIssue::HeaderDisallowedByPreflightResponse",e[e["CorsIssue::RedirectContainsCredentials"]=51]="CorsIssue::RedirectContainsCredentials",e[e["CorsIssue::DisallowedByMode"]=52]="CorsIssue::DisallowedByMode",e[e["CorsIssue::CorsDisabledScheme"]=53]="CorsIssue::CorsDisabledScheme",e[e["CorsIssue::PreflightMissingAllowExternal"]=54]="CorsIssue::PreflightMissingAllowExternal",e[e["CorsIssue::PreflightInvalidAllowExternal"]=55]="CorsIssue::PreflightInvalidAllowExternal",e[e["CorsIssue::NoCorsRedirectModeNotFollow"]=57]="CorsIssue::NoCorsRedirectModeNotFollow",e[e["QuirksModeIssue::QuirksMode"]=58]="QuirksModeIssue::QuirksMode",e[e["QuirksModeIssue::LimitedQuirksMode"]=59]="QuirksModeIssue::LimitedQuirksMode",e[e.DeprecationIssue=60]="DeprecationIssue",e[e["ClientHintIssue::MetaTagAllowListInvalidOrigin"]=61]="ClientHintIssue::MetaTagAllowListInvalidOrigin",e[e["ClientHintIssue::MetaTagModifiedHTML"]=62]="ClientHintIssue::MetaTagModifiedHTML",e[e["CorsIssue::PreflightAllowPrivateNetworkError"]=63]="CorsIssue::PreflightAllowPrivateNetworkError",e[e["GenericIssue::CrossOriginPortalPostMessageError"]=64]="GenericIssue::CrossOriginPortalPostMessageError",e[e["GenericIssue::FormLabelForNameError"]=65]="GenericIssue::FormLabelForNameError",e[e["GenericIssue::FormDuplicateIdForInputError"]=66]="GenericIssue::FormDuplicateIdForInputError",e[e["GenericIssue::FormInputWithNoLabelError"]=67]="GenericIssue::FormInputWithNoLabelError",e[e["GenericIssue::FormAutocompleteAttributeEmptyError"]=68]="GenericIssue::FormAutocompleteAttributeEmptyError",e[e["GenericIssue::FormEmptyIdAndNameAttributesForInputError"]=69]="GenericIssue::FormEmptyIdAndNameAttributesForInputError",e[e["GenericIssue::FormAriaLabelledByToNonExistingId"]=70]="GenericIssue::FormAriaLabelledByToNonExistingId",e[e["GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError"]=71]="GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError",e[e["GenericIssue::FormLabelHasNeitherForNorNestedInput"]=72]="GenericIssue::FormLabelHasNeitherForNorNestedInput",e[e["GenericIssue::FormLabelForMatchesNonExistingIdError"]=73]="GenericIssue::FormLabelForMatchesNonExistingIdError",e[e["GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError"]=74]="GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError",e[e["GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError"]=75]="GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError",e[e["StylesheetLoadingIssue::LateImportRule"]=76]="StylesheetLoadingIssue::LateImportRule",e[e["StylesheetLoadingIssue::RequestFailed"]=77]="StylesheetLoadingIssue::RequestFailed",e[e["CorsIssue::PreflightMissingPrivateNetworkAccessId"]=78]="CorsIssue::PreflightMissingPrivateNetworkAccessId",e[e["CorsIssue::PreflightMissingPrivateNetworkAccessName"]=79]="CorsIssue::PreflightMissingPrivateNetworkAccessName",e[e["CorsIssue::PrivateNetworkAccessPermissionUnavailable"]=80]="CorsIssue::PrivateNetworkAccessPermissionUnavailable",e[e["CorsIssue::PrivateNetworkAccessPermissionDenied"]=81]="CorsIssue::PrivateNetworkAccessPermissionDenied",e[e["CookieIssue::WarnThirdPartyPhaseout::ReadCookie"]=82]="CookieIssue::WarnThirdPartyPhaseout::ReadCookie",e[e["CookieIssue::WarnThirdPartyPhaseout::SetCookie"]=83]="CookieIssue::WarnThirdPartyPhaseout::SetCookie",e[e["CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie"]=84]="CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie",e[e["CookieIssue::ExcludeThirdPartyPhaseout::SetCookie"]=85]="CookieIssue::ExcludeThirdPartyPhaseout::SetCookie",e[e["SelectElementAccessibilityIssue::DisallowedSelectChild"]=86]="SelectElementAccessibilityIssue::DisallowedSelectChild",e[e["SelectElementAccessibilityIssue::DisallowedOptGroupChild"]=87]="SelectElementAccessibilityIssue::DisallowedOptGroupChild",e[e["SelectElementAccessibilityIssue::NonPhrasingContentOptionChild"]=88]="SelectElementAccessibilityIssue::NonPhrasingContentOptionChild",e[e["SelectElementAccessibilityIssue::InteractiveContentOptionChild"]=89]="SelectElementAccessibilityIssue::InteractiveContentOptionChild",e[e["SelectElementAccessibilityIssue::InteractiveContentLegendChild"]=90]="SelectElementAccessibilityIssue::InteractiveContentLegendChild",e[e["SRIMessageSignatureIssue::MissingSignatureHeader"]=91]="SRIMessageSignatureIssue::MissingSignatureHeader",e[e["SRIMessageSignatureIssue::MissingSignatureInputHeader"]=92]="SRIMessageSignatureIssue::MissingSignatureInputHeader",e[e["SRIMessageSignatureIssue::InvalidSignatureHeader"]=93]="SRIMessageSignatureIssue::InvalidSignatureHeader",e[e["SRIMessageSignatureIssue::InvalidSignatureInputHeader"]=94]="SRIMessageSignatureIssue::InvalidSignatureInputHeader",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence"]=95]="SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized"]=96]="SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized",e[e["SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength"]=97]="SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength",e[e["SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel"]=98]="SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel",e[e["SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList"]=99]="SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList",e[e["SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents"]=100]="SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType"]=101]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName"]=102]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter"]=103]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter"]=104]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength"]=105]="SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength",e[e["SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter"]=106]="SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter",e[e["SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters"]=107]="SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters",e[e["SRIMessageSignatureIssue::ValidationFailedSignatureExpired"]=108]="SRIMessageSignatureIssue::ValidationFailedSignatureExpired",e[e["SRIMessageSignatureIssue::ValidationFailedInvalidLength"]=109]="SRIMessageSignatureIssue::ValidationFailedInvalidLength",e[e["SRIMessageSignatureIssue::ValidationFailedSignatureMismatch"]=110]="SRIMessageSignatureIssue::ValidationFailedSignatureMismatch",e[e["CorsIssue::LocalNetworkAccessPermissionDenied"]=111]="CorsIssue::LocalNetworkAccessPermissionDenied",e[e["SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch"]=112]="SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch",e[e.MAX_VALUE=113]="MAX_VALUE"}(de||(de={})),function(e){e[e.af=1]="af",e[e.am=2]="am",e[e.ar=3]="ar",e[e.as=4]="as",e[e.az=5]="az",e[e.be=6]="be",e[e.bg=7]="bg",e[e.bn=8]="bn",e[e.bs=9]="bs",e[e.ca=10]="ca",e[e.cs=11]="cs",e[e.cy=12]="cy",e[e.da=13]="da",e[e.de=14]="de",e[e.el=15]="el",e[e["en-GB"]=16]="en-GB",e[e["en-US"]=17]="en-US",e[e["es-419"]=18]="es-419",e[e.es=19]="es",e[e.et=20]="et",e[e.eu=21]="eu",e[e.fa=22]="fa",e[e.fi=23]="fi",e[e.fil=24]="fil",e[e["fr-CA"]=25]="fr-CA",e[e.fr=26]="fr",e[e.gl=27]="gl",e[e.gu=28]="gu",e[e.he=29]="he",e[e.hi=30]="hi",e[e.hr=31]="hr",e[e.hu=32]="hu",e[e.hy=33]="hy",e[e.id=34]="id",e[e.is=35]="is",e[e.it=36]="it",e[e.ja=37]="ja",e[e.ka=38]="ka",e[e.kk=39]="kk",e[e.km=40]="km",e[e.kn=41]="kn",e[e.ko=42]="ko",e[e.ky=43]="ky",e[e.lo=44]="lo",e[e.lt=45]="lt",e[e.lv=46]="lv",e[e.mk=47]="mk",e[e.ml=48]="ml",e[e.mn=49]="mn",e[e.mr=50]="mr",e[e.ms=51]="ms",e[e.my=52]="my",e[e.ne=53]="ne",e[e.nl=54]="nl",e[e.no=55]="no",e[e.or=56]="or",e[e.pa=57]="pa",e[e.pl=58]="pl",e[e["pt-PT"]=59]="pt-PT",e[e.pt=60]="pt",e[e.ro=61]="ro",e[e.ru=62]="ru",e[e.si=63]="si",e[e.sk=64]="sk",e[e.sl=65]="sl",e[e.sq=66]="sq",e[e["sr-Latn"]=67]="sr-Latn",e[e.sr=68]="sr",e[e.sv=69]="sv",e[e.sw=70]="sw",e[e.ta=71]="ta",e[e.te=72]="te",e[e.th=73]="th",e[e.tr=74]="tr",e[e.uk=75]="uk",e[e.ur=76]="ur",e[e.uz=77]="uz",e[e.vi=78]="vi",e[e.zh=79]="zh",e[e["zh-HK"]=80]="zh-HK",e[e["zh-TW"]=81]="zh-TW",e[e.zu=82]="zu",e[e.MAX_VALUE=83]="MAX_VALUE"}(ce||(ce={})),function(e){e[e.OtherSection=0]="OtherSection",e[e.Identity=1]="Identity",e[e.Presentation=2]="Presentation",e[e["Protocol Handlers"]=3]="Protocol Handlers",e[e.Icons=4]="Icons",e[e["Window Controls Overlay"]=5]="Window Controls Overlay",e[e.MAX_VALUE=6]="MAX_VALUE"}(le||(le={}));var me=Object.freeze({__proto__:null,get Action(){return J},get DevtoolsExperiments(){return se},get ElementsSidebarTabCodes(){return re},get IssueCreated(){return de},get IssueExpanded(){return ie},get IssueResourceOpened(){return ae},get KeybindSetSettings(){return ne},get KeyboardShortcutAction(){return oe},get Language(){return ce},get ManifestSectionCodes(){return le},get MediaTypes(){return te},get PanelCodes(){return Z},get PanelWithLocation(){return ee},UserMetrics:ge});const pe=new ge,he=K();export{U as AidaClient,M as InspectorFrontendHost,i as InspectorFrontendHostAPI,X as Platform,ue as RNPerfMetrics,v as ResourceLoader,me as UserMetrics,he as rnPerfMetrics,pe as userMetrics}; diff --git a/packages/debugger-frontend/dist/third-party/front_end/panels/console/console.js b/packages/debugger-frontend/dist/third-party/front_end/panels/console/console.js index e4bcc233efaaec..6a87d2b8101815 100644 --- a/packages/debugger-frontend/dist/third-party/front_end/panels/console/console.js +++ b/packages/debugger-frontend/dist/third-party/front_end/panels/console/console.js @@ -3,4 +3,4 @@ import*as e from"../../core/common/common.js";import*as t from"../../core/i18n/i ${this.deletePinIcon}
- `;this.pinElement=i.element(),this.pinPreview=i.$("preview");const r=i.$("name");o.Tooltip.Tooltip.install(r,t),z.set(this.pinElement,this),this.lastResult=null,this.lastExecutionContext=null,this.committedExpression=t,this.hovered=!1,this.lastNode=null,this.editor=this.createEditor(t,r),this.pinPreview.addEventListener("mouseenter",this.setHovered.bind(this,!0),!1),this.pinPreview.addEventListener("mouseleave",this.setHovered.bind(this,!1),!1),this.pinPreview.addEventListener("click",(t=>{this.lastNode&&(e.Revealer.reveal(this.lastNode),t.consume())}),!1),r.addEventListener("keydown",(e=>{"Escape"===e.key&&e.consume()}))}createEditor(e,t){const s=[a.EditorView.contentAttributes.of({"aria-label":_(D.liveExpressionEditor)}),a.EditorView.lineWrapping,a.javascript.javascriptLanguage,l.Config.showCompletionHint,a.placeholder(_(D.expression)),a.keymap.of([{key:"Escape",run:e=>(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)},{key:"Enter",run:()=>(this.focusOut(),!0)},{key:"Mod-Enter",run:()=>(this.focusOut(),!0)},{key:"Tab",run:e=>null===a.completionStatus(this.editor.state)&&(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)},{key:"Shift-Tab",run:e=>null===a.completionStatus(this.editor.state)&&(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)}]),a.EditorView.domEventHandlers({blur:(e,t)=>this.onBlur(t)}),l.Config.baseConfiguration(e),l.Config.closeBrackets.instance(),l.Config.autocompletion.instance()];"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")&&s.push(l.JavaScript.completion());const n=new l.TextEditor.TextEditor(a.EditorState.create({doc:e,extensions:s}));return t.appendChild(n),n}onBlur(e){const t=e.state.doc.toString(),s=t.trim();this.committedExpression=s,this.pinPane.savePins(),this.committedExpression.length?this.deletePinIcon.setAccessibleName(_(D.removeExpressionS,{PH1:this.committedExpression})):this.deletePinIcon.setAccessibleName(_(D.removeBlankExpression)),e.dispatch({selection:{anchor:s.length},changes:s!==t?{from:0,to:t.length,insert:s}:void 0})}setHovered(e){this.hovered!==e&&(this.hovered=e,!e&&this.lastNode&&n.OverlayModel.OverlayModel.hideDOMNodeHighlight())}expression(){return this.committedExpression}element(){return this.pinElement}async focus(){const e=this.editor;e.editor.focus(),e.dispatch({selection:{anchor:e.state.doc.length}})}appendToContextMenu(e){this.lastResult&&!("error"in this.lastResult)&&this.lastResult.object&&(e.appendApplicableItems(this.lastResult.object),this.lastResult=null)}async updatePreview(){if(!this.editor)return;const e=l.Config.contentIncludingHint(this.editor.editor),t=this.pinElement.hasFocus(),s=t&&e!==this.committedExpression,i=s?250:void 0,r=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext),{preview:a,result:d}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(e,s,!0,i,!t,"live-expression",!0,!0);this.lastResult&&this.lastExecutionContext&&this.lastExecutionContext.runtimeModel.releaseEvaluationResult(this.lastResult),this.lastResult=d||null,this.lastExecutionContext=r||null;const h=a.deepTextContent();if(!h||h!==this.pinPreview.deepTextContent()){if(this.pinPreview.removeChildren(),d&&n.RuntimeModel.RuntimeModel.isSideEffectFailure(d)){const e=this.pinPreview.createChild("span","object-value-calculate-value-button");e.textContent="(…)",o.Tooltip.Tooltip.install(e,_(D.evaluateAllowingSideEffects))}else h?this.pinPreview.appendChild(a):t||o.UIUtils.createTextChild(this.pinPreview,_(D.notAvailable));o.Tooltip.Tooltip.install(this.pinPreview,h)}let u=null;d&&!("error"in d)&&"object"===d.object.type&&"node"===d.object.subtype&&(u=d.object),this.hovered&&(u?n.OverlayModel.OverlayModel.highlightObjectAsDOMNode(u):this.lastNode&&n.OverlayModel.OverlayModel.hideDOMNodeHighlight()),this.lastNode=u||null;const m=d&&!("error"in d)&&d.exceptionDetails&&!n.RuntimeModel.RuntimeModel.isSideEffectFailure(d);this.pinElement.classList.toggle("error-level",Boolean(m))}}var K=Object.freeze({__proto__:null,ConsolePin:q,ConsolePinPane:$}),J={cssText:`:host{overflow:auto}.count{flex:none;margin:0 var(--sys-size-3)}devtools-icon{&[name="cross-circle"]{color:var(--sys-color-error-bright)}&[name="warning"]{color:var(--icon-warning)}&[name="info"]{color:var(--icon-info)}}.tree-element-title{flex-grow:1}\n/*# sourceURL=${import.meta.resolve("./consoleSidebar.css")} */\n`};const X={other:"",dUserMessages:"{n, plural, =0 {No user messages} =1 {# user message} other {# user messages}}",dMessages:"{n, plural, =0 {No messages} =1 {# message} other {# messages}}",dErrors:"{n, plural, =0 {No errors} =1 {# error} other {# errors}}",dWarnings:"{n, plural, =0 {No warnings} =1 {# warning} other {# warnings}}",dInfo:"{n, plural, =0 {No info} =1 {# info} other {# info}}",dVerbose:"{n, plural, =0 {No verbose} =1 {# verbose} other {# verbose}}"},Z=t.i18n.registerUIStrings("panels/console/ConsoleSidebar.ts",X),Q=t.i18n.getLocalizedString.bind(void 0,Z);class Y extends(e.ObjectWrapper.eventMixin(o.Widget.VBox)){tree;selectedTreeElement;treeElements;constructor(){super(!0),this.setMinimumSize(125,0),this.tree=new o.TreeOutline.TreeOutlineInShadow("NavigationTree"),this.tree.addEventListener(o.TreeOutline.Events.ElementSelected,this.selectionChanged.bind(this)),this.tree.registerRequiredCSS(J),this.tree.hideOverflow(),this.contentElement.setAttribute("jslog",`${d.pane("sidebar").track({resize:!0})}`),this.contentElement.appendChild(this.tree.element),this.selectedTreeElement=null,this.treeElements=[];const t=e.Settings.Settings.instance().createSetting("console.sidebar-selected-filter",null),s=[{key:R.Source,text:e.Console.FrontendMessageSource.ConsoleAPI,negative:!1,regex:void 0}];this.appendGroup("message",[],P.allLevelsFilterValue(),h.Icon.create("list"),t),this.appendGroup("user message",s,P.allLevelsFilterValue(),h.Icon.create("profile"),t),this.appendGroup("error",[],P.singleLevelMask("error"),h.Icon.create("cross-circle"),t),this.appendGroup("warning",[],P.singleLevelMask("warning"),h.Icon.create("warning"),t),this.appendGroup("info",[],P.singleLevelMask("info"),h.Icon.create("info"),t),this.appendGroup("verbose",[],P.singleLevelMask("verbose"),h.Icon.create("bug"),t);const n=t.get();(this.treeElements.find((e=>e.name()===n))||this.treeElements[0]).select()}appendGroup(e,t,s,n,o){const i=new P(e,t,null,s),r=new ne(i,n,o);this.tree.appendChild(r),this.treeElements.push(r)}clear(){for(const e of this.treeElements)e.clear()}onMessageAdded(e){for(const t of this.treeElements)t.onMessageAdded(e)}shouldBeVisible(e){return!(this.selectedTreeElement instanceof ee)||this.selectedTreeElement.filter().shouldBeVisible(e)}selectionChanged(e){this.selectedTreeElement=e.data,this.dispatchEventToListeners("FilterSelected")}}class ee extends o.TreeOutline.TreeElement{filterInternal;constructor(e,t){super(e),this.filterInternal=t}filter(){return this.filterInternal}}class te extends ee{countElement;messageCount;constructor(e){super(e.name,e),this.countElement=this.listItemElement.createChild("span","count");const t=h.Icon.create("document");this.setLeadingIcons([t]),this.messageCount=0}incrementAndUpdateCounter(){this.messageCount++,this.countElement.textContent=`${this.messageCount}`}}const se=new Map([["user message",X.dUserMessages],["message",X.dMessages],["error",X.dErrors],["warning",X.dWarnings],["info",X.dInfo],["verbose",X.dVerbose]]);class ne extends ee{selectedFilterSetting;urlTreeElements;messageCount;uiStringForFilterCount;constructor(e,t,s){super(e.name,e),this.uiStringForFilterCount=se.get(e.name)||"",this.selectedFilterSetting=s,this.urlTreeElements=new Map,this.setLeadingIcons([t]),this.messageCount=0,this.updateCounter()}clear(){this.urlTreeElements.clear(),this.removeChildren(),this.messageCount=0,this.updateCounter()}name(){return this.filterInternal.name}onselect(e){return this.selectedFilterSetting.set(this.filterInternal.name),super.onselect(e)}updateCounter(){this.title=this.updateGroupTitle(this.messageCount),this.setExpandable(Boolean(this.childCount()))}updateGroupTitle(e){return this.uiStringForFilterCount?Q(this.uiStringForFilterCount,{n:e}):""}onMessageAdded(e){const t=e.consoleMessage(),s=t.type!==n.ConsoleModel.FrontendMessageType.Command&&t.type!==n.ConsoleModel.FrontendMessageType.Result&&!t.isGroupMessage();if(!this.filterInternal.shouldBeVisible(e)||!s)return;this.childElement(t.url).incrementAndUpdateCounter(),this.messageCount++,this.updateCounter()}childElement(t){const s=t||null;let n=this.urlTreeElements.get(s);if(n)return n;const o=this.filterInternal.clone(),i=s?e.ParsedURL.ParsedURL.fromString(s):null;return o.name=s?i?i.displayName:s:Q(X.other),o.parsedFilters.push({key:R.Url,text:s,negative:!1,regex:void 0}),n=new te(o),s&&(n.tooltip=s),this.urlTreeElements.set(s,n),this.appendChild(n),n}}var oe=Object.freeze({__proto__:null,ConsoleSidebar:Y,FilterTreeElement:ne,URLGroupTreeElement:te}),ie={cssText:`.console-view{background-color:var(--sys-color-cdt-base-container);overflow:hidden;--override-error-text-color:var(--sys-color-on-error-container);--message-corner-rounder-background:var(--sys-color-cdt-base-container)}.console-toolbar-container{display:flex;flex:none}.console-main-toolbar{flex:1 1 auto}#console-issues-counter{margin-top:0}.console-toolbar-container > devtools-toolbar{background-color:var(--sys-color-cdt-base-container);border-bottom:1px solid var(--sys-color-divider)}.console-view-fix-select-all{height:0;overflow:hidden}.console-settings-pane{display:grid;grid-template-columns:50% 50%;flex:none;background-color:var(--sys-color-cdt-base-container);border-bottom:1px solid var(--sys-color-divider)}#console-messages{flex:1 1;overflow-y:auto;word-wrap:break-word;user-select:text;transform:translateZ(0);overflow-anchor:none;background-color:var(--sys-color-cdt-base-container)}#console-prompt{clear:right;position:relative;margin:0 22px 0 20px}.console-prompt-editor-container{min-height:21px}.console-message,\n.console-user-command{clear:right;position:relative;padding:3px 22px 1px 0;margin-left:24px;min-height:17px;flex:auto;display:flex}.console-message > *{flex:auto}.console-timestamp{color:var(--sys-color-token-subtle);user-select:none;flex:none;margin-right:5px}.message-level-icon,\n.command-result-icon{position:absolute;left:-17px;top:2px;user-select:none}.console-message-repeat-count{margin:1.4px 0 0 10px;flex:none}.repeated-message{margin-left:4px}.repeated-message .message-level-icon{display:none}.console-message-stack-trace-toggle{display:flex;flex-direction:row;align-items:flex-start;margin-top:-1px}.console-error-level .repeated-message,\n.console-warning-level .repeated-message,\n.console-verbose-level .repeated-message,\n.console-info-level .repeated-message{display:flex}.console-info{color:var(--sys-color-token-subtle);font-style:italic;padding-bottom:2px}.console-group .console-group > .console-group-messages{margin-left:16px}.console-group-title.console-from-api{font-weight:bold}.console-group-title .console-message{margin-left:12px}.expand-group-icon{user-select:none;flex:none;position:relative;left:8px;top:3px;margin-right:2px}.console-group-title .message-level-icon{display:none}.console-message-repeat-count .expand-group-icon{position:static;color:var(--sys-color-cdt-base-container);margin-left:-1px}.console-group{position:relative}.console-message-wrapper{display:flex;flex-direction:column;margin:4px;border-radius:5px;--console-color-black:#000;--console-color-red:#a00;--console-color-green:#0a0;--console-color-yellow:#a50;--console-color-blue:#00a;--console-color-magenta:#a0a;--console-color-cyan:#0aa;--console-color-gray:#aaa;--console-color-darkgray:#555;--console-color-lightred:#f55;--console-color-lightgreen:#5f5;--console-color-lightyellow:#ff5;--console-color-lightblue:#55f;--console-color-ightmagenta:#f5f;--console-color-lightcyan:#5ff;--console-color-white:#fff;&:focus{background-color:var(--sys-color-tonal-container);& ::selection{background-color:var(--sys-color-state-focus-select);color:currentcolor}}}.console-row-wrapper{display:flex;flex-direction:row}.theme-with-dark-background .console-message-wrapper{--console-color-red:rgb(237 78 76);--console-color-green:rgb(1 200 1);--console-color-yellow:rgb(210 192 87);--console-color-blue:rgb(39 116 240);--console-color-magenta:rgb(161 66 244);--console-color-cyan:rgb(18 181 203);--console-color-gray:rgb(207 208 208);--console-color-darkgray:rgb(137 137 137);--console-color-lightred:rgb(242 139 130);--console-color-lightgreen:rgb(161 247 181);--console-color-lightyellow:rgb(221 251 85);--console-color-lightblue:rgb(102 157 246);--console-color-lightmagenta:rgb(214 112 214);--console-color-lightcyan:rgb(132 240 255)}.console-message-wrapper.console-warning-level + .console-message-wrapper,\n.console-message-wrapper.console-error-level + .console-message-wrapper{& .console-message::before,\n & .console-user-command::before{display:none!important}}.console-message-wrapper:not(.console-error-level, .console-warning-level){& .console-message::before,\n & .console-user-command::before{width:calc(100% - 25px);content:"";display:block;position:absolute;top:-2px;border-top:1px solid var(--sys-color-divider)}&:first-of-type .console-message::before,\n &:first-of-type .console-user-command::before{display:none}}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level){border-top-width:0}.console-message-wrapper:focus + .console-message-wrapper{border-top-color:transparent}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus{border-top-width:1px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus .console-message{padding-top:2px;min-height:16px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus .command-result-icon{top:3px}.console-message-wrapper .nesting-level-marker{width:14px;flex:0 0 auto;position:relative;margin-bottom:-1px;margin-top:-1px;background-color:var(--sys-color-cdt-base-container)}.console-message-wrapper .nesting-level-marker + .console-message::after{position:absolute;left:-30px;top:0;width:6px;height:100%;box-sizing:border-box;background-color:var(--sys-color-surface-yellow);border-top-left-radius:5px;border-bottom-left-radius:5px;content:""}.console-error-level{background-color:var(--sys-color-surface-error);--message-corner-rounder-background:var(--sys-color-surface-error)}.console-warning-level{background-color:var(--sys-color-surface-yellow);--message-corner-rounder-background:var(--sys-color-surface-yellow)}.console-view-object-properties-section{padding:0;position:relative;vertical-align:baseline;color:inherit;display:inline-block;overflow-wrap:break-word;max-width:100%}.info-note{background-color:var(--sys-color-tonal-container)}.info-note::before{content:"i"}.console-view-object-properties-section:not(.expanded) .info-note{display:none}.console-system-type.console-info-level{color:var(--sys-color-primary)}#console-messages .link{cursor:pointer;text-decoration:underline}#console-messages .link,\n#console-messages .devtools-link:not(.invalid-link){color:var(--sys-color-primary);word-break:break-all}#console-messages .devtools-link.ignore-list-link{opacity:60%}#console-messages .devtools-link:focus-visible{background-color:transparent}#console-messages .resource-links{margin-top:-1px;margin-bottom:-2px}.console-object-preview{white-space:normal;word-wrap:break-word;font-style:italic}.console-object-preview .name{flex-shrink:0}.console-message-text{.object-value-node{display:inline-block}.object-value-string,\n .object-value-regexp,\n .object-value-symbol{white-space:pre-wrap;word-break:break-all}.formatted-stack-frame:has(.ignore-list-link){display:var(--display-ignored-formatted-stack-frame);opacity:60%;& + .formatted-builtin-stack-frame{display:var(--display-ignored-formatted-stack-frame);opacity:60%}}}.console-message-stack-trace-wrapper{--override-display-stack-preview-toggle-link:none;flex:1 1 auto;display:flex;flex-direction:column;align-items:stretch;&:has(div > .stack-preview-container.show-hidden-rows){--display-ignored-formatted-stack-frame:inherit}&:has(.formatted-stack-frame .ignore-list-link):has(.formatted-stack-frame .devtools-link:not(.ignore-list-link)){--override-display-stack-preview-toggle-link:table-row;--override-display-stack-preview-hidden-div:block;&:not(:has(div > .stack-preview-container.show-hidden-rows)){--display-ignored-formatted-stack-frame:none}}& > .hidden-stack-trace{display:var(--override-display-stack-preview-hidden-div,none);--override-display-stack-preview-tbody:none}}.repeated-message .console-message-stack-trace-toggle,\n.repeated-message > .console-message-text{flex:1}.console-warning-level .console-message-text{color:var(--sys-color-on-surface-yellow)}.console-error-level .console-message-text,\n.console-error-level .console-view-object-properties-section{color:var(--override-error-text-color)!important}.console-message-formatted-table{clear:both}.console-message .source-code{line-height:1.2}.console-message-anchor{float:right;text-align:right;max-width:100%;margin-left:4px}.cookie-report-anchor{margin-top:-3px;margin-bottom:-5px}.console-message-nowrap-below,\n.console-message-nowrap-below div,\n.console-message-nowrap-below span{white-space:nowrap!important}.object-state-note{display:inline-block;width:11px;height:11px;color:var(--sys-color-on-tonal-container);text-align:center;border-radius:3px;line-height:13px;margin:0 6px;font-size:9px}.console-object{white-space:pre-wrap;word-break:break-all}.console-message-stack-trace-wrapper > *{flex:none}.console-message-expand-icon{margin-bottom:-4px}.console-searchable-view{max-height:100%}.console-view-pinpane{flex:none;max-height:50%}.message-count{width:0;height:0}devtools-console-insight{margin:9px 22px 11px 24px}.hover-button{--width:24px;align-items:center;border-radius:50%;border:none;box-shadow:0 1px 3px 1px rgb(0 0 0/15%),0 1px 2px 0 rgb(0 0 0/30%);box-sizing:border-box;background-color:var(--sys-color-tonal-container);color:var(--sys-color-on-tonal-container);font:var(--sys-typescale-body4-medium);height:var(--width);justify-content:center;margin:0;max-height:var(--width);max-width:var(--width);min-height:var(--width);min-width:var(--width);overflow:hidden;padding:var(--sys-size-3) var(--sys-size-4);position:absolute;right:6px;display:none;width:var(--width);z-index:1;.theme-with-dark-background &{border:1px solid var(--sys-color-neutral-outline);background-color:var(--sys-color-primary);color:var(--sys-color-on-primary)}& devtools-icon{box-sizing:border-box;flex-shrink:0;height:var(--sys-size-8);min-height:var(--sys-size-8);min-width:var(--sys-size-8);width:var(--sys-size-8);--devtools-icon-color:var(--sys-color-on-tonal-container)}.theme-with-dark-background & devtools-icon{--devtools-icon-color:var(--sys-color-on-primary)}}.hover-button:focus,\n.hover-button:hover{border-radius:4px;max-width:200px;transition:max-width var(--sys-motion-duration-short4) var(--sys-motion-easing-emphasized),border-radius 50ms linear;width:fit-content;gap:var(--sys-size-3)}.hover-button:focus-visible{outline:2px solid var(--sys-color-primary);outline-offset:2px}.button-label{display:block;overflow:hidden;white-space:nowrap;& div{display:inline-block;vertical-align:-1px}}.console-message-wrapper:not(.has-insight){&:hover,\n &:focus,\n &.console-selected{.hover-button{display:flex;&:focus,\n &:hover{display:inline-flex}}}}@media (forced-colors: active){.console-message-expand-icon,\n .console-warning-level .expand-group-icon{forced-color-adjust:none;color:ButtonText}.console-message-wrapper:focus,\n .console-message-wrapper:focus:last-of-type{forced-color-adjust:none;background-color:Highlight;border-top-color:Highlight;border-bottom-color:Highlight}.console-message-wrapper:focus *,\n .console-message-wrapper:focus:last-of-type *,\n .console-message-wrapper:focus .devtools-link,\n .console-message-wrapper:focus:last-of-type .devtools-link{color:HighlightText!important}#console-messages .devtools-link,\n #console-messages .devtools-link:hover{color:linktext}#console-messages .link:focus-visible,\n #console-messages .devtools-link:focus-visible{background:Highlight;color:HighlightText}.console-message-wrapper:focus devtools-icon{color:HighlightText}.console-message-wrapper.console-error-level:focus,\n .console-message-wrapper.console-error-level:focus:last-of-type{--override-error-text-color:HighlightText}}\n/*# sourceURL=${import.meta.resolve("./consoleView.css")} */\n`};function re(t,s){if(!/^[\w.]*Error\b/.test(s))return null;const n=t.debuggerModel(),o=t.target().inspectedURL(),i=s.split("\n"),r=[];for(const t of i){const i=/^\s*at\s(async\s)?/.exec(t);if(!i){if(r.length&&r[r.length-1].isCallFrame)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'"at (url)" not found'),null;r.push({line:t});continue}const a=!0;let l=i[0].length,c=t.length,d=!1;for(;")"===t[c-1];)for(c--,d=!0;;){if(l=t.indexOf(" (",l),l<0)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'left "(" not found'),null;if(l+=2,!t.substring(l).startsWith("eval at "))break;if(l+=8,c=t.lastIndexOf(", ",c)-1,c<0)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'right "(" not found'),null}const h=t.substring(l,c),u=e.ParsedURL.ParsedURL.splitLineAndColumn(h);if(""===u.url||"native"===u.url){r.length&&r[r.length-1].isCallFrame&&!r[r.length-1].link?r[r.length-1].line+=`\n${t}`:r.push({line:t,isCallFrame:a});continue}let p=ae(n,u.url);if(!p&&e.ParsedURL.ParsedURL.isRelativeURL(u.url)&&(p=ae(n,e.ParsedURL.ParsedURL.completeURL(o,u.url))),!p)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,"url parsing failed"),null;r.push({line:t,isCallFrame:a,link:{url:p,prefix:t.substring(0,l),suffix:t.substring(c),enclosedInBraces:d,lineNumber:u.lineNumber,columnNumber:u.columnNumber}})}return r}function ae(t,s){if(!s)return null;if(e.ParsedURL.ParsedURL.isValidUrlString(s))return s;if(t.scriptsForSourceURL(s).length)return s;const n=new URL(s,"file://");return t.scriptsForSourceURL(n.href).length?n.href:null}function le(e,t){for(const s of e){const e=t.callFrames.find((e=>ce(s,e)));e&&s.link&&(s.link.scriptId=e.scriptId)}}function ce(e,t){if(!e.link)return!1;const{url:s,lineNumber:n,columnNumber:o}=e.link;return s===t.url&&n===t.lineNumber&&o===t.columnNumber}var de=Object.freeze({__proto__:null,augmentErrorStackWithScriptIds:le,parseSourcePositionsFromErrorStack:re});const he={consoleclearWasPreventedDueTo:"`console.clear()` was prevented due to 'Preserve log'",consoleWasCleared:"Console was cleared",clearAllMessagesWithS:"Clear all messages with {PH1}",assertionFailed:"Assertion failed: ",violationS:"`[Violation]` {PH1}",interventionS:"`[Intervention]` {PH1}",deprecationS:"`[Deprecation]` {PH1}",thisValueWillNotBeCollectedUntil:"This value will not be collected until console is cleared.",thisValueWasEvaluatedUponFirst:"This value was evaluated upon first expanding. It may have changed since then.",functionWasResolvedFromBound:"Function was resolved from bound function.",exception:"",warning:"Warning",error:"Error",logpoint:"Logpoint",cndBreakpoint:"Conditional Breakpoint",repeatS:"{n, plural, =1 {Repeated # time} other {Repeated # times}}",warningS:"{n, plural, =1 {Warning, Repeated # time} other {Warning, Repeated # times}}",errorS:"{n, plural, =1 {Error, Repeated # time} other {Error, Repeated # times}}",url:"",tookNms:"took ms",someEvent:" event",Mxx:" M",attribute:"",index:"(index)",value:"Value",console:"Console",stackMessageExpanded:"Stack table expanded",stackMessageCollapsed:"Stack table collapsed",explainThisError:"Understand this error",explainThisWarning:"Understand this warning",explainThisMessage:"Understand this message",explainThisErrorWithAI:"Understand this error. Powered by AI.",explainThisWarningWithAI:"Understand this warning. Powered by AI.",explainThisMessageWithAI:"Understand this message. Powered by AI",SeeIssueInCookieReport:"Click to open privacy and security panel and show third-party cookie report"},ue=t.i18n.registerUIStrings("panels/console/ConsoleViewMessage.ts",he),me=t.i18n.getLocalizedString.bind(void 0,ue),pe=new WeakMap,ge=e=>pe.get(e),ve=(e,t)=>{const s=e.indexOf("\n"),n=-1===s?e:e.substring(0,s),o=-1===s?"":e.substring(s);return e=`${n}. ${t}${o}`},fe=e=>t=>t instanceof n.RemoteObject.RemoteObject?t:e?"object"==typeof t?e.createRemoteObject(t):e.createRemoteObjectFromPrimitiveValue(t):n.RemoteObject.RemoteObject.fromLocalObject(t),be="explain.console-message.hover",Ce=new IntersectionObserver((e=>{for(const t of e)t.intersectionRatio>0&&m.userMetrics.actionTaken(m.UserMetrics.Action.InsightHoverButtonShown)}));class xe{message;linkifier;repeatCountInternal;closeGroupDecorationCount;consoleGroupInternal;selectableChildren;messageResized;elementInternal;consoleRowWrapper=null;previewFormatter;searchRegexInternal;messageIcon;traceExpanded;expandTrace;anchorElement;contentElementInternal;nestingLevelMarkers;searchHighlightNodes;searchHighlightNodeChanges;isVisibleInternal;cachedHeight;messagePrefix;timestampElement;inSimilarGroup;similarGroupMarker;lastInSimilarGroup;groupKeyInternal;repeatCountElement;requestResolver;issueResolver;#e=!1;#t=Promise.resolve();constructor(e,t,s,n,o){this.message=e,this.linkifier=t,this.requestResolver=s,this.issueResolver=n,this.repeatCountInternal=1,this.closeGroupDecorationCount=0,this.selectableChildren=[],this.messageResized=o,this.elementInternal=null,this.previewFormatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.searchRegexInternal=null,this.messageIcon=null,this.traceExpanded=!1,this.expandTrace=null,this.anchorElement=null,this.contentElementInternal=null,this.nestingLevelMarkers=null,this.searchHighlightNodes=[],this.searchHighlightNodeChanges=[],this.isVisibleInternal=!1,this.cachedHeight=0,this.messagePrefix="",this.timestampElement=null,this.inSimilarGroup=!1,this.similarGroupMarker=null,this.lastInSimilarGroup=!1,this.groupKeyInternal="",this.repeatCountElement=null,this.consoleGroupInternal=null}setInsight(e){this.elementInternal?.querySelector("devtools-console-insight")?.remove(),this.elementInternal?.append(e),this.elementInternal?.classList.toggle("has-insight",!0),e.addEventListener("close",(()=>{m.userMetrics.actionTaken(m.UserMetrics.Action.InsightClosed),this.elementInternal?.classList.toggle("has-insight",!1),this.elementInternal?.removeChild(e)}),{once:!0})}element(){return this.toMessageElement()}wasShown(){this.isVisibleInternal=!0}onResize(){}willHide(){this.isVisibleInternal=!1,this.cachedHeight=this.element().offsetHeight}isVisible(){return this.isVisibleInternal}fastHeight(){return this.cachedHeight?this.cachedHeight:this.approximateFastHeight()}approximateFastHeight(){return 19}consoleMessage(){return this.message}formatErrorStackPromiseForTest(){return this.#t}buildMessage(){let t,s=this.message.messageText;if(this.message.source===e.Console.FrontendMessageSource.ConsoleAPI)switch(this.message.type){case"trace":t=this.format(this.message.parameters||["console.trace"]);break;case"clear":t=document.createElement("span"),t.classList.add("console-info"),e.Settings.Settings.instance().moduleSetting("preserve-console-log").get()?t.textContent=me(he.consoleclearWasPreventedDueTo):t.textContent=me(he.consoleWasCleared),o.Tooltip.Tooltip.install(t,me(he.clearAllMessagesWithS,{PH1:String(o.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction("console.clear"))}));break;case"dir":{const e=["%O",this.message.parameters?this.message.parameters[0]:void 0];t=this.format(e);break}case"profile":case"profileEnd":t=this.format([s]);break;default:{if("assert"===this.message.type&&(this.messagePrefix=me(he.assertionFailed)),this.message.parameters&&1===this.message.parameters.length){const e=this.message.parameters[0];"string"!=typeof e&&"string"===e.type&&(t=this.tryFormatAsError(e.value))}const e=this.message.parameters||[s];t=t||this.format(e)}}else if("network"===this.message.source)t=this.formatAsNetworkRequest()||this.format([s]);else{const e=this.message.parameters&&s===this.message.parameters[0];"violation"===this.message.source?s=me(he.violationS,{PH1:s}):"intervention"===this.message.source?s=me(he.interventionS,{PH1:s}):"deprecation"===this.message.source&&(s=me(he.deprecationS,{PH1:s}));const n=this.message.parameters||[s];e&&(n[0]=s),t=this.format(n)}t.classList.add("console-message-text");const n=document.createElement("span");if(n.classList.add("source-code"),this.anchorElement=this.buildMessageAnchor(),this.anchorElement&&n.appendChild(this.anchorElement),n.appendChild(t),"fusebox_preserve_log_rec"===this.message.context){const t=document.createElement("button");t.classList.add("devtools-link","text-button","link-style"),t.appendChild(t.ownerDocument.createTextNode("show settings")),t.addEventListener("click",(async()=>{await e.Revealer.reveal(e.Settings.Settings.instance().moduleSetting("preserve-console-log"))})),n.appendChild(t)}return n}formatAsNetworkRequest(){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(this.message);if(!e)return null;const t=document.createElement("span");if("error"===this.message.level){o.UIUtils.createTextChild(t,e.requestMethod+" ");const s=u.Linkifier.Linkifier.linkifyRevealable(e,e.url(),e.url(),void 0,void 0,"network-request");s.tabIndex=-1,this.selectableChildren.push({element:s,forceSelect:()=>s.focus()}),t.appendChild(s),e.failed&&o.UIUtils.createTextChildren(t," ",e.localizedFailDescription||""),0!==e.statusCode&&o.UIUtils.createTextChildren(t," ",String(e.statusCode));const n=e.getInferredStatusText();n&&o.UIUtils.createTextChildren(t," (",n,")")}else{const s=this.message.messageText,n=this.linkifyWithCustomLinkifier(s,((t,s,n,o)=>{const i=s===e.url()?u.Linkifier.Linkifier.linkifyRevealable(e,s,e.url(),void 0,void 0,"network-request"):u.Linkifier.Linkifier.linkifyURL(s,{text:t,lineNumber:n,columnNumber:o});return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}));t.appendChild(n)}return t}createAffectedResourceLinks(){const e=[],t=this.message.getAffectedResources()?.requestId;if(t){const s=new x.RequestLinkIcon.RequestLinkIcon;s.classList.add("resource-links"),s.data={affectedRequest:{requestId:t},requestResolver:this.requestResolver,displayURL:!1},e.push(s)}const s=this.message.getAffectedResources()?.issueId;if(s){const t=new C.IssueLinkIcon.IssueLinkIcon;t.classList.add("resource-links"),t.data={issueId:s,issueResolver:this.issueResolver},e.push(t)}return e}#s(t){const s=new f.Button.Button;s.data={size:"SMALL",variant:"icon",iconName:"cookie",jslogContext:"privacy",title:me(he.SeeIssueInCookieReport)},s.addEventListener("click",(()=>{e.Revealer.reveal(new S.CookieReportView.CookieReportView)})),t.appendChild(s)}#n(){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(this.message);if(e?.resourceType().isStyleSheet())return m.UserMetrics.Action.StyleSheetInitiatorLinkClicked}buildMessageAnchor(){const e=this.message.runtimeModel();if(!e)return null;if(this.message.isCookieReportIssue&&r.Runtime.hostConfig.devToolsPrivacyUI?.enabled){const e=document.createElement("span");return e.classList.add("console-message-anchor","cookie-report-anchor"),this.#s(e),o.UIUtils.createTextChild(e," "),e}const t=(({stackFrameWithBreakpoint:t,scriptId:n,stackTrace:o,url:i,line:r,column:a})=>{const l=this.#n();return t?this.linkifier.maybeLinkifyConsoleCallFrame(e.target(),t,{inlineFrameIndex:0,revealBreakpoint:!0,userMetric:l}):n?this.linkifier.linkifyScriptLocation(e.target(),n,i||s.DevToolsPath.EmptyUrlString,r,{columnNumber:a,inlineFrameIndex:0,userMetric:l}):o?.callFrames.length?this.linkifier.linkifyStackTraceTopFrame(e.target(),o):i&&"undefined"!==i?this.linkifier.linkifyScriptLocation(e.target(),null,i,r,{columnNumber:a,inlineFrameIndex:0,userMetric:l}):null})(this.message);if(t){t.tabIndex=-1,this.selectableChildren.push({element:t,forceSelect:()=>t.focus()});const e=document.createElement("span");e.classList.add("console-message-anchor"),e.appendChild(t);for(const t of this.createAffectedResourceLinks())o.UIUtils.createTextChild(e," "),e.append(t);return o.UIUtils.createTextChild(e," "),e}return null}buildMessageWithStackTrace(t){const s=h.Icon.create("triangle-right","console-message-expand-icon"),{stackTraceElement:n,contentElement:i,messageElement:r,clickableElement:a,toggleElement:l}=this.buildMessageHelper(t.target(),this.message.stackTrace,s);let c;this.expandTrace=e=>{e?c=window.setTimeout((()=>{m.userMetrics.actionTaken(m.UserMetrics.Action.TraceExpanded)}),300):clearTimeout(c),s.name=e?"triangle-down":"triangle-right",n.classList.toggle("hidden-stack-trace",!e);const t=me(e?he.stackMessageExpanded:he.stackMessageCollapsed);o.ARIAUtils.setLabel(i,`${r.textContent} ${t}`),o.ARIAUtils.alert(t),o.ARIAUtils.setExpanded(a,e),this.traceExpanded=e};return a.addEventListener("click",(e=>{o.UIUtils.isEditing()||i.hasSelection()||(this.expandTrace&&this.expandTrace(n.classList.contains("hidden-stack-trace")),e.consume())}),!1),"trace"===this.message.type&&e.Settings.Settings.instance().moduleSetting("console-trace-expand").get()&&this.expandTrace(!0),l._expandStackTraceForTest=this.expandTrace.bind(this,!0),l}buildMessageWithIgnoreLinks(){const{toggleElement:e}=this.buildMessageHelper(null,void 0,null);return e}buildMessageHelper(e,t,s){const n=document.createElement("div");n.classList.add("console-message-stack-trace-toggle");const i=n.createChild("div","console-message-stack-trace-wrapper"),r=this.buildMessage(),a=i.createChild("div");o.ARIAUtils.setExpanded(a,!1),s&&a.appendChild(s),a.tabIndex=-1,a.appendChild(r);const l=i.createChild("div"),c=u.JSPresentationUtils.buildStackTracePreviewContents(e,this.linkifier,{stackTrace:t,tabStops:void 0,widthConstrained:!0});l.appendChild(c.element);for(const e of c.links)this.selectableChildren.push({element:e,forceSelect:()=>e.focus()});return l.classList.add("hidden-stack-trace"),o.ARIAUtils.setLabel(i,`${r.textContent} ${me(he.stackMessageCollapsed)}`),o.ARIAUtils.markAsGroup(l),{stackTraceElement:l,contentElement:i,messageElement:r,clickableElement:a,toggleElement:n}}format(e){const t=document.createElement("span");if(this.messagePrefix&&(t.createChild("span").textContent=this.messagePrefix),!e.length)return t;let s=e.map(fe(this.message.runtimeModel()));const i="string"===n.RemoteObject.RemoteObject.type(s[0])&&(this.message.type!==n.ConsoleModel.FrontendMessageType.Result||"error"===this.message.level);i&&(s=this.formatWithSubstitutionString(s[0].description,s.slice(1),t),s.length&&o.UIUtils.createTextChild(t," "));for(let e=0;eRe()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),s,Ae());t.appendChild(e.element)}else o.UIUtils.createTextChild(t,s);return t.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),t}formatParameterAsTrustedType(e){const t=document.createElement("span"),s=document.createElement("span");return s.appendChild(this.formatParameterAsString(e)),s.classList.add("object-value-string"),o.UIUtils.createTextChild(t,`${e.className} `),t.appendChild(s),t}formatParameterAsObject(e,t){const s=document.createElement("span");if(s.classList.add("console-object"),t&&e.preview)s.classList.add("console-object-preview"),this.previewFormatter.appendObjectPreview(s,e.preview,!1),c.ObjectPropertiesSection.ObjectPropertiesSection.appendMemoryIcon(s,e);else if("function"===e.type){const t=s.createChild("span");c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(e,t,!1),s.classList.add("object-value-function")}else"trustedtype"===e.subtype?s.appendChild(this.formatParameterAsTrustedType(e)):o.UIUtils.createTextChild(s,e.description||"");if(!e.hasChildren||e.customPreview())return s;const i=s.createChild("span","object-state-note info-note");this.message.type===n.ConsoleModel.FrontendMessageType.QueryObjectResult?o.Tooltip.Tooltip.install(i,me(he.thisValueWillNotBeCollectedUntil)):o.Tooltip.Tooltip.install(i,me(he.thisValueWasEvaluatedUponFirst));const r=new c.ObjectPropertiesSection.ObjectPropertiesSection(e,s,this.linkifier);return r.element.classList.add("console-view-object-properties-section"),r.enableContextMenu(),r.setShowSelectionOnKeyboardFocus(!0,!0),this.selectableChildren.push(r),r.addEventListener(o.TreeOutline.Events.ElementAttached,this.messageResized),r.addEventListener(o.TreeOutline.Events.ElementExpanded,this.messageResized),r.addEventListener(o.TreeOutline.Events.ElementCollapsed,this.messageResized),r.element}formatParameterAsFunction(e,t){const s=document.createElement("span");return n.RemoteObject.RemoteFunction.objectAsFunction(e).targetFunction().then(function(n){const i=document.createElement("span"),r=c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(n,i,!0,t);if(s.appendChild(i),n!==e){const e=s.createChild("span","object-state-note info-note");o.Tooltip.Tooltip.install(e,me(he.functionWasResolvedFromBound))}s.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),r.then((()=>this.formattedParameterAsFunctionForTest()))}.bind(this)),s}formattedParameterAsFunctionForTest(){}contextMenuEventFired(e,t){const s=new o.ContextMenu.ContextMenu(t);s.appendApplicableItems(e),s.show()}renderPropertyPreviewOrAccessor(e,t,s){return"accessor"===t.type?this.formatAsAccessorProperty(e,s.map((e=>e.name.toString())),!1):this.previewFormatter.renderPropertyPreview(t.type,"subtype"in t?t.subtype:void 0,null,t.value)}formatParameterAsNode(e){const t=document.createElement("span"),s=e.runtimeModel().target().model(n.DOMModel.DOMModel);return s?(s.pushObjectAsNodeToFrontend(e).then((async s=>{if(!s)return void t.appendChild(this.formatParameterAsObject(e,!1));const n=await o.UIUtils.Renderer.render(s);n?(n.tree&&(this.selectableChildren.push(n.tree),n.tree.addEventListener(o.TreeOutline.Events.ElementAttached,this.messageResized),n.tree.addEventListener(o.TreeOutline.Events.ElementExpanded,this.messageResized),n.tree.addEventListener(o.TreeOutline.Events.ElementCollapsed,this.messageResized)),t.appendChild(n.node)):t.appendChild(this.formatParameterAsObject(e,!1)),this.formattedParameterAsNodeForTest()})),t):t}formattedParameterAsNodeForTest(){}formatParameterAsString(e){const t=e.description??"",n=s.StringUtilities.formatAsJSLiteral(t),o=document.createElement("span");return o.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),o.appendChild(this.linkifyStringAsFragment(n)),o}formatParameterAsError(e){const t=document.createElement("span"),s=async(e,o=!1)=>{const i=n.RemoteObject.RemoteError.objectAsError(e),[r,a]=await Promise.all([i.exceptionDetails(),i.cause()]);let l=this.tryFormatAsError(i.errorStack,r);if(l||(l=document.createElement("span"),l.append(this.linkifyStringAsFragment(i.errorStack))),o){const e=document.createElement("div");e.append("Caused by: ",l),t.appendChild(e)}else t.appendChild(l);if(a&&"error"===a.subtype)await s(a,!0);else if(a&&"string"===a.type){const e=document.createElement("div");e.append(`Caused by: ${a.value}`),t.append(e)}};return this.#t=s(e),t}formatAsArrayEntry(e){return this.previewFormatter.renderPropertyPreview(e.type,e.subtype,e.className,e.description)}formatAsAccessorProperty(e,t,n){const i=c.ObjectPropertiesSection.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(e,t,function(e){const t=e.wasThrown,r=e.object;if(!r)return;if(i.removeChildren(),t){const e=i.createChild("span");e.textContent=me(he.exception),o.Tooltip.Tooltip.install(e,r.description)}else if(n)i.appendChild(this.formatAsArrayEntry(r));else{const e=100,t=r.type,n=r.subtype;let o="";"function"!==t&&r.description&&(o="string"===t||"regexp"===n||"trustedtype"===n?s.StringUtilities.trimMiddle(r.description,e):s.StringUtilities.trimEndWithMaxLength(r.description,e)),i.appendChild(this.previewFormatter.renderPropertyPreview(t,n,r.className,o))}}.bind(this));return i}formatWithSubstitutionString(e,t,s){const n=new Map,{tokens:o,args:i}=j(e,t);for(const e of o)switch(e.type){case"generic":s.append(this.formatParameter(e.value,!0,!1));break;case"optimal":s.append(this.formatParameter(e.value,!1,!0));break;case"string":if(0===n.size)s.append(this.linkifyStringAsFragment(e.value));else{const t=e.value.split("\n");for(let e=0;e0&&s.append(document.createElement("br"));const o=document.createElement("span");o.style.setProperty("contain","paint"),o.style.setProperty("display","inline-block"),o.style.setProperty("max-width","100%"),o.appendChild(this.linkifyStringAsFragment(t[e]));for(const[e,{value:t,priority:s}]of n)o.style.setProperty(e,t,s);s.append(o)}}break;case"style":O(n,e.value)}return i}matchesFilterRegex(e){e.lastIndex=0;const t=this.contentElement(),s=this.anchorElement?this.anchorElement.deepTextContent():"";return Boolean(s)&&e.test(s.trim())||e.test(t.deepTextContent().slice(s.length))}matchesFilterText(e){return this.contentElement().deepTextContent().toLowerCase().includes(e.toLowerCase())}updateTimestamp(){this.contentElementInternal&&(e.Settings.Settings.instance().moduleSetting("console-timestamps-enabled").get()?(this.timestampElement||(this.timestampElement=document.createElement("span"),this.timestampElement.classList.add("console-timestamp")),this.timestampElement.textContent=o.UIUtils.formatTimestamp(this.message.timestamp,!1)+" ",o.Tooltip.Tooltip.install(this.timestampElement,o.UIUtils.formatTimestamp(this.message.timestamp,!0)),this.contentElementInternal.insertBefore(this.timestampElement,this.contentElementInternal.firstChild)):this.timestampElement&&(this.timestampElement.remove(),this.timestampElement=null))}nestingLevel(){let e=0;for(let t=this.consoleGroup();null!==t;t=t.consoleGroup())e++;return e}setConsoleGroup(e){this.consoleGroupInternal=e}clearConsoleGroup(){this.consoleGroupInternal=null}consoleGroup(){return this.consoleGroupInternal}setInSimilarGroup(e,t){this.inSimilarGroup=e,this.lastInSimilarGroup=e&&Boolean(t),this.similarGroupMarker&&!e?(this.similarGroupMarker.remove(),this.similarGroupMarker=null):this.elementInternal&&!this.similarGroupMarker&&e&&(this.similarGroupMarker=document.createElement("div"),this.similarGroupMarker.classList.add("nesting-level-marker"),this.consoleRowWrapper?.insertBefore(this.similarGroupMarker,this.consoleRowWrapper.firstChild),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup))}isLastInSimilarGroup(){return Boolean(this.inSimilarGroup)&&Boolean(this.lastInSimilarGroup)}resetCloseGroupDecorationCount(){this.closeGroupDecorationCount&&(this.closeGroupDecorationCount=0,this.updateCloseGroupDecorations())}incrementCloseGroupDecorationCount(){++this.closeGroupDecorationCount,this.updateCloseGroupDecorations()}updateCloseGroupDecorations(){if(this.nestingLevelMarkers)for(let e=0,t=this.nestingLevelMarkers.length;ee.element.hasFocus())):-1}onKeyDown(e){!o.UIUtils.isEditing()&&this.elementInternal&&this.elementInternal.hasFocus()&&!this.elementInternal.hasSelection()&&this.maybeHandleOnKeyDown(e)&&e.consume(!0)}maybeHandleOnKeyDown(e){const t=this.focusedChildIndex(),s=-1===t;if(this.expandTrace&&s&&("ArrowLeft"===e.key&&this.traceExpanded||"ArrowRight"===e.key&&!this.traceExpanded))return this.expandTrace(!this.traceExpanded),!0;if(!this.selectableChildren.length)return!1;if("ArrowLeft"===e.key)return this.elementInternal&&this.elementInternal.focus(),!0;if("ArrowRight"===e.key&&s&&this.selectNearestVisibleChild(0))return!0;if("ArrowUp"===e.key){const e=this.nearestVisibleChild(0);if(this.selectableChildren[t]===e&&e)return this.elementInternal&&this.elementInternal.focus(),!0;if(this.selectNearestVisibleChild(t-1,!0))return!0}if("ArrowDown"===e.key){if(s&&this.selectNearestVisibleChild(0))return!0;if(!s&&this.selectNearestVisibleChild(t+1))return!0}return!1}selectNearestVisibleChild(e,t){const s=this.nearestVisibleChild(e,t);return!!s&&(s.forceSelect(),!0)}nearestVisibleChild(e,t){const s=this.selectableChildren.length;if(e<0||e>=s)return null;const n=t?-1:1;let o=e;for(;!this.selectableChildren[o].element.offsetParent;)if(o+=n,o<0||o>=s)return null;return this.selectableChildren[o]}focusLastChildOrSelf(){this.elementInternal&&!this.selectNearestVisibleChild(this.selectableChildren.length-1,!0)&&this.elementInternal.focus()}setContentElement(e){console.assert(!this.contentElementInternal,"Cannot set content element twice"),this.contentElementInternal=e}getContentElement(){return this.contentElementInternal}contentElement(){if(this.contentElementInternal)return this.contentElementInternal;const e=document.createElement("div");e.classList.add("console-message"),this.messageIcon&&e.appendChild(this.messageIcon),this.contentElementInternal=e;const t=this.message.runtimeModel();let s;const n=Boolean(this.message.stackTrace)&&("network"===this.message.source||"violation"===this.message.source||"error"===this.message.level||"warning"===this.message.level||"trace"===this.message.type);return s=t&&n?this.buildMessageWithStackTrace(t):this.buildMessageWithIgnoreLinks(),e.appendChild(s),this.updateTimestamp(),this.contentElementInternal}toMessageElement(){return this.elementInternal||(this.elementInternal=document.createElement("div"),this.elementInternal.tabIndex=-1,this.elementInternal.addEventListener("keydown",this.onKeyDown.bind(this)),this.updateMessageElement(),this.elementInternal.classList.toggle("console-adjacent-user-command-result",this.#e)),this.elementInternal}updateMessageElement(){if(this.elementInternal){this.elementInternal.className="console-message-wrapper",this.elementInternal.setAttribute("jslog",`${d.item("console-message").track({click:!0,keydown:"ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Enter|Space|Home|End"})}`),this.elementInternal.removeChildren(),this.consoleRowWrapper=this.elementInternal.createChild("div"),this.consoleRowWrapper.classList.add("console-row-wrapper"),this.message.isGroupStartMessage()&&this.elementInternal.classList.add("console-group-title"),this.message.source===e.Console.FrontendMessageSource.ConsoleAPI&&this.elementInternal.classList.add("console-from-api"),this.inSimilarGroup&&(this.similarGroupMarker=this.consoleRowWrapper.createChild("div","nesting-level-marker"),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup)),this.nestingLevelMarkers=[];for(let e=0;e1&&this.showRepeatCountElement()}}shouldShowInsights(){return(this.message.source!==e.Console.FrontendMessageSource.ConsoleAPI||""!==this.message.stackTrace?.callFrames[0]?.url)&&(""!==this.message.messageText&&this.message.source!==e.Console.FrontendMessageSource.SELF_XSS&&("error"===this.message.level||"warning"===this.message.level))}getExplainLabel(){return"error"===this.message.level?me(he.explainThisError):"warning"===this.message.level?me(he.explainThisWarning):me(he.explainThisMessage)}#i(){return"error"===this.message.level?me(he.explainThisErrorWithAI):"warning"===this.message.level?me(he.explainThisWarningWithAI):me(he.explainThisMessageWithAI)}getExplainActionId(){return"error"===this.message.level?"explain.console-message.context.error":"warning"===this.message.level?"explain.console-message.context.warning":"explain.console-message.context.other"}#o(){const e=new h.Icon.Icon;e.data={iconName:"lightbulb-spark",color:"var(--devtools-icon-color)",width:"16px",height:"16px"};const t=document.createElement("button");t.append(e),t.onclick=e=>{e.stopPropagation(),o.Context.Context.instance().setFlavor(xe,this);o.ActionRegistry.ActionRegistry.instance().getAction(be).execute()};const s=document.createElement("div");s.classList.add("button-label");const n=document.createElement("div");return n.innerText=this.getExplainLabel(),s.append(n),t.append(s),t.classList.add("hover-button"),t.ariaLabel=this.#i(),t.tabIndex=0,t.setAttribute("jslog",`${d.action(be).track({click:!0})}`),Ce.observe(t),t}shouldRenderAsWarning(){return!("verbose"!==this.message.level&&"info"!==this.message.level||"violation"!==this.message.source&&"deprecation"!==this.message.source&&"intervention"!==this.message.source&&"recommendation"!==this.message.source)}updateMessageIcon(){this.messageIcon&&(this.messageIcon.remove(),this.messageIcon=null);let e="",t="",s="";"warning"===this.message.level?(e="var(--icon-warning)",t="warning-filled",s=me(he.warning)):"error"===this.message.level?(e="var(--icon-error)",t="cross-circle-filled",s=me(he.error)):this.message.originatesFromLogpoint?(t="console-logpoint",s=me(he.logpoint)):this.message.originatesFromConditionalBreakpoint&&(t="console-conditional-breakpoint",s=me(he.cndBreakpoint)),t&&(this.messageIcon=new h.Icon.Icon,this.messageIcon.data={iconName:t,color:e,width:"14px",height:"14px"},this.messageIcon.classList.add("message-level-icon"),this.contentElementInternal&&this.contentElementInternal.insertBefore(this.messageIcon,this.contentElementInternal.firstChild),o.ARIAUtils.setLabel(this.messageIcon,s))}setAdjacentUserCommandResult(e){this.#e=e,this.elementInternal?.classList.toggle("console-adjacent-user-command-result",this.#e)}repeatCount(){return this.repeatCountInternal||1}resetIncrementRepeatCount(){this.repeatCountInternal=1,this.repeatCountElement&&(this.repeatCountElement.remove(),this.contentElementInternal&&this.contentElementInternal.classList.remove("repeated-message"),this.repeatCountElement=null)}incrementRepeatCount(){this.repeatCountInternal++,this.showRepeatCountElement()}setRepeatCount(e){this.repeatCountInternal=e,this.showRepeatCountElement()}showRepeatCountElement(){if(!this.elementInternal)return;if(!this.repeatCountElement){switch(this.repeatCountElement=document.createElement("dt-small-bubble"),this.repeatCountElement.classList.add("console-message-repeat-count"),this.message.level){case"warning":this.repeatCountElement.type="warning";break;case"error":this.repeatCountElement.type="error";break;case"verbose":this.repeatCountElement.type="verbose";break;default:this.repeatCountElement.type="info"}this.shouldRenderAsWarning()&&(this.repeatCountElement.type="warning"),this.consoleRowWrapper?.insertBefore(this.repeatCountElement,this.contentElementInternal),this.contentElement().classList.add("repeated-message")}let e;this.repeatCountElement.textContent=`${this.repeatCountInternal}`,e="warning"===this.message.level?me(he.warningS,{n:this.repeatCountInternal}):"error"===this.message.level?me(he.errorS,{n:this.repeatCountInternal}):me(he.repeatS,{n:this.repeatCountInternal}),o.ARIAUtils.setLabel(this.repeatCountElement,e)}get text(){return this.message.messageText}toExportString(){const e=[],t=this.contentElement().childTextNodes().map(u.Linkifier.Linkifier.untruncatedNodeText).join("");for(let s=0;se.uiSourceCodeForURL(t))).flat().filter((e=>!!e)).map((e=>i.scriptsForUISourceCode(e))).flat();if(r.length){const t=new n.DebuggerModel.Location(e,r[0].scriptId,s||0,o),a=await i.pluginManager.getFunctionInfo(r[0],t);return a&&"frames"in a?a:{frames:[]}}return{frames:[]}}async expandInlineStackFrames(e,t,s,n,o,i,r,a){const{frames:l}=await this.getInlineFrames(e,n,o,i);if(!l.length)return!1;for(let c=0;cu.focus()}),h.appendChild(u),h.appendChild(this.linkifyStringAsFragment(s)),h.classList.add("formatted-stack-frame"),r.insertBefore(h,a)}return!0}createScriptLocationLinkForSyntaxError(e,t){const{scriptId:s,lineNumber:n,columnNumber:o}=t;if(!s)return;const i=t.url||e.scriptForId(s)?.sourceURL;if(!i)return;const r=this.linkifier.linkifyScriptLocation(e.target(),t.scriptId||null,i,n,{columnNumber:o,inlineFrameIndex:0,showColumnNumber:!0});return r.tabIndex=-1,r}tryFormatAsError(e,t){const s=this.message.runtimeModel();if(!s)return null;const n=t?.exceptionMetaData?.issueSummary;"string"==typeof n&&(e=ve(e,n));const o=re(s,e);if(!o?.length)return null;t?.stackTrace&&le(o,t.stackTrace);const i=s.debuggerModel(),r=document.createElement("span");for(let e=0;eh.focus()}),c.appendChild(h),c.appendChild(this.linkifyStringAsFragment(d)),c.classList.add("formatted-stack-frame"),r.appendChild(c),!a.enclosedInBraces)continue;const u=a.prefix.substring(0,a.prefix.lastIndexOf(" ",a.prefix.length-3)),m=this.selectableChildren.length-1;this.expandInlineStackFrames(i,u,d,a.url,a.lineNumber,a.columnNumber,r,c).then((e=>{e&&(r.removeChild(c),this.selectableChildren.splice(m,1))}))}return r}linkifyWithCustomLinkifier(t,n){if(t.length>Re()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),t,Ae()),s=document.createDocumentFragment();return s.appendChild(e.element),s}const o=document.createDocumentFragment(),i=xe.tokenizeMessageText(t);let r=!1;for(const t of i)if(t.text)switch(r&&(t.text=`blob:${t.text}`,r=!r),"'blob:"===t.text&&t===i[0]&&(r=!0,t.text="'"),t.type){case"url":{const i=t.text.startsWith("www.")?"http://"+t.text:t.text,r=e.ParsedURL.ParsedURL.splitLineAndColumn(i),a=e.ParsedURL.ParsedURL.removeWasmFunctionInfoFromURL(r.url);let l;l=r?n(t.text,a,r.lineNumber,r.columnNumber):n(t.text,s.DevToolsPath.EmptyUrlString),o.appendChild(l);break}default:o.appendChild(document.createTextNode(t.text))}return o}linkifyStringAsFragment(e){return this.linkifyWithCustomLinkifier(e,((e,t,s,n)=>{const o={text:e,lineNumber:s,columnNumber:n},i=u.Linkifier.Linkifier.linkifyURL(t,o);return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}))}static tokenizeMessageText(e){const{tokenizerRegexes:t,tokenizerTypes:s}=Ie();if(e.length>Re())return[{text:e,type:void 0}];return i.TextUtils.Utils.splitStringByRegexes(e,t).map((e=>({text:e.value,type:s[e.regexIndex]})))}groupKey(){return this.groupKeyInternal||(this.groupKeyInternal=this.message.groupCategoryKey()+":"+this.groupTitle()),this.groupKeyInternal}groupTitle(){return xe.tokenizeMessageText(this.message.messageText).reduce(((e,t)=>{let s=t.text;return"url"===t.type?s=me(he.url):"time"===t.type?s=me(he.tookNms):"event"===t.type?s=me(he.someEvent):"milestone"===t.type?s=me(he.Mxx):"autofill"===t.type&&(s=me(he.attribute)),e+s}),"").replace(/[%]o/g,"")}}let we=null,Se=null;function Ie(){if(!we||!Se){const e="\\u0000-\\u0020\\u007f-\\u009f",t=new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s"+e+'"]{2,}[^\\s'+e+"\"')}\\],:;.!?]","u"),s=/(?:\/[\w\.-]*)+\:[\d]+/,n=/took [\d]+ms/,o=/'\w+' event/,i=/\sM[6-7]\d/,r=/\(suggested: \"[\w-]+\"\)/,a=new Map;return a.set(t,"url"),a.set(s,"url"),a.set(n,"time"),a.set(o,"event"),a.set(i,"milestone"),a.set(r,"autofill"),we=Array.from(a.keys()),Se=Array.from(a.values()),{tokenizerRegexes:we,tokenizerTypes:Se}}return{tokenizerRegexes:we,tokenizerTypes:Se}}class ye extends xe{collapsedInternal;expandGroupIcon;onToggle;groupEndMessageInternal;constructor(e,t,s,n,o,i){console.assert(e.isGroupStartMessage()),super(e,t,s,n,i),this.collapsedInternal="startGroupCollapsed"===e.type,this.expandGroupIcon=null,this.onToggle=o,this.groupEndMessageInternal=null}setCollapsed(e){this.collapsedInternal=e,this.expandGroupIcon&&(this.expandGroupIcon.name=this.collapsedInternal?"triangle-right":"triangle-down"),this.onToggle.call(null)}collapsed(){return this.collapsedInternal}maybeHandleOnKeyDown(e){return-1===this.focusedChildIndex()&&("ArrowLeft"===e.key&&!this.collapsedInternal||"ArrowRight"===e.key&&this.collapsedInternal)?(this.setCollapsed(!this.collapsedInternal),!0):super.maybeHandleOnKeyDown(e)}toMessageElement(){let e=this.elementInternal||null;if(!e){e=super.toMessageElement();const t=this.collapsedInternal?"triangle-right":"triangle-down";this.expandGroupIcon=h.Icon.create(t,"expand-group-icon"),this.contentElement().tabIndex=-1,this.repeatCountElement?this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild):this.consoleRowWrapper?.insertBefore(this.expandGroupIcon,this.contentElementInternal),e.addEventListener("click",(()=>this.setCollapsed(!this.collapsedInternal)))}return e}showRepeatCountElement(){super.showRepeatCountElement(),this.repeatCountElement&&this.expandGroupIcon&&this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild)}messagesHidden(){if(this.collapsed())return!0;const e=this.consoleGroup();return Boolean(e?.messagesHidden())}setGroupEnd(e){if("endGroup"!==e.consoleMessage().type)throw new Error("Invalid console message as group end");if(null!==this.groupEndMessageInternal)throw new Error("Console group already has an end");this.groupEndMessageInternal=e}groupEnd(){return this.groupEndMessageInternal}}class Me extends xe{formattedCommand;constructor(e,t,s,n,o){super(e,t,s,n,o),this.formattedCommand=null}contentElement(){const e=this.getContentElement();if(e)return e;const t=document.createElement("div");this.setContentElement(t),t.classList.add("console-user-command");const n=new h.Icon.Icon;return n.data={iconName:"chevron-right",color:"var(--icon-default)",width:"16px",height:"16px"},n.classList.add("command-result-icon"),t.appendChild(n),pe.set(t,this),this.formattedCommand=document.createElement("span"),this.formattedCommand.classList.add("source-code"),this.formattedCommand.textContent=s.StringUtilities.replaceControlCharacters(this.text),t.appendChild(this.formattedCommand),this.formattedCommand.textContent.lengthe===n?me(he.value):e.toString()));if(a.length&&(this.dataGrid=w.SortableDataGrid.SortableDataGrid.create(l,a,me(he.console)),this.dataGrid)){this.dataGrid.setStriped(!0),this.dataGrid.setFocusable(!1);const t=document.createElement("span");t.classList.add("console-message-text");const n=t.createChild("div","console-message-formatted-table"),o=n.createChild("span");n.appendChild(this.formatParameter(s,!0,!1));const i=o.attachShadow({mode:"open"}),r=this.dataGrid.asWidget();r.markAsRoot(),r.show(i),r.registerRequiredCSS(ie,N),e.appendChild(t),this.dataGrid.renderInline()}return e}approximateFastHeight(){const e=this.message.parameters?.[0];return e&&"string"!=typeof e&&e.preview?19*e.preview.properties.length:19}}const Te=1e4;let Le=1e4,Fe=5e3;const Re=()=>Le,Ae=()=>Fe;var Pe=Object.freeze({__proto__:null,ConsoleCommand:Me,ConsoleCommandResult:Ee,ConsoleGroupViewMessage:ye,ConsoleTableMessageView:ke,ConsoleViewMessage:xe,MaxLengthForLinks:40,concatErrorDescriptionAndIssueSummary:ve,getLongStringVisibleLength:Ae,getMaxTokenizableStringLength:Re,getMessageForElement:ge,setLongStringVisibleLength:e=>{Fe=e},setMaxTokenizableStringLength:e=>{Le=e}});class Ue{element;topGapElement;topGapElementActive;contentElementInternal;bottomGapElement;bottomGapElementActive;provider;virtualSelectedIndex;firstActiveIndex;lastActiveIndex;renderedItems;anchorSelection;headSelection;itemCount;cumulativeHeights;muteCopyHandler;observer;observerConfig;stickToBottomInternal;selectionIsBackward;lastSelectedElement;cachedProviderElements;constructor(e){this.element=document.createElement("div"),this.element.style.overflow="auto",this.topGapElement=this.element.createChild("div"),this.topGapElement.style.height="0px",this.topGapElement.style.color="transparent",this.topGapElementActive=!1,this.contentElementInternal=this.element.createChild("div"),this.bottomGapElement=this.element.createChild("div"),this.bottomGapElement.style.height="0px",this.bottomGapElement.style.color="transparent",this.bottomGapElementActive=!1,this.topGapElement.textContent="\ufeff",this.bottomGapElement.textContent="\ufeff",o.ARIAUtils.setHidden(this.topGapElement,!0),o.ARIAUtils.setHidden(this.bottomGapElement,!0),this.provider=e,this.element.addEventListener("scroll",this.onScroll.bind(this),!1),this.element.addEventListener("copy",this.onCopy.bind(this),!1),this.element.addEventListener("dragstart",this.onDragStart.bind(this),!1),this.contentElementInternal.addEventListener("focusin",this.onFocusIn.bind(this),!1),this.contentElementInternal.addEventListener("focusout",this.onFocusOut.bind(this),!1),this.contentElementInternal.addEventListener("keydown",this.onKeyDown.bind(this),!1),this.virtualSelectedIndex=-1,this.contentElementInternal.tabIndex=-1,this.firstActiveIndex=-1,this.lastActiveIndex=-1,this.renderedItems=[],this.anchorSelection=null,this.headSelection=null,this.itemCount=0,this.cumulativeHeights=new Int32Array(0),this.muteCopyHandler=!1,this.observer=new MutationObserver(this.refresh.bind(this)),this.observerConfig={childList:!0,subtree:!0},this.stickToBottomInternal=!1,this.selectionIsBackward=!1}stickToBottom(){return this.stickToBottomInternal}setStickToBottom(e){this.stickToBottomInternal=e,this.stickToBottomInternal?this.observer.observe(this.contentElementInternal,this.observerConfig):this.observer.disconnect()}hasVirtualSelection(){return-1!==this.virtualSelectedIndex}copyWithStyles(){this.muteCopyHandler=!0,this.element.ownerDocument.execCommand("copy"),this.muteCopyHandler=!1}onCopy(e){if(this.muteCopyHandler)return;const t=this.selectedText();t&&(e.preventDefault(),this.selectionContainsTable()?this.copyWithStyles():e.clipboardData&&e.clipboardData.setData("text/plain",t))}onFocusIn(e){const t=this.renderedItems.findIndex((t=>t.element().isSelfOrAncestor(e.target)));-1!==t&&(this.virtualSelectedIndex=this.firstActiveIndex+t);let s=!1;-1===this.virtualSelectedIndex&&this.isOutsideViewport(e.relatedTarget)&&e.target===this.contentElementInternal&&this.itemCount&&(s=!0,this.virtualSelectedIndex=this.itemCount-1,this.refresh(),this.scrollItemIntoView(this.virtualSelectedIndex)),this.updateFocusedItem(s)}onFocusOut(e){this.isOutsideViewport(e.relatedTarget)&&(this.virtualSelectedIndex=-1),this.updateFocusedItem()}isOutsideViewport(e){return null!==e&&!e.isSelfOrDescendant(this.contentElementInternal)}onDragStart(e){const t=this.selectedText();return!!t&&(e.dataTransfer&&(e.dataTransfer.clearData(),e.dataTransfer.setData("text/plain",t),e.dataTransfer.effectAllowed="copy"),!0)}onKeyDown(e){if(o.UIUtils.isEditing()||!this.itemCount||e.shiftKey)return;let t=!1;switch(e.key){case"ArrowUp":if(!(this.virtualSelectedIndex>0))return;t=!0,this.virtualSelectedIndex--;break;case"ArrowDown":if(!(this.virtualSelectedIndexthis.itemCount-1&&(this.virtualSelectedIndex=this.itemCount-1),this.rebuildCumulativeHeights(),this.refresh()}providerElement(e){this.cachedProviderElements||(this.cachedProviderElements=new Array(this.itemCount));let t=this.cachedProviderElements[e];return t||(t=this.provider.itemElement(e),this.cachedProviderElements[e]=t),t}rebuildCumulativeHeights(){const e=this.firstActiveIndex,t=this.lastActiveIndex;let s=0;this.cumulativeHeights=new Int32Array(this.itemCount);for(let n=0;n1)return void this.rebuildCumulativeHeights();if(t+=o,e+=n,Math.abs(e-t)>1)return void this.rebuildCumulativeHeights()}}cachedItemHeight(e){return 0===e?this.cumulativeHeights[0]:this.cumulativeHeights[e]-this.cumulativeHeights[e-1]}isSelectionBackwards(e){if(!e?.rangeCount||!e.anchorNode||!e.focusNode)return!1;const t=document.createRange();return t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.collapsed}createSelectionModel(e,t,s){return{item:e,node:t,offset:s}}updateSelectionModel(e){const t=e?.rangeCount?e.getRangeAt(0):null;if(!t||!e||e.isCollapsed||!this.element.hasSelection())return this.headSelection=null,this.anchorSelection=null,!1;let s=Number.MAX_VALUE,n=-1,o=!1;for(let e=0;ec.item?h:c):o?i?d=a?this.headSelection:this.anchorSelection:r&&(h=a?this.anchorSelection:this.headSelection):(d=l,h=c),a?(this.anchorSelection=h,this.headSelection=d):(this.anchorSelection=d,this.headSelection=h),this.selectionIsBackward=a,!0}restoreSelection(e){if(!e||!this.anchorSelection||!this.headSelection)return;const t=(e,t)=>{if(this.firstActiveIndex<=e.item&&e.item<=this.lastActiveIndex)return{element:e.node,offset:e.offset};return{element:e.item!t.has(e)));for(let e=0;e0&&(s[s.length-1]=s[s.length-1].substring(0,e))}const i=this.providerElement(e.item),r=i?.element();if(r&&e.node?.isSelfOrDescendant(r)){const t=this.textOffsetInNode(r,e.node,e.offset);s[0]=s[0].substring(t)}return s.join("\n")}textOffsetInNode(e,t,s){const n=t.textContent?t.textContent.length:0;t.nodeType!==Node.TEXT_NODE&&(s0&&r!==n&&(s=r),o+s}onScroll(e){this.refresh()}firstVisibleIndex(){return this.cumulativeHeights.length?(this.rebuildCumulativeHeightsIfNeeded(),s.ArrayUtilities.lowerBound(this.cumulativeHeights,this.element.scrollTop+1,s.ArrayUtilities.DEFAULT_COMPARATOR)):-1}lastVisibleIndex(){if(!this.cumulativeHeights.length)return-1;this.rebuildCumulativeHeightsIfNeeded();const e=this.element.scrollTop+this.element.clientHeight,t=this.itemCount-1;return s.ArrayUtilities.lowerBound(this.cumulativeHeights,e,s.ArrayUtilities.DEFAULT_COMPARATOR,void 0,t)}renderedElementAt(e){return-1===e||ethis.lastActiveIndex?null:this.renderedItems[e-this.firstActiveIndex].element()}scrollItemIntoView(e,t){const s=this.firstVisibleIndex(),n=this.lastVisibleIndex();e>s&&e=n&&this.forceScrollItemToBeLast(e))}forceScrollItemToBeFirst(e){console.assert(e>=0&&e0?this.cumulativeHeights[e-1]:0,o.UIUtils.isScrolledToBottom(this.element)&&this.setStickToBottom(!0),this.refresh();const t=this.renderedElementAt(e);t&&t.scrollIntoView(!0)}forceScrollItemToBeLast(e){console.assert(e>=0&&e{this.isSidebarOpen="Both"===e.data,this.isSidebarOpen&&(this.userHasOpenedSidebarAtLeastOnce||(m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleSidebarOpened),this.userHasOpenedSidebarAtLeastOnce=!0),this.pendingSidebarMessages.forEach((e=>{this.sidebar.onMessageAdded(e)})),this.pendingSidebarMessages=[]),this.filter.setLevelMenuOverridden(this.isSidebarOpen),this.onFilterChanged()})),this.contentsElement=this.searchableViewInternal.element,this.element.classList.add("console-view"),this.visibleViewMessages=[],this.hiddenByFilterCount=0,this.shouldBeHiddenCache=new Set,this.groupableMessages=new Map,this.groupableMessageTitle=new Map,this.shortcuts=new Map,this.regexMatchRanges=[],this.consoleContextSelector=new F,this.filterStatusText=new o.Toolbar.ToolbarText,this.filterStatusText.element.classList.add("dimmed"),this.showSettingsPaneSetting=e.Settings.Settings.instance().createSetting("console-show-settings-toolbar",!1),this.showSettingsPaneButton=new o.Toolbar.ToolbarSettingToggle(this.showSettingsPaneSetting,"gear",Oe(He.consoleSettings),"gear-filled"),this.showSettingsPaneButton.element.setAttribute("jslog",`${d.toggleSubpane("console-settings").track({click:!0})}`),this.progressToolbarItem=new o.Toolbar.ToolbarItem(document.createElement("div")),this.groupSimilarSetting=e.Settings.Settings.instance().moduleSetting("console-group-similar"),this.groupSimilarSetting.addChangeListener((()=>this.updateMessageList())),this.showCorsErrorsSetting=e.Settings.Settings.instance().moduleSetting("console-shows-cors-errors"),this.showCorsErrorsSetting.addChangeListener((()=>this.updateMessageList()));const s=this.consoleToolbarContainer.createChild("devtools-toolbar","console-main-toolbar");s.setAttribute("jslog",`${d.toolbar()}`),s.role="presentation",s.wrappable=!0,s.appendToolbarItem(this.splitWidget.createShowHideSidebarButton(Oe(He.showConsoleSidebar),Oe(He.hideConsoleSidebar),Oe(He.consoleSidebarShown),Oe(He.consoleSidebarHidden),"console-sidebar")),s.appendToolbarItem(o.Toolbar.Toolbar.createActionButton("console.clear")),s.appendSeparator(),s.appendToolbarItem(this.consoleContextSelector.toolbarItem()),s.appendSeparator(),s.appendSeparator(),s.appendToolbarItem(this.filter.textFilterUI),s.appendToolbarItem(this.filter.levelMenuButton),s.appendToolbarItem(this.progressToolbarItem),s.appendSeparator(),this.issueCounter=new C.IssueCounter.IssueCounter,this.issueCounter.id="console-issues-counter",this.issueCounter.setAttribute("jslog",`${d.counter("issues").track({click:!0})}`);const i=new o.Toolbar.ToolbarItem(this.issueCounter);this.issueCounter.data={clickHandler:()=>{m.userMetrics.issuesPanelOpenedFrom(2),o.ViewManager.ViewManager.instance().showView("issues-pane")},issuesManager:M.IssuesManager.IssuesManager.instance(),accessibleName:Oe(He.issueToolbarTooltipGeneral),displayMode:"OmitEmpty"},s.appendToolbarItem(i),s.appendSeparator(),s.appendToolbarItem(this.filterStatusText),s.appendToolbarItem(this.showSettingsPaneButton);const r=e.Settings.Settings.instance().moduleSetting("monitoring-xhr-enabled");this.timestampsSetting=e.Settings.Settings.instance().moduleSetting("console-timestamps-enabled"),this.consoleHistoryAutocompleteSetting=e.Settings.Settings.instance().moduleSetting("console-history-autocomplete"),this.selfXssWarningDisabledSetting=e.Settings.Settings.instance().createSetting("disable-self-xss-warning",!1,"Synced");const a=this.contentsElement.createChild("div","console-settings-pane");o.ARIAUtils.setLabel(a,Oe(He.consoleSettings)),o.ARIAUtils.markAsGroup(a);const l=e.Settings.Settings.instance().moduleSetting("preserve-console-log"),c=e.Settings.Settings.instance().moduleSetting("console-user-activation-eval");a.append(o.SettingsUI.createSettingCheckbox(Oe(He.hideNetwork),this.filter.hideNetworkMessagesSetting,this.filter.hideNetworkMessagesSetting.title()),o.SettingsUI.createSettingCheckbox(Oe(He.logXMLHttpRequests),r),o.SettingsUI.createSettingCheckbox(Oe(He.preserveLog),l,Oe(He.doNotClearLogOnPageReload)),o.SettingsUI.createSettingCheckbox(Oe(He.selectedContextOnly),this.filter.filterByExecutionContextSetting,Oe(He.onlyShowMessagesFromTheCurrentContext)),o.SettingsUI.createSettingCheckbox(this.consoleHistoryAutocompleteSetting.title(),this.consoleHistoryAutocompleteSetting,Oe(He.autocompleteFromHistory)),o.SettingsUI.createSettingCheckbox(this.groupSimilarSetting.title(),this.groupSimilarSetting,Oe(He.groupSimilarMessagesInConsole)),o.SettingsUI.createSettingCheckbox(c.title(),c,Oe(He.treatEvaluationAsUserActivation)),o.SettingsUI.createSettingCheckbox(this.showCorsErrorsSetting.title(),this.showCorsErrorsSetting,Oe(He.showCorsErrorsInConsole))),this.showSettingsPaneSetting.get()||a.classList.add("hidden"),this.showSettingsPaneSetting.addChangeListener((()=>a.classList.toggle("hidden",!this.showSettingsPaneSetting.get()))),this.viewport=new Ue(this),this.viewport.setStickToBottom(!0),this.viewport.contentElement().classList.add("console-group","console-group-messages"),this.contentsElement.appendChild(this.viewport.element),this.messagesElement=this.viewport.element,this.messagesElement.id="console-messages",this.messagesElement.classList.add("monospace"),this.messagesElement.addEventListener("click",this.messagesClicked.bind(this),!1),["paste","clipboard-paste","drop"].forEach((e=>{this.messagesElement.addEventListener(e,this.messagesPasted.bind(this),!0)})),this.messagesCountElement=this.consoleToolbarContainer.createChild("div","message-count"),o.ARIAUtils.markAsPoliteLiveRegion(this.messagesCountElement,!1),this.viewportThrottler=new e.Throttler.Throttler(t),this.pendingBatchResize=!1,this.onMessageResizedBound=e=>{this.onMessageResized(e)},this.promptElement=this.messagesElement.createChild("div","source-code"),this.promptElement.id="console-prompt";const h=this.messagesElement.createChild("div","console-view-fix-select-all");h.textContent=".",o.ARIAUtils.setHidden(h,!0),this.registerShortcuts(),this.messagesElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!1);const p=new e.Throttler.Throttler(100);this.linkifier=new u.Linkifier.Linkifier(40),this.linkifier.addEventListener("liveLocationUpdated",(()=>p.schedule((async()=>this.onFilterChanged())))),this.consoleMessages=[],this.consoleGroupStarts=[],this.prompt=new tt,this.prompt.show(this.promptElement),this.prompt.element.addEventListener("keydown",this.promptKeyDown.bind(this),!0),this.prompt.addEventListener("TextChanged",this.promptTextChanged,this),this.messagesElement.addEventListener("keydown",this.messagesKeyDown.bind(this),!1),this.prompt.element.addEventListener("focusin",(()=>{this.isScrolledToBottom()&&this.viewport.setStickToBottom(!0)})),this.consoleHistoryAutocompleteSetting.addChangeListener(this.consoleHistoryAutocompleteChanged,this),this.consoleHistoryAutocompleteChanged(),this.updateFilterStatus(),this.timestampsSetting.addChangeListener(this.consoleTimestampsSettingChanged,this),this.registerWithMessageSink(),o.Context.Context.instance().addFlavorChangeListener(n.RuntimeModel.ExecutionContext,this.executionContextChanged,this),this.messagesElement.addEventListener("mousedown",(e=>this.updateStickToBottomOnPointerDown(2===e.button)),!1),this.messagesElement.addEventListener("mouseup",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("mouseleave",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("wheel",this.updateStickToBottomOnWheel.bind(this),!1),this.messagesElement.addEventListener("touchstart",this.updateStickToBottomOnPointerDown.bind(this,!1),!1),this.messagesElement.addEventListener("touchend",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("touchcancel",this.updateStickToBottomOnPointerUp.bind(this),!1),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.ConsoleCleared,this.consoleCleared,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.MessageAdded,this.onConsoleMessageAdded,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.MessageUpdated,this.onConsoleMessageUpdated,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.CommandEvaluated,this.commandEvaluated,this,{scoped:!0}),n.TargetManager.TargetManager.instance().observeModels(n.ConsoleModel.ConsoleModel,this,{scoped:!0});const g=M.IssuesManager.IssuesManager.instance();this.issueToolbarThrottle=new e.Throttler.Throttler(100),g.addEventListener("IssuesCountUpdated",this.#a)}static instance(e){return Ve&&!e?.forceNew||(Ve=new Ne(e?.viewportThrottlerTimeout??50)),Ve}static clearConsole(){n.ConsoleModel.ConsoleModel.requestClearMessages()}#l(){this.issueToolbarThrottle.schedule((async()=>this.updateIssuesToolbarItem())),this.issuesCountUpdatedForTest()}issuesCountUpdatedForTest(){}modelAdded(e){e.messages().forEach(this.addConsoleMessage,this)}modelRemoved(t){e.Settings.Settings.instance().moduleSetting("preserve-console-log").get()||t.target().outermostTarget()!==t.target()||this.consoleCleared()}onFilterChanged(){if(this.filter.currentFilter.levelsMask=this.isSidebarOpen?P.allLevelsFilterValue():this.filter.messageLevelFiltersSetting.get(),this.cancelBuildHiddenCache(),this.immediatelyFilterMessagesForTest){for(const e of this.consoleMessages)this.computeShouldMessageBeVisible(e);this.updateMessageList()}else this.buildHiddenCache(0,this.consoleMessages.slice())}setImmediatelyFilterMessagesForTest(){this.immediatelyFilterMessagesForTest=!0}searchableView(){return this.searchableViewInternal}clearHistory(){this.prompt.history().clear()}consoleHistoryAutocompleteChanged(){this.prompt.setAddCompletionsFromHistory(this.consoleHistoryAutocompleteSetting.get())}itemCount(){return this.visibleViewMessages.length}itemElement(e){return this.visibleViewMessages[e]}fastHeight(e){return this.visibleViewMessages[e].fastHeight()}minimumRowHeight(){return 16}registerWithMessageSink(){e.Console.Console.instance().messages().forEach(this.addSinkMessage,this),e.Console.Console.instance().addEventListener("messageAdded",(({data:e})=>{this.addSinkMessage(e)}),this)}addSinkMessage(e){let t="verbose";switch(e.level){case"info":t="info";break;case"error":t="error";break;case"warning":t="warning"}const s=e.source||"other",o=new n.ConsoleModel.ConsoleMessage(null,s,t,e.text,{type:n.ConsoleModel.FrontendMessageType.System,timestamp:e.timestamp});this.addConsoleMessage(o)}consoleTimestampsSettingChanged(){this.updateMessageList(),this.consoleMessages.forEach((e=>e.updateTimestamp())),this.groupableMessageTitle.forEach((e=>e.updateTimestamp()))}executionContextChanged(){this.prompt.clearAutocomplete()}willHide(){this.hidePromptSuggestBox()}wasShown(){if(super.wasShown(),this.#r){M.IssuesManager.IssuesManager.instance().addEventListener("IssuesCountUpdated",this.#a)}this.#r=!1,this.updateIssuesToolbarItem(),this.viewport.refresh()}focus(){this.viewport.hasVirtualSelection()?this.viewport.contentElement().focus():this.focusPrompt()}focusPrompt(){if(!this.prompt.hasFocus()){const e=this.viewport.stickToBottom(),t=this.viewport.element.scrollTop;this.prompt.focus(),this.viewport.setStickToBottom(e),this.viewport.element.scrollTop=t}}restoreScrollPositions(){this.viewport.stickToBottom()?this.immediatelyScrollToBottom():super.restoreScrollPositions()}onResize(){this.scheduleViewportRefresh(),this.hidePromptSuggestBox(),this.viewport.stickToBottom()&&this.immediatelyScrollToBottom();for(let e=0;e0?this.consoleMessages.length:s.ArrayUtilities.upperBound(this.consoleMessages,t,l);const i=o=5&&!this.selfXssWarningDisabledSetting.get()&&this.selfXssWarningDisabledSetting.set(!0);else if(e.type!==n.ConsoleModel.FrontendMessageType.Result){const n=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,l)-1;if(n>=0){!function e(t,s){const n=s.groupEnd();if(null!==n&&l(t,n)>0){const n=s.consoleGroup();if(null===n)return;return void e(t,n)}"endGroup"===t.consoleMessage().type?s.setGroupEnd(t):t.setConsoleGroup(s)}(t,this.consoleGroupStarts[n])}e.isGroupStartMessage()&&(o=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,l),this.consoleGroupStarts.splice(o,0,t))}this.filter.onMessageAdded(e),this.isSidebarOpen?this.sidebar.onMessageAdded(t):this.pendingSidebarMessages.push(t);let r=!1;const a=this.groupSimilarSetting.get();if(e.isGroupable()){const e=t.groupKey();r=a&&this.groupableMessages.has(e);let s=this.groupableMessages.get(e);s||(s=[],this.groupableMessages.set(e,s)),s.push(t)}function l(e,t){return(De.get(e)||0)-(De.get(t)||0)}this.computeShouldMessageBeVisible(t),r||i?this.needsFullUpdate=!0:(this.appendMessageToEnd(t,!a),this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length)),this.scheduleViewportRefresh(),this.consoleMessageAddedForTest(t)}onConsoleMessageUpdated(e){const t=e.data,s=We.get(t);s&&(s.updateMessageElement(),this.computeShouldMessageBeVisible(s),this.updateMessageList())}consoleMessageAddedForTest(e){}shouldMessageBeVisible(e){return!this.shouldBeHiddenCache.has(e)}computeShouldMessageBeVisible(e){!this.filter.shouldBeVisible(e)||this.isSidebarOpen&&!this.sidebar.shouldBeVisible(e)?this.shouldBeHiddenCache.add(e):this.shouldBeHiddenCache.delete(e)}appendMessageToEnd(e,t){if("cors"===e.consoleMessage().category&&!this.showCorsErrorsSetting.get())return;const s=this.visibleViewMessages[this.visibleViewMessages.length-1];if("endGroup"===e.consoleMessage().type){if(s){const e=s.consoleGroup();e&&!e.messagesHidden()&&s.incrementCloseGroupDecorationCount()}return}if(!this.shouldMessageBeVisible(e))return void this.hiddenByFilterCount++;if(!t&&this.tryToCollapseMessages(e,this.visibleViewMessages[this.visibleViewMessages.length-1]))return;const n=e.consoleGroup();if(!n?.messagesHidden()){const t=e.consoleMessage().originatingMessage(),o=Boolean(t&&s?.consoleMessage()===t);e.setAdjacentUserCommandResult(o),function e(t,s){if(null===t)return;if(s.includes(t))return;const n=t.consoleGroup();n&&e(n,s);s.push(t)}(n,this.visibleViewMessages),this.visibleViewMessages.push(e),this.searchMessage(this.visibleViewMessages.length-1)}this.messageAppendedForTests()}messageAppendedForTests(){}createViewMessage(e){switch(e.type){case n.ConsoleModel.FrontendMessageType.Command:return new Me(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case n.ConsoleModel.FrontendMessageType.Result:return new Ee(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case"startGroupCollapsed":case"startGroup":return new ye(e,this.linkifier,this.requestResolver,this.issueResolver,this.updateMessageList.bind(this),this.onMessageResizedBound);case"table":return new ke(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);default:return new xe(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound)}}async onMessageResized(e){const t=e.data;if(this.pendingBatchResize||!t.treeOutline)return;this.pendingBatchResize=!0,await Promise.resolve();const s=t.treeOutline.element;this.viewport.setStickToBottom(this.isScrolledToBottom()),s.offsetHeight<=this.messagesElement.offsetHeight&&s.scrollIntoViewIfNeeded(),this.pendingBatchResize=!1}consoleCleared(){const e=this.viewport.element.hasFocus();this.cancelBuildHiddenCache(),this.currentMatchRangeIndex=-1,this.consoleMessages=[],this.groupableMessages.clear(),this.groupableMessageTitle.clear(),this.sidebar.clear(),this.pendingSidebarMessages=[],this.updateMessageList(),this.hidePromptSuggestBox(),this.viewport.setStickToBottom(!0),this.linkifier.reset(),this.filter.clear(),this.requestResolver.clear(),this.consoleGroupStarts=[],e&&this.prompt.focus(),o.ARIAUtils.alert(Oe(He.consoleCleared))}handleContextMenuEvent(t){const s=new o.ContextMenu.ContextMenu(t),i=t.target;if(i.isSelfOrDescendant(this.promptElement))return void s.show();const r=i.enclosingNodeOrSelfWithClass("console-message-wrapper"),a=r&&ge(r),l=a?a.consoleMessage():null;if(a&&o.Context.Context.instance().setFlavor(xe,a),l&&!a?.element()?.matches(".has-insight")&&a?.shouldShowInsights()&&s.headerSection().appendAction(a?.getExplainActionId(),void 0,!0),l&&l.url){const t=Oe(He.hideMessagesFromS,{PH1:new e.ParsedURL.ParsedURL(l.url).displayName});s.headerSection().appendItem(t,this.filter.addMessageURLFilter.bind(this.filter,l.url),{jslogContext:"hide-messages-from"})}if(s.defaultSection().appendAction("console.clear"),s.defaultSection().appendAction("console.clear.history"),s.saveSection().appendItem(Oe(He.copyConsole),this.copyConsole.bind(this),{jslogContext:"copy-console"}),s.saveSection().appendItem(Oe(He.saveAs),this.saveConsole.bind(this),{jslogContext:"save-as"}),this.element.hasSelection()&&s.clipboardSection().appendItem(Oe(He.copyVisibleStyledSelection),this.viewport.copyWithStyles.bind(this.viewport),{jslogContext:"copy-visible-styled-selection"}),l){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(l);e&&n.NetworkManager.NetworkManager.canReplayRequest(e)&&s.debugSection().appendItem(Oe(He.replayXhr),n.NetworkManager.NetworkManager.replayRequest.bind(null,e),{jslogContext:"replay-xhr"})}s.show()}async saveConsole(){const t=n.TargetManager.TargetManager.instance().scopeTarget().inspectedURL(),i=e.ParsedURL.ParsedURL.fromString(t),r=s.StringUtilities.sprintf("%s-%d.log",i?i.host:"console",Date.now()),a=new p.FileUtils.FileOutputStream,l=new o.ProgressIndicator.ProgressIndicator;l.setTitle(Oe(He.writingFile)),l.setTotalWork(this.itemCount());if(!await a.open(r))return;this.progressToolbarItem.element.appendChild(l.element);let c=0;for(;c12));++n);n!==t.length?this.buildHiddenCacheTimeout=this.element.window().requestAnimationFrame(this.buildHiddenCache.bind(this,n+1,t)):this.updateMessageList()}cancelBuildHiddenCache(){this.shouldBeHiddenCache.clear(),this.buildHiddenCacheTimeout&&(this.element.window().cancelAnimationFrame(this.buildHiddenCacheTimeout),delete this.buildHiddenCacheTimeout)}updateMessageList(){this.regexMatchRanges=[],this.hiddenByFilterCount=0;for(const e of this.visibleViewMessages)e.resetCloseGroupDecorationCount(),e.resetIncrementRepeatCount();if(this.visibleViewMessages=[],this.groupSimilarSetting.get())this.addGroupableMessagesToEnd();else for(const e of this.consoleMessages)e.setInSimilarGroup(!1),e.consoleMessage().isGroupable()&&e.clearConsoleGroup(),this.appendMessageToEnd(e,!0);this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length),this.viewport.invalidate(),this.messagesCountElement.setAttribute("aria-label",Oe(He.filteredMessagesInConsole,{PH1:this.visibleViewMessages.length}))}addGroupableMessagesToEnd(){const e=new Set,t=new Set;for(const s of this.consoleMessages){const o=s.consoleMessage();if(e.has(o))continue;if(!o.isGroupable()){this.appendMessageToEnd(s),e.add(o);continue}const i=s.groupKey(),r=this.groupableMessages.get(i);if(!r||r.length<5){s.setInSimilarGroup(!1),this.appendMessageToEnd(s),e.add(o);continue}if(t.has(i))continue;if(!r.find((e=>this.shouldMessageBeVisible(e)))){for(const t of r)e.add(t.consoleMessage());t.add(i);continue}let a=this.groupableMessageTitle.get(i);if(!a){const e=new n.ConsoleModel.ConsoleMessage(null,o.source,o.level,s.groupTitle(),{type:"startGroupCollapsed"});a=this.createViewMessage(e),this.groupableMessageTitle.set(i,a)}a.setRepeatCount(r.length),this.appendMessageToEnd(a);for(const t of r)t.setInSimilarGroup(!0,r[r.length-1]===t),t.setConsoleGroup(a),this.appendMessageToEnd(t,!0),e.add(t.consoleMessage());const l=new n.ConsoleModel.ConsoleMessage(null,o.source,o.level,o.messageText,{type:"endGroup"});this.appendMessageToEnd(this.createViewMessage(l))}}messagesClicked(e){const t=e.target;if(!this.messagesElement.hasSelection()){(t===this.messagesElement||this.prompt.belowEditorElement().isSelfOrAncestor(t))&&(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}}messagesKeyDown(e){const t=e;t.ctrlKey||t.altKey||t.metaKey||1!==t.key.length||o.UIUtils.isEditing()||this.messagesElement.hasSelection()||(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}messagesPasted(e){r.Runtime.Runtime.queryParam("isChromeForTesting")||r.Runtime.Runtime.queryParam("disableSelfXssWarnings")||this.selfXssWarningDisabledSetting.get()||(e.preventDefault(),this.prompt.showSelfXssWarning()),o.UIUtils.isEditing()||this.prompt.focus()}registerShortcuts(){this.shortcuts.set(o.KeyboardShortcut.KeyboardShortcut.makeKey("u",o.KeyboardShortcut.Modifiers.Ctrl.value),this.clearPromptBackwards.bind(this))}clearPromptBackwards(e){this.prompt.clear(),d.logKeyDown(e.currentTarget,e,"clear-prompt")}promptKeyDown(e){const t=e;if("PageUp"===t.key)return void this.updateStickToBottomOnWheel();const s=o.KeyboardShortcut.KeyboardShortcut.makeKeyFromEvent(t),n=this.shortcuts.get(s);n&&(n(t),t.preventDefault())}printResult(e,t,s){if(!e)return;const o=Boolean(s)?"error":"info";let i;i=s?n.ConsoleModel.ConsoleMessage.fromException(e.runtimeModel(),s,n.ConsoleModel.FrontendMessageType.Result,void 0,void 0):new n.ConsoleModel.ConsoleMessage(e.runtimeModel(),"javascript",o,"",{type:n.ConsoleModel.FrontendMessageType.Result,parameters:[e]}),i.setOriginatingMessage(t),e.runtimeModel().target().model(n.ConsoleModel.ConsoleModel)?.addMessage(i)}commandEvaluated(e){const{data:t}=e;this.printResult(t.result,t.commandMessage,t.exceptionDetails)}elementsToRestoreScrollPositionsFor(){return[this.messagesElement]}onSearchCanceled(){this.cleanupAfterSearch();for(const e of this.visibleViewMessages)e.setSearchRegex(null);this.currentMatchRangeIndex=-1,this.regexMatchRanges=[],this.searchRegex=null,this.viewport.refresh()}performSearch(e,t,s){this.onSearchCanceled(),this.searchableViewInternal.updateSearchMatchesCount(0),this.searchRegex=e.toSearchRegex(!0).regex,this.regexMatchRanges=[],this.currentMatchRangeIndex=-1,t&&(this.searchShouldJumpBackwards=Boolean(s)),this.searchProgressIndicator=new o.ProgressIndicator.ProgressIndicator,this.searchProgressIndicator.setTitle(Oe(He.searching)),this.searchProgressIndicator.setTotalWork(this.visibleViewMessages.length),this.progressToolbarItem.element.appendChild(this.searchProgressIndicator.element),this.innerSearch(0)}cleanupAfterSearch(){delete this.searchShouldJumpBackwards,this.innerSearchTimeoutId&&(clearTimeout(this.innerSearchTimeoutId),delete this.innerSearchTimeoutId),this.searchProgressIndicator&&(this.searchProgressIndicator.done(),delete this.searchProgressIndicator)}searchFinishedForTests(){}innerSearch(e){if(delete this.innerSearchTimeoutId,this.searchProgressIndicator?.isCanceled())return void this.cleanupAfterSearch();const t=Date.now();for(;e=0){t=this.regexMatchRanges[this.currentMatchRangeIndex];this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex).classList.remove(o.UIUtils.highlightedCurrentSearchResultClassName)}e=s.NumberUtilities.mod(e,this.regexMatchRanges.length),this.currentMatchRangeIndex=e,this.searchableViewInternal.updateCurrentMatchIndex(e),t=this.regexMatchRanges[e];const n=this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex);n.classList.add(o.UIUtils.highlightedCurrentSearchResultClassName),this.viewport.scrollItemIntoView(t.messageIndex),n.scrollIntoViewIfNeeded()}updateStickToBottomOnPointerDown(e){this.muteViewportUpdates=!e,this.viewport.setStickToBottom(!1),this.waitForScrollTimeout&&(clearTimeout(this.waitForScrollTimeout),delete this.waitForScrollTimeout)}updateStickToBottomOnPointerUp(){this.muteViewportUpdates&&(this.waitForScrollTimeout=window.setTimeout(function(){this.muteViewportUpdates=!1,this.isShowing()&&this.viewport.setStickToBottom(this.isScrolledToBottom());this.maybeDirtyWhileMuted&&(this.scheduleViewportRefresh(),delete this.maybeDirtyWhileMuted);delete this.waitForScrollTimeout,this.updateViewportStickinessForTest()}.bind(this),200))}updateViewportStickinessForTest(){}updateStickToBottomOnWheel(){this.updateStickToBottomOnPointerDown(),this.updateStickToBottomOnPointerUp()}promptTextChanged(){const e=this.viewport.stickToBottom(),t=this.isScrolledToBottom();this.viewport.setStickToBottom(t),t&&!e&&this.scheduleViewportRefresh(),this.promptTextChangedForTest()}promptTextChangedForTest(){}isScrolledToBottom(){return this.messagesElement.scrollHeight-this.messagesElement.scrollTop-this.messagesElement.clientHeight-this.prompt.belowEditorElement().offsetHeight<=2}}globalThis.Console=globalThis.Console||{},globalThis.Console.ConsoleView=Ne;class Ge{filterChanged;messageLevelFiltersSetting;hideNetworkMessagesSetting;filterByExecutionContextSetting;suggestionBuilder;textFilterUI;textFilterSetting;filterParser;currentFilter;levelLabels;levelMenuButton;constructor(t){this.filterChanged=t,this.messageLevelFiltersSetting=Ge.levelFilterSetting(),this.hideNetworkMessagesSetting=e.Settings.Settings.instance().moduleSetting("hide-network-messages"),this.filterByExecutionContextSetting=e.Settings.Settings.instance().moduleSetting("selected-context-filter-enabled"),this.messageLevelFiltersSetting.addChangeListener(this.onFilterChanged.bind(this)),this.hideNetworkMessagesSetting.addChangeListener(this.onFilterChanged.bind(this)),this.filterByExecutionContextSetting.addChangeListener(this.onFilterChanged.bind(this)),o.Context.Context.instance().addFlavorChangeListener(n.RuntimeModel.ExecutionContext,this.onFilterChanged,this);const s=Object.values(R);this.suggestionBuilder=new o.FilterSuggestionBuilder.FilterSuggestionBuilder(s),this.textFilterUI=new o.Toolbar.ToolbarFilter(void 0,1,1,Oe(He.egEventdCdnUrlacom),this.suggestionBuilder.completions.bind(this.suggestionBuilder),!0),this.textFilterSetting=e.Settings.Settings.instance().createSetting("console.text-filter",""),this.textFilterSetting.get()&&this.textFilterUI.setValue(this.textFilterSetting.get()),this.textFilterUI.addEventListener("TextChanged",(()=>{this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()})),this.filterParser=new i.TextUtils.FilterParser(s),this.currentFilter=new P("",[],null,this.messageLevelFiltersSetting.get()),this.updateCurrentFilter(),this.levelLabels=new Map([["verbose",Oe(He.verbose)],["info",Oe(He.info)],["warning",Oe(He.warnings)],["error",Oe(He.errors)]]),this.levelMenuButton=new o.Toolbar.ToolbarMenuButton(this.appendLevelMenuItems.bind(this),void 0,void 0,"log-level"),this.updateLevelMenuButtonText(),this.messageLevelFiltersSetting.addChangeListener(this.updateLevelMenuButtonText.bind(this))}onMessageAdded(e){e.type===n.ConsoleModel.FrontendMessageType.Command||e.type===n.ConsoleModel.FrontendMessageType.Result||e.isGroupMessage()||(e.context&&this.suggestionBuilder.addItem(R.Context,e.context),e.source&&this.suggestionBuilder.addItem(R.Source,e.source),e.url&&this.suggestionBuilder.addItem(R.Url,e.url))}setLevelMenuOverridden(e){this.levelMenuButton.setEnabled(!e),e?this.levelMenuButton.setTitle(Oe(He.overriddenByFilterSidebar)):this.updateLevelMenuButtonText()}static levelFilterSetting(){return e.Settings.Settings.instance().createSetting("message-level-filters",P.defaultLevelsFilterValue())}updateCurrentFilter(){const e=this.filterParser.parse(this.textFilterUI.value());for(const{key:t}of e)switch(t){case R.Context:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterByContext);break;case R.Source:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterBySource);break;case R.Url:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterByUrl)}this.hideNetworkMessagesSetting.get()&&e.push({key:R.Source,text:"network",negative:!0,regex:void 0}),this.currentFilter.executionContext=this.filterByExecutionContextSetting.get()?o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext):null,this.currentFilter.parsedFilters=e,this.currentFilter.levelsMask=this.messageLevelFiltersSetting.get()}onFilterChanged(){this.updateCurrentFilter(),this.filterChanged()}updateLevelMenuButtonText(){let e=!0,t=!0;const s=P.allLevelsFilterValue(),n=P.defaultLevelsFilterValue();let o=null;const i=this.messageLevelFiltersSetting.get(),r={Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"};for(const a of Object.values(r))e=e&&i[a]===s[a],t=t&&i[a]===n[a],i[a]&&(o=o?Oe(He.customLevels):Oe(He.sOnly,{PH1:String(this.levelLabels.get(a))}));o=e?Oe(He.allLevels):t?Oe(He.defaultLevels):o||Oe(He.hideAll),this.levelMenuButton.element.classList.toggle("warning",!e&&!t),this.levelMenuButton.setText(o),this.levelMenuButton.setTitle(Oe(He.logLevelS,{PH1:o}))}appendLevelMenuItems(e){const t=this.messageLevelFiltersSetting,s=t.get();e.headerSection().appendItem(Oe(He.default),(()=>t.set(P.defaultLevelsFilterValue())),{jslogContext:"default"});for(const[t,o]of this.levelLabels.entries())e.defaultSection().appendCheckboxItem(o,n.bind(null,t),{checked:s[t],jslogContext:t});function n(e){s[e]=!s[e],t.set(s)}}addMessageURLFilter(e){if(!e)return;const t=this.textFilterUI.value()?` ${this.textFilterUI.value()}`:"";this.textFilterUI.setValue(`-url:${e}${t}`),this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()}shouldBeVisible(e){return this.currentFilter.shouldBeVisible(e)}clear(){this.suggestionBuilder.clear()}reset(){this.messageLevelFiltersSetting.set(P.defaultLevelsFilterValue()),this.filterByExecutionContextSetting.set(!1),this.hideNetworkMessagesSetting.set(!1),this.textFilterUI.setValue(""),this.onFilterChanged()}}const De=new WeakMap,We=new WeakMap;var _e=Object.freeze({__proto__:null,ActionDelegate:class{handleAction(t,s){switch(s){case"console.toggle":return Ne.instance().hasFocus()&&o.InspectorView.InspectorView.instance().drawerVisible()?(o.InspectorView.InspectorView.instance().closeDrawer(),!0):(m.InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront(),e.Console.Console.instance().show(),Ne.instance().focusPrompt(),!0);case"console.clear":return Ne.clearConsole(),!0;case"console.clear.history":return Ne.instance().clearHistory(),!0}return!1}},ConsoleView:Ne,ConsoleViewFilter:Ge});let ze;class $e extends o.Panel.Panel{view;constructor(){super("console"),this.view=Ne.instance()}static instance(e={forceNew:null}){const{forceNew:t}=e;return ze&&!t||(ze=new $e),ze}static updateContextFlavor(){const e=$e.instance().view;o.Context.Context.instance().setFlavor(Ne,e.isShowing()?e:null)}wasShown(){super.wasShown();const e=qe;e?.isShowing()&&o.InspectorView.InspectorView.instance().setDrawerMinimized(!0),this.view.show(this.element),$e.updateContextFlavor()}willHide(){super.willHide(),o.InspectorView.InspectorView.instance().setDrawerMinimized(!1),qe&&qe.showViewInWrapper(),$e.updateContextFlavor()}searchableView(){return Ne.instance().searchableView()}}let qe=null;class Ke extends o.Widget.VBox{view;constructor(){super(),this.view=Ne.instance(),this.element.setAttribute("jslog",`${d.panel("console").track({resize:!0})}`)}static instance(){return qe||(qe=new Ke),qe}wasShown(){$e.instance().isShowing()?o.InspectorView.InspectorView.instance().setDrawerMinimized(!0):this.showViewInWrapper(),$e.updateContextFlavor()}willHide(){o.InspectorView.InspectorView.instance().setDrawerMinimized(!1),$e.updateContextFlavor()}showViewInWrapper(){this.view.show(this.element)}}var Je=Object.freeze({__proto__:null,ConsolePanel:$e,ConsoleRevealer:class{async reveal(e){const t=Ne.instance();t.isShowing()?t.focus():await o.ViewManager.ViewManager.instance().showView("console-view")}},WrapperView:Ke}),Xe={cssText:`#console-prompt .CodeMirror{padding:3px 0 1px}#console-prompt .CodeMirror-line{padding-top:0}#console-prompt .CodeMirror-lines{padding-top:0}#console-prompt .console-prompt-icon{position:absolute;left:-13px;top:2px;user-select:none}.console-eager-preview{padding-bottom:2px;opacity:60%;position:relative}.console-eager-inner-preview{text-overflow:ellipsis;overflow:hidden;margin-left:4px;height:100%;white-space:nowrap}.preview-result-icon{position:absolute;left:-13px;top:-1px}.console-eager-inner-preview:empty,\n.console-eager-inner-preview:empty + .preview-result-icon{opacity:0%}.console-prompt-icon.console-prompt-incomplete{opacity:65%}\n/*# sourceURL=${import.meta.resolve("./consolePrompt.css")} */\n`};const{Direction:Ze}=l.TextEditorHistory,Qe={consolePrompt:"Console prompt",selfXssWarning:"Warning: Don’t paste code into the DevTools Console that you don’t understand or haven’t reviewed yourself. This could allow attackers to steal your identity or take control of your computer. Please type ‘{PH1}’ below and hit Enter to allow pasting.",allowPasting:"allow pasting"},Ye=t.i18n.registerUIStrings("panels/console/ConsolePrompt.ts",Qe),et=t.i18n.getLocalizedString.bind(void 0,Ye);class tt extends(e.ObjectWrapper.eventMixin(o.Widget.Widget)){addCompletionsFromHistory;historyInternal;initialText;editor;eagerPreviewElement;textChangeThrottler;formatter;requestPreviewBound;requestPreviewCurrent=0;innerPreviewElement;promptIcon;iconThrottler;previewRequestForTest;highlightingNode;#c;#d;#h=!1;#u=new a.Compartment;#m(){return this.#h?[]:"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")?[a.javascript.javascript(),l.JavaScript.completion()]:[a.javascript.javascriptLanguage]}#p(){const e=this.#m(),t=this.#u.reconfigure(e);this.editor.dispatch({effects:t})}constructor(){super(),this.registerRequiredCSS(Xe),this.addCompletionsFromHistory=!0,this.historyInternal=new l.AutocompleteHistory.AutocompleteHistory(e.Settings.Settings.instance().createLocalSetting("console-history",[])),this.initialText="",this.eagerPreviewElement=document.createElement("div"),this.eagerPreviewElement.classList.add("console-eager-preview"),this.textChangeThrottler=new e.Throttler.Throttler(150),this.formatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.requestPreviewBound=this.requestPreview.bind(this),this.innerPreviewElement=this.eagerPreviewElement.createChild("div","console-eager-inner-preview");const t=new h.Icon.Icon;t.data={iconName:"chevron-left-dot",color:"var(--icon-default)",width:"16px",height:"16px"},t.classList.add("preview-result-icon"),this.eagerPreviewElement.appendChild(t);const s=this.element.createChild("div","console-prompt-editor-container");this.element.appendChild(this.eagerPreviewElement),this.promptIcon=new h.Icon.Icon,this.promptIcon.data={iconName:"chevron-right",color:"var(--icon-action)",width:"16px",height:"16px"},this.promptIcon.classList.add("console-prompt-icon"),this.element.appendChild(this.promptIcon),this.iconThrottler=new e.Throttler.Throttler(0),this.element.tabIndex=0,this.previewRequestForTest=null,this.highlightingNode=!1;const n=l.JavaScript.argumentHints();this.#c=n[0];const o=l.Config.DynamicSetting.bool("console-autocomplete-on-enter",[],l.Config.conservativeCompletion),i=[a.keymap.of(this.editorKeymap()),a.EditorView.updateListener.of((e=>this.editorUpdate(e))),n,o.instance(),l.Config.showCompletionHint,l.Config.baseConfiguration(this.initialText),l.Config.autocompletion.instance(),a.javascript.javascriptLanguage.data.of({autocomplete:e=>this.addCompletionsFromHistory?this.#d.historyCompletions(e):null}),a.EditorView.contentAttributes.of({"aria-label":et(Qe.consolePrompt)}),a.EditorView.lineWrapping,a.autocompletion({aboveCursor:!0}),this.#u.of(this.#m())],r=this.initialText,u=a.EditorState.create({doc:r,extensions:i});this.editor=new l.TextEditor.TextEditor(u),this.editor.addEventListener("keydown",(e=>{e.defaultPrevented&&e.stopPropagation()})),s.appendChild(this.editor),this.#d=new l.TextEditorHistory.TextEditorHistory(this.editor,this.historyInternal),this.hasFocus()&&this.focus(),this.element.removeAttribute("tabindex"),this.editorSetForTest(),m.userMetrics.panelLoaded("console","DevTools.Launch.Console"),this.element.setAttribute("jslog",`${d.textField("console-prompt").track({change:!0,keydown:"Enter|ArrowUp|ArrowDown|PageUp"})}`)}belowEditorElement(){return this.eagerPreviewElement}onTextChanged(){this.updatePromptIcon(),this.dispatchEventToListeners("TextChanged")}async requestPreview(){const e=++this.requestPreviewCurrent,t=l.Config.contentIncludingHint(this.editor.editor).trim(),s=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext),{preview:i,result:r}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(t,!0,!0,500);this.requestPreviewCurrent===e&&(this.innerPreviewElement.removeChildren(),i.deepTextContent()!==l.Config.contentIncludingHint(this.editor.editor).trim()&&this.innerPreviewElement.appendChild(i),r&&"object"in r&&r.object&&"node"===r.object.subtype?(this.highlightingNode=!0,n.OverlayModel.OverlayModel.highlightObjectAsDOMNode(r.object)):this.highlightingNode&&(this.highlightingNode=!1,n.OverlayModel.OverlayModel.hideDOMNodeHighlight()),r&&s&&s.runtimeModel.releaseEvaluationResult(r))}willHide(){super.willHide(),this.highlightingNode&&(this.highlightingNode=!1,n.OverlayModel.OverlayModel.hideDOMNodeHighlight())}history(){return this.historyInternal}clearAutocomplete(){a.closeCompletion(this.editor.editor)}isCaretAtEndOfPrompt(){return this.editor.state.selection.main.head===this.editor.state.doc.length}moveCaretToEndOfPrompt(){this.editor.dispatch({selection:a.EditorSelection.cursor(this.editor.state.doc.length)})}clear(){this.editor.dispatch({changes:{from:0,to:this.editor.state.doc.length}})}text(){return this.editor.state.doc.toString()}setAddCompletionsFromHistory(e){this.addCompletionsFromHistory=e}editorKeymap(){return[{key:"ArrowUp",run:()=>this.#d.moveHistory(-1)},{key:"ArrowDown",run:()=>this.#d.moveHistory(1)},{mac:"Ctrl-p",run:()=>this.#d.moveHistory(-1,!0)},{mac:"Ctrl-n",run:()=>this.#d.moveHistory(1,!0)},{key:"Escape",run:()=>l.JavaScript.closeArgumentsHintsTooltip(this.editor.editor,this.#c)},{key:"Ctrl-Enter",run:()=>(this.handleEnter(!0),!0)},{key:"Enter",run:()=>(this.handleEnter(),!0),shift:a.insertNewlineAndIndent}]}async enterWillEvaluate(e){const{doc:t,selection:s}=this.editor.state;if(!t.length)return!1;if(e||s.main.head{this.promptIcon.classList.toggle("console-prompt-incomplete",!await this.enterWillEvaluate())}))}appendCommand(e,t){const s=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext);if(s){const o=s,i=o.target().model(n.ConsoleModel.ConsoleModel);if(i){const s=i.addCommandMessage(o,e),n=c.JavaScriptREPL.JavaScriptREPL.wrapObjectLiteral(e);this.evaluateCommandInConsole(o,s,n,t),$e.instance().isShowing()&&m.userMetrics.actionTaken(m.UserMetrics.Action.CommandEvaluatedInConsolePanel)}}}async evaluateCommandInConsole(e,t,s,o){const i=e.debuggerModel.selectedCallFrame();if(i?.script.isJavaScript()){const e=await y.NamesResolver.allVariablesInCallFrame(i);s=await this.substituteNames(s,e)}await(e.target().model(n.ConsoleModel.ConsoleModel)?.evaluateCommandInConsole(e,t,s,o))}async substituteNames(e,t){try{return await I.FormatterWorkerPool.formatterWorkerPool().javaScriptSubstitute(e,t)}catch{return e}}editorUpdate(e){e.docChanged||a.selectedCompletion(e.state)!==a.selectedCompletion(e.startState)?this.onTextChanged():e.selectionSet&&this.updatePromptIcon()}focus(){this.editor.focus()}editorSetForTest(){}}var st=Object.freeze({__proto__:null,ConsolePrompt:tt});export{A as ConsoleContextSelector,U as ConsoleFilter,V as ConsoleFormat,Je as ConsolePanel,K as ConsolePinPane,st as ConsolePrompt,oe as ConsoleSidebar,_e as ConsoleView,Pe as ConsoleViewMessage,Be as ConsoleViewport,de as ErrorStackParser}; + `;this.pinElement=i.element(),this.pinPreview=i.$("preview");const r=i.$("name");o.Tooltip.Tooltip.install(r,t),z.set(this.pinElement,this),this.lastResult=null,this.lastExecutionContext=null,this.committedExpression=t,this.hovered=!1,this.lastNode=null,this.editor=this.createEditor(t,r),this.pinPreview.addEventListener("mouseenter",this.setHovered.bind(this,!0),!1),this.pinPreview.addEventListener("mouseleave",this.setHovered.bind(this,!1),!1),this.pinPreview.addEventListener("click",(t=>{this.lastNode&&(e.Revealer.reveal(this.lastNode),t.consume())}),!1),r.addEventListener("keydown",(e=>{"Escape"===e.key&&e.consume()}))}createEditor(e,t){const s=[a.EditorView.contentAttributes.of({"aria-label":_(D.liveExpressionEditor)}),a.EditorView.lineWrapping,a.javascript.javascriptLanguage,l.Config.showCompletionHint,a.placeholder(_(D.expression)),a.keymap.of([{key:"Escape",run:e=>(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)},{key:"Enter",run:()=>(this.focusOut(),!0)},{key:"Mod-Enter",run:()=>(this.focusOut(),!0)},{key:"Tab",run:e=>null===a.completionStatus(this.editor.state)&&(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)},{key:"Shift-Tab",run:e=>null===a.completionStatus(this.editor.state)&&(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)}]),a.EditorView.domEventHandlers({blur:(e,t)=>this.onBlur(t)}),l.Config.baseConfiguration(e),l.Config.closeBrackets.instance(),l.Config.autocompletion.instance()];"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")&&s.push(l.JavaScript.completion());const n=new l.TextEditor.TextEditor(a.EditorState.create({doc:e,extensions:s}));return t.appendChild(n),n}onBlur(e){const t=e.state.doc.toString(),s=t.trim();this.committedExpression=s,this.pinPane.savePins(),this.committedExpression.length?this.deletePinIcon.setAccessibleName(_(D.removeExpressionS,{PH1:this.committedExpression})):this.deletePinIcon.setAccessibleName(_(D.removeBlankExpression)),e.dispatch({selection:{anchor:s.length},changes:s!==t?{from:0,to:t.length,insert:s}:void 0})}setHovered(e){this.hovered!==e&&(this.hovered=e,!e&&this.lastNode&&n.OverlayModel.OverlayModel.hideDOMNodeHighlight())}expression(){return this.committedExpression}element(){return this.pinElement}async focus(){const e=this.editor;e.editor.focus(),e.dispatch({selection:{anchor:e.state.doc.length}})}appendToContextMenu(e){this.lastResult&&!("error"in this.lastResult)&&this.lastResult.object&&(e.appendApplicableItems(this.lastResult.object),this.lastResult=null)}async updatePreview(){if(!this.editor)return;const e=l.Config.contentIncludingHint(this.editor.editor),t=this.pinElement.hasFocus(),s=t&&e!==this.committedExpression,i=s?250:void 0,r=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext),{preview:a,result:d}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(e,s,!0,i,!t,"live-expression",!0,!0);this.lastResult&&this.lastExecutionContext&&this.lastExecutionContext.runtimeModel.releaseEvaluationResult(this.lastResult),this.lastResult=d||null,this.lastExecutionContext=r||null;const h=a.deepTextContent();if(!h||h!==this.pinPreview.deepTextContent()){if(this.pinPreview.removeChildren(),d&&n.RuntimeModel.RuntimeModel.isSideEffectFailure(d)){const e=this.pinPreview.createChild("span","object-value-calculate-value-button");e.textContent="(…)",o.Tooltip.Tooltip.install(e,_(D.evaluateAllowingSideEffects))}else h?this.pinPreview.appendChild(a):t||o.UIUtils.createTextChild(this.pinPreview,_(D.notAvailable));o.Tooltip.Tooltip.install(this.pinPreview,h)}let u=null;d&&!("error"in d)&&"object"===d.object.type&&"node"===d.object.subtype&&(u=d.object),this.hovered&&(u?n.OverlayModel.OverlayModel.highlightObjectAsDOMNode(u):this.lastNode&&n.OverlayModel.OverlayModel.hideDOMNodeHighlight()),this.lastNode=u||null;const m=d&&!("error"in d)&&d.exceptionDetails&&!n.RuntimeModel.RuntimeModel.isSideEffectFailure(d);this.pinElement.classList.toggle("error-level",Boolean(m))}}var K=Object.freeze({__proto__:null,ConsolePin:q,ConsolePinPane:$}),J={cssText:`:host{overflow:auto}.count{flex:none;margin:0 var(--sys-size-3)}devtools-icon{&[name="cross-circle"]{color:var(--sys-color-error-bright)}&[name="warning"]{color:var(--icon-warning)}&[name="info"]{color:var(--icon-info)}}.tree-element-title{flex-grow:1}\n/*# sourceURL=${import.meta.resolve("./consoleSidebar.css")} */\n`};const X={other:"",dUserMessages:"{n, plural, =0 {No user messages} =1 {# user message} other {# user messages}}",dMessages:"{n, plural, =0 {No messages} =1 {# message} other {# messages}}",dErrors:"{n, plural, =0 {No errors} =1 {# error} other {# errors}}",dWarnings:"{n, plural, =0 {No warnings} =1 {# warning} other {# warnings}}",dInfo:"{n, plural, =0 {No info} =1 {# info} other {# info}}",dVerbose:"{n, plural, =0 {No verbose} =1 {# verbose} other {# verbose}}"},Z=t.i18n.registerUIStrings("panels/console/ConsoleSidebar.ts",X),Q=t.i18n.getLocalizedString.bind(void 0,Z);class Y extends(e.ObjectWrapper.eventMixin(o.Widget.VBox)){tree;selectedTreeElement;treeElements;constructor(){super(!0),this.setMinimumSize(125,0),this.tree=new o.TreeOutline.TreeOutlineInShadow("NavigationTree"),this.tree.addEventListener(o.TreeOutline.Events.ElementSelected,this.selectionChanged.bind(this)),this.tree.registerRequiredCSS(J),this.tree.hideOverflow(),this.contentElement.setAttribute("jslog",`${d.pane("sidebar").track({resize:!0})}`),this.contentElement.appendChild(this.tree.element),this.selectedTreeElement=null,this.treeElements=[];const t=e.Settings.Settings.instance().createSetting("console.sidebar-selected-filter",null),s=[{key:R.Source,text:e.Console.FrontendMessageSource.ConsoleAPI,negative:!1,regex:void 0}];this.appendGroup("message",[],P.allLevelsFilterValue(),h.Icon.create("list"),t),this.appendGroup("user message",s,P.allLevelsFilterValue(),h.Icon.create("profile"),t),this.appendGroup("error",[],P.singleLevelMask("error"),h.Icon.create("cross-circle"),t),this.appendGroup("warning",[],P.singleLevelMask("warning"),h.Icon.create("warning"),t),this.appendGroup("info",[],P.singleLevelMask("info"),h.Icon.create("info"),t),this.appendGroup("verbose",[],P.singleLevelMask("verbose"),h.Icon.create("bug"),t);const n=t.get();(this.treeElements.find((e=>e.name()===n))||this.treeElements[0]).select()}appendGroup(e,t,s,n,o){const i=new P(e,t,null,s),r=new ne(i,n,o);this.tree.appendChild(r),this.treeElements.push(r)}clear(){for(const e of this.treeElements)e.clear()}onMessageAdded(e){for(const t of this.treeElements)t.onMessageAdded(e)}shouldBeVisible(e){return!(this.selectedTreeElement instanceof ee)||this.selectedTreeElement.filter().shouldBeVisible(e)}selectionChanged(e){this.selectedTreeElement=e.data,this.dispatchEventToListeners("FilterSelected")}}class ee extends o.TreeOutline.TreeElement{filterInternal;constructor(e,t){super(e),this.filterInternal=t}filter(){return this.filterInternal}}class te extends ee{countElement;messageCount;constructor(e){super(e.name,e),this.countElement=this.listItemElement.createChild("span","count");const t=h.Icon.create("document");this.setLeadingIcons([t]),this.messageCount=0}incrementAndUpdateCounter(){this.messageCount++,this.countElement.textContent=`${this.messageCount}`}}const se=new Map([["user message",X.dUserMessages],["message",X.dMessages],["error",X.dErrors],["warning",X.dWarnings],["info",X.dInfo],["verbose",X.dVerbose]]);class ne extends ee{selectedFilterSetting;urlTreeElements;messageCount;uiStringForFilterCount;constructor(e,t,s){super(e.name,e),this.uiStringForFilterCount=se.get(e.name)||"",this.selectedFilterSetting=s,this.urlTreeElements=new Map,this.setLeadingIcons([t]),this.messageCount=0,this.updateCounter()}clear(){this.urlTreeElements.clear(),this.removeChildren(),this.messageCount=0,this.updateCounter()}name(){return this.filterInternal.name}onselect(e){return this.selectedFilterSetting.set(this.filterInternal.name),super.onselect(e)}updateCounter(){this.title=this.updateGroupTitle(this.messageCount),this.setExpandable(Boolean(this.childCount()))}updateGroupTitle(e){return this.uiStringForFilterCount?Q(this.uiStringForFilterCount,{n:e}):""}onMessageAdded(e){const t=e.consoleMessage(),s=t.type!==n.ConsoleModel.FrontendMessageType.Command&&t.type!==n.ConsoleModel.FrontendMessageType.Result&&!t.isGroupMessage();if(!this.filterInternal.shouldBeVisible(e)||!s)return;this.childElement(t.url).incrementAndUpdateCounter(),this.messageCount++,this.updateCounter()}childElement(t){const s=t||null;let n=this.urlTreeElements.get(s);if(n)return n;const o=this.filterInternal.clone(),i=s?e.ParsedURL.ParsedURL.fromString(s):null;return o.name=s?i?i.displayName:s:Q(X.other),o.parsedFilters.push({key:R.Url,text:s,negative:!1,regex:void 0}),n=new te(o),s&&(n.tooltip=s),this.urlTreeElements.set(s,n),this.appendChild(n),n}}var oe=Object.freeze({__proto__:null,ConsoleSidebar:Y,FilterTreeElement:ne,URLGroupTreeElement:te}),ie={cssText:`.console-view{background-color:var(--sys-color-cdt-base-container);overflow:hidden;--override-error-text-color:var(--sys-color-on-error-container);--message-corner-rounder-background:var(--sys-color-cdt-base-container)}.console-toolbar-container{display:flex;flex:none}.console-main-toolbar{flex:1 1 auto}#console-issues-counter{margin-top:0}.console-toolbar-container > devtools-toolbar{background-color:var(--sys-color-cdt-base-container);border-bottom:1px solid var(--sys-color-divider)}.console-view-fix-select-all{height:0;overflow:hidden}.console-settings-pane{display:grid;grid-template-columns:50% 50%;flex:none;background-color:var(--sys-color-cdt-base-container);border-bottom:1px solid var(--sys-color-divider)}#console-messages{flex:1 1;overflow-y:auto;word-wrap:break-word;user-select:text;transform:translateZ(0);overflow-anchor:none;background-color:var(--sys-color-cdt-base-container)}#console-prompt{clear:right;position:relative;margin:0 22px 0 20px}.console-prompt-editor-container{min-height:21px}.console-message,\n.console-user-command{clear:right;position:relative;padding:3px 22px 1px 0;margin-left:24px;min-height:17px;flex:auto;display:flex}.console-message > *{flex:auto}.console-timestamp{color:var(--sys-color-token-subtle);user-select:none;flex:none;margin-right:5px}.message-level-icon,\n.command-result-icon{position:absolute;left:-17px;top:2px;user-select:none}.console-message-repeat-count{margin:1.4px 0 0 10px;flex:none}.repeated-message{margin-left:4px}.repeated-message .message-level-icon{display:none}.console-message-stack-trace-toggle{display:flex;flex-direction:row;align-items:flex-start;margin-top:-1px}.console-error-level .repeated-message,\n.console-warning-level .repeated-message,\n.console-verbose-level .repeated-message,\n.console-info-level .repeated-message{display:flex}.console-info{color:var(--sys-color-token-subtle);font-style:italic;padding-bottom:2px}.console-group .console-group > .console-group-messages{margin-left:16px}.console-group-title.console-from-api{font-weight:bold}.console-group-title .console-message{margin-left:12px}.expand-group-icon{user-select:none;flex:none;position:relative;left:8px;top:3px;margin-right:2px}.console-group-title .message-level-icon{display:none}.console-message-repeat-count .expand-group-icon{position:static;color:var(--sys-color-cdt-base-container);margin-left:-1px}.console-group{position:relative}.console-message-wrapper{display:flex;flex-direction:column;margin:4px;border-radius:5px;--console-color-black:#000;--console-color-red:#a00;--console-color-green:#0a0;--console-color-yellow:#a50;--console-color-blue:#00a;--console-color-magenta:#a0a;--console-color-cyan:#0aa;--console-color-gray:#aaa;--console-color-darkgray:#555;--console-color-lightred:#f55;--console-color-lightgreen:#5f5;--console-color-lightyellow:#ff5;--console-color-lightblue:#55f;--console-color-ightmagenta:#f5f;--console-color-lightcyan:#5ff;--console-color-white:#fff;&:focus{background-color:var(--sys-color-tonal-container);& ::selection{background-color:var(--sys-color-state-focus-select);color:currentcolor}}}.console-row-wrapper{display:flex;flex-direction:row}.theme-with-dark-background .console-message-wrapper{--console-color-red:rgb(237 78 76);--console-color-green:rgb(1 200 1);--console-color-yellow:rgb(210 192 87);--console-color-blue:rgb(39 116 240);--console-color-magenta:rgb(161 66 244);--console-color-cyan:rgb(18 181 203);--console-color-gray:rgb(207 208 208);--console-color-darkgray:rgb(137 137 137);--console-color-lightred:rgb(242 139 130);--console-color-lightgreen:rgb(161 247 181);--console-color-lightyellow:rgb(221 251 85);--console-color-lightblue:rgb(102 157 246);--console-color-lightmagenta:rgb(214 112 214);--console-color-lightcyan:rgb(132 240 255)}.console-message-wrapper.console-warning-level + .console-message-wrapper,\n.console-message-wrapper.console-error-level + .console-message-wrapper{& .console-message::before,\n & .console-user-command::before{display:none!important}}.console-message-wrapper:not(.console-error-level, .console-warning-level){& .console-message::before,\n & .console-user-command::before{width:calc(100% - 25px);content:"";display:block;position:absolute;top:-2px;border-top:1px solid var(--sys-color-divider)}&:first-of-type .console-message::before,\n &:first-of-type .console-user-command::before{display:none}}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level){border-top-width:0}.console-message-wrapper:focus + .console-message-wrapper{border-top-color:transparent}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus{border-top-width:1px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus .console-message{padding-top:2px;min-height:16px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level, .console-warning-level):focus .command-result-icon{top:3px}.console-message-wrapper .nesting-level-marker{width:14px;flex:0 0 auto;position:relative;margin-bottom:-1px;margin-top:-1px;background-color:var(--sys-color-cdt-base-container)}.console-message-wrapper .nesting-level-marker + .console-message::after{position:absolute;left:-30px;top:0;width:6px;height:100%;box-sizing:border-box;background-color:var(--sys-color-surface-yellow);border-top-left-radius:5px;border-bottom-left-radius:5px;content:""}.console-error-level{background-color:var(--sys-color-surface-error);--message-corner-rounder-background:var(--sys-color-surface-error)}.console-warning-level{background-color:var(--sys-color-surface-yellow);--message-corner-rounder-background:var(--sys-color-surface-yellow)}.console-view-object-properties-section{padding:0;position:relative;vertical-align:baseline;color:inherit;display:inline-block;overflow-wrap:break-word;max-width:100%}.info-note{background-color:var(--sys-color-tonal-container)}.info-note::before{content:"i"}.console-view-object-properties-section:not(.expanded) .info-note{display:none}.console-system-type.console-info-level{color:var(--sys-color-primary)}#console-messages .link{cursor:pointer;text-decoration:underline}#console-messages .link,\n#console-messages .devtools-link:not(.invalid-link){color:var(--sys-color-primary);word-break:break-all}#console-messages .devtools-link.ignore-list-link{opacity:60%}#console-messages .devtools-link:focus-visible{background-color:transparent}#console-messages .resource-links{margin-top:-1px;margin-bottom:-2px}.console-object-preview{white-space:normal;word-wrap:break-word;font-style:italic}.console-object-preview .name{flex-shrink:0}.console-message-text{.object-value-node{display:inline-block}.object-value-string,\n .object-value-regexp,\n .object-value-symbol{white-space:pre-wrap;word-break:break-all}.formatted-stack-frame:has(.ignore-list-link){display:var(--display-ignored-formatted-stack-frame);opacity:60%;& + .formatted-builtin-stack-frame{display:var(--display-ignored-formatted-stack-frame);opacity:60%}}}.console-message-stack-trace-wrapper{--override-display-stack-preview-toggle-link:none;flex:1 1 auto;display:flex;flex-direction:column;align-items:stretch;&:has(div > .stack-preview-container.show-hidden-rows){--display-ignored-formatted-stack-frame:inherit}&:has(.formatted-stack-frame .ignore-list-link):has(.formatted-stack-frame .devtools-link:not(.ignore-list-link)){--override-display-stack-preview-toggle-link:table-row;--override-display-stack-preview-hidden-div:block;&:not(:has(div > .stack-preview-container.show-hidden-rows)){--display-ignored-formatted-stack-frame:none}}& > .hidden-stack-trace{display:var(--override-display-stack-preview-hidden-div,none);--override-display-stack-preview-tbody:none}}.repeated-message .console-message-stack-trace-toggle,\n.repeated-message > .console-message-text{flex:1}.console-warning-level .console-message-text{color:var(--sys-color-on-surface-yellow)}.console-error-level .console-message-text,\n.console-error-level .console-view-object-properties-section{color:var(--override-error-text-color)!important}.console-message-formatted-table{clear:both}.console-message .source-code{line-height:1.2}.console-message-anchor{float:right;text-align:right;max-width:100%;margin-left:4px}.cookie-report-anchor{margin-top:-3px;margin-bottom:-5px}.console-message-nowrap-below,\n.console-message-nowrap-below div,\n.console-message-nowrap-below span{white-space:nowrap!important}.object-state-note{display:inline-block;width:11px;height:11px;color:var(--sys-color-on-tonal-container);text-align:center;border-radius:3px;line-height:13px;margin:0 6px;font-size:9px}.console-object{white-space:pre-wrap;word-break:break-all}.console-message-stack-trace-wrapper > *{flex:none}.console-message-expand-icon{margin-bottom:-4px}.console-searchable-view{max-height:100%}.console-view-pinpane{flex:none;max-height:50%}.message-count{width:0;height:0}devtools-console-insight{margin:9px 22px 11px 24px}.hover-button{--width:24px;align-items:center;border-radius:50%;border:none;box-shadow:0 1px 3px 1px rgb(0 0 0/15%),0 1px 2px 0 rgb(0 0 0/30%);box-sizing:border-box;background-color:var(--sys-color-tonal-container);color:var(--sys-color-on-tonal-container);font:var(--sys-typescale-body4-medium);height:var(--width);justify-content:center;margin:0;max-height:var(--width);max-width:var(--width);min-height:var(--width);min-width:var(--width);overflow:hidden;padding:var(--sys-size-3) var(--sys-size-4);position:absolute;right:6px;display:none;width:var(--width);z-index:1;.theme-with-dark-background &{border:1px solid var(--sys-color-neutral-outline);background-color:var(--sys-color-primary);color:var(--sys-color-on-primary)}& devtools-icon{box-sizing:border-box;flex-shrink:0;height:var(--sys-size-8);min-height:var(--sys-size-8);min-width:var(--sys-size-8);width:var(--sys-size-8);--devtools-icon-color:var(--sys-color-on-tonal-container)}.theme-with-dark-background & devtools-icon{--devtools-icon-color:var(--sys-color-on-primary)}}.hover-button:focus,\n.hover-button:hover{border-radius:4px;max-width:200px;transition:max-width var(--sys-motion-duration-short4) var(--sys-motion-easing-emphasized),border-radius 50ms linear;width:fit-content;gap:var(--sys-size-3)}.hover-button:focus-visible{outline:2px solid var(--sys-color-primary);outline-offset:2px}.button-label{display:block;overflow:hidden;white-space:nowrap;& div{display:inline-block;vertical-align:-1px}}.console-message-wrapper:not(.has-insight){&:hover,\n &:focus,\n &.console-selected{.hover-button{display:flex;&:focus,\n &:hover{display:inline-flex}}}}@media (forced-colors: active){.console-message-expand-icon,\n .console-warning-level .expand-group-icon{forced-color-adjust:none;color:ButtonText}.console-message-wrapper:focus,\n .console-message-wrapper:focus:last-of-type{forced-color-adjust:none;background-color:Highlight;border-top-color:Highlight;border-bottom-color:Highlight}.console-message-wrapper:focus *,\n .console-message-wrapper:focus:last-of-type *,\n .console-message-wrapper:focus .devtools-link,\n .console-message-wrapper:focus:last-of-type .devtools-link{color:HighlightText!important}#console-messages .devtools-link,\n #console-messages .devtools-link:hover{color:linktext}#console-messages .link:focus-visible,\n #console-messages .devtools-link:focus-visible{background:Highlight;color:HighlightText}.console-message-wrapper:focus devtools-icon{color:HighlightText}.console-message-wrapper.console-error-level:focus,\n .console-message-wrapper.console-error-level:focus:last-of-type{--override-error-text-color:HighlightText}}\n/*# sourceURL=${import.meta.resolve("./consoleView.css")} */\n`};function re({url:e}){return"native"===e?"native":""===e?"empty url":e.startsWith?.("address at ")?"address at":null}function ae(t,s){if(!/^[\w.]*Error\b/.test(s))return null;const n=t.debuggerModel(),o=t.target().inspectedURL(),i=s.split("\n"),r=[],a=new Set;for(const t of i){const i=/^\s*at\s(async\s)?/.exec(t);if(!i){if(r.length&&r[r.length-1].isCallFrame)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'"at (url)" not found'),null;r.push({line:t});continue}const l=!0;let c=i[0].length,d=t.length,h=!1;for(;")"===t[d-1];)for(d--,h=!0;;){if(c=t.indexOf(" (",c),c<0)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'left "(" not found'),null;if(c+=2,!t.substring(c).startsWith("eval at "))break;if(c+=8,d=t.lastIndexOf(", ",d)-1,d<0)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,'right "(" not found'),null}const u=t.substring(c,d),p=e.ParsedURL.ParsedURL.splitLineAndColumn(u),g=re(p);if(""===p.url||null!==g){r.length&&r[r.length-1].isCallFrame&&!r[r.length-1].link?r[r.length-1].line+=`\n${t}`:r.push({line:t,isCallFrame:l}),null!==g&&a.add(g);continue}let v=le(n,p.url);if(!v&&e.ParsedURL.ParsedURL.isRelativeURL(p.url)&&(v=le(n,e.ParsedURL.ParsedURL.completeURL(o,p.url))),!v)return m.rnPerfMetrics.stackTraceSymbolicationFailed(s,t,"url parsing failed"),null;r.push({line:t,isCallFrame:l,link:{url:v,prefix:t.substring(0,c),suffix:t.substring(d),enclosedInBraces:h,lineNumber:p.lineNumber,columnNumber:p.columnNumber}})}return r?.length&&m.rnPerfMetrics.stackTraceSymbolicationSucceeded(Array.from(a)),r}function le(t,s){if(!s)return null;if(e.ParsedURL.ParsedURL.isValidUrlString(s))return s;if(t.scriptsForSourceURL(s).length)return s;const n=new URL(s,"file://");return t.scriptsForSourceURL(n.href).length?n.href:null}function ce(e,t){for(const s of e){const e=t.callFrames.find((e=>de(s,e)));e&&s.link&&(s.link.scriptId=e.scriptId)}}function de(e,t){if(!e.link)return!1;const{url:s,lineNumber:n,columnNumber:o}=e.link;return s===t.url&&n===t.lineNumber&&o===t.columnNumber}var he=Object.freeze({__proto__:null,augmentErrorStackWithScriptIds:ce,parseSourcePositionsFromErrorStack:ae});const ue={consoleclearWasPreventedDueTo:"`console.clear()` was prevented due to 'Preserve log'",consoleWasCleared:"Console was cleared",clearAllMessagesWithS:"Clear all messages with {PH1}",assertionFailed:"Assertion failed: ",violationS:"`[Violation]` {PH1}",interventionS:"`[Intervention]` {PH1}",deprecationS:"`[Deprecation]` {PH1}",thisValueWillNotBeCollectedUntil:"This value will not be collected until console is cleared.",thisValueWasEvaluatedUponFirst:"This value was evaluated upon first expanding. It may have changed since then.",functionWasResolvedFromBound:"Function was resolved from bound function.",exception:"",warning:"Warning",error:"Error",logpoint:"Logpoint",cndBreakpoint:"Conditional Breakpoint",repeatS:"{n, plural, =1 {Repeated # time} other {Repeated # times}}",warningS:"{n, plural, =1 {Warning, Repeated # time} other {Warning, Repeated # times}}",errorS:"{n, plural, =1 {Error, Repeated # time} other {Error, Repeated # times}}",url:"",tookNms:"took ms",someEvent:" event",Mxx:" M",attribute:"",index:"(index)",value:"Value",console:"Console",stackMessageExpanded:"Stack table expanded",stackMessageCollapsed:"Stack table collapsed",explainThisError:"Understand this error",explainThisWarning:"Understand this warning",explainThisMessage:"Understand this message",explainThisErrorWithAI:"Understand this error. Powered by AI.",explainThisWarningWithAI:"Understand this warning. Powered by AI.",explainThisMessageWithAI:"Understand this message. Powered by AI",SeeIssueInCookieReport:"Click to open privacy and security panel and show third-party cookie report"},me=t.i18n.registerUIStrings("panels/console/ConsoleViewMessage.ts",ue),pe=t.i18n.getLocalizedString.bind(void 0,me),ge=new WeakMap,ve=e=>ge.get(e),fe=(e,t)=>{const s=e.indexOf("\n"),n=-1===s?e:e.substring(0,s),o=-1===s?"":e.substring(s);return e=`${n}. ${t}${o}`},be=e=>t=>t instanceof n.RemoteObject.RemoteObject?t:e?"object"==typeof t?e.createRemoteObject(t):e.createRemoteObjectFromPrimitiveValue(t):n.RemoteObject.RemoteObject.fromLocalObject(t),Ce="explain.console-message.hover",xe=new IntersectionObserver((e=>{for(const t of e)t.intersectionRatio>0&&m.userMetrics.actionTaken(m.UserMetrics.Action.InsightHoverButtonShown)}));class we{message;linkifier;repeatCountInternal;closeGroupDecorationCount;consoleGroupInternal;selectableChildren;messageResized;elementInternal;consoleRowWrapper=null;previewFormatter;searchRegexInternal;messageIcon;traceExpanded;expandTrace;anchorElement;contentElementInternal;nestingLevelMarkers;searchHighlightNodes;searchHighlightNodeChanges;isVisibleInternal;cachedHeight;messagePrefix;timestampElement;inSimilarGroup;similarGroupMarker;lastInSimilarGroup;groupKeyInternal;repeatCountElement;requestResolver;issueResolver;#e=!1;#t=Promise.resolve();constructor(e,t,s,n,o){this.message=e,this.linkifier=t,this.requestResolver=s,this.issueResolver=n,this.repeatCountInternal=1,this.closeGroupDecorationCount=0,this.selectableChildren=[],this.messageResized=o,this.elementInternal=null,this.previewFormatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.searchRegexInternal=null,this.messageIcon=null,this.traceExpanded=!1,this.expandTrace=null,this.anchorElement=null,this.contentElementInternal=null,this.nestingLevelMarkers=null,this.searchHighlightNodes=[],this.searchHighlightNodeChanges=[],this.isVisibleInternal=!1,this.cachedHeight=0,this.messagePrefix="",this.timestampElement=null,this.inSimilarGroup=!1,this.similarGroupMarker=null,this.lastInSimilarGroup=!1,this.groupKeyInternal="",this.repeatCountElement=null,this.consoleGroupInternal=null}setInsight(e){this.elementInternal?.querySelector("devtools-console-insight")?.remove(),this.elementInternal?.append(e),this.elementInternal?.classList.toggle("has-insight",!0),e.addEventListener("close",(()=>{m.userMetrics.actionTaken(m.UserMetrics.Action.InsightClosed),this.elementInternal?.classList.toggle("has-insight",!1),this.elementInternal?.removeChild(e)}),{once:!0})}element(){return this.toMessageElement()}wasShown(){this.isVisibleInternal=!0}onResize(){}willHide(){this.isVisibleInternal=!1,this.cachedHeight=this.element().offsetHeight}isVisible(){return this.isVisibleInternal}fastHeight(){return this.cachedHeight?this.cachedHeight:this.approximateFastHeight()}approximateFastHeight(){return 19}consoleMessage(){return this.message}formatErrorStackPromiseForTest(){return this.#t}buildMessage(){let t,s=this.message.messageText;if(this.message.source===e.Console.FrontendMessageSource.ConsoleAPI)switch(this.message.type){case"trace":t=this.format(this.message.parameters||["console.trace"]);break;case"clear":t=document.createElement("span"),t.classList.add("console-info"),e.Settings.Settings.instance().moduleSetting("preserve-console-log").get()?t.textContent=pe(ue.consoleclearWasPreventedDueTo):t.textContent=pe(ue.consoleWasCleared),o.Tooltip.Tooltip.install(t,pe(ue.clearAllMessagesWithS,{PH1:String(o.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction("console.clear"))}));break;case"dir":{const e=["%O",this.message.parameters?this.message.parameters[0]:void 0];t=this.format(e);break}case"profile":case"profileEnd":t=this.format([s]);break;default:{if("assert"===this.message.type&&(this.messagePrefix=pe(ue.assertionFailed)),this.message.parameters&&1===this.message.parameters.length){const e=this.message.parameters[0];"string"!=typeof e&&"string"===e.type&&(t=this.tryFormatAsError(e.value))}const e=this.message.parameters||[s];t=t||this.format(e)}}else if("network"===this.message.source)t=this.formatAsNetworkRequest()||this.format([s]);else{const e=this.message.parameters&&s===this.message.parameters[0];"violation"===this.message.source?s=pe(ue.violationS,{PH1:s}):"intervention"===this.message.source?s=pe(ue.interventionS,{PH1:s}):"deprecation"===this.message.source&&(s=pe(ue.deprecationS,{PH1:s}));const n=this.message.parameters||[s];e&&(n[0]=s),t=this.format(n)}t.classList.add("console-message-text");const n=document.createElement("span");if(n.classList.add("source-code"),this.anchorElement=this.buildMessageAnchor(),this.anchorElement&&n.appendChild(this.anchorElement),n.appendChild(t),"fusebox_preserve_log_rec"===this.message.context){const t=document.createElement("button");t.classList.add("devtools-link","text-button","link-style"),t.appendChild(t.ownerDocument.createTextNode("show settings")),t.addEventListener("click",(async()=>{await e.Revealer.reveal(e.Settings.Settings.instance().moduleSetting("preserve-console-log"))})),n.appendChild(t)}return n}formatAsNetworkRequest(){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(this.message);if(!e)return null;const t=document.createElement("span");if("error"===this.message.level){o.UIUtils.createTextChild(t,e.requestMethod+" ");const s=u.Linkifier.Linkifier.linkifyRevealable(e,e.url(),e.url(),void 0,void 0,"network-request");s.tabIndex=-1,this.selectableChildren.push({element:s,forceSelect:()=>s.focus()}),t.appendChild(s),e.failed&&o.UIUtils.createTextChildren(t," ",e.localizedFailDescription||""),0!==e.statusCode&&o.UIUtils.createTextChildren(t," ",String(e.statusCode));const n=e.getInferredStatusText();n&&o.UIUtils.createTextChildren(t," (",n,")")}else{const s=this.message.messageText,n=this.linkifyWithCustomLinkifier(s,((t,s,n,o)=>{const i=s===e.url()?u.Linkifier.Linkifier.linkifyRevealable(e,s,e.url(),void 0,void 0,"network-request"):u.Linkifier.Linkifier.linkifyURL(s,{text:t,lineNumber:n,columnNumber:o});return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}));t.appendChild(n)}return t}createAffectedResourceLinks(){const e=[],t=this.message.getAffectedResources()?.requestId;if(t){const s=new x.RequestLinkIcon.RequestLinkIcon;s.classList.add("resource-links"),s.data={affectedRequest:{requestId:t},requestResolver:this.requestResolver,displayURL:!1},e.push(s)}const s=this.message.getAffectedResources()?.issueId;if(s){const t=new C.IssueLinkIcon.IssueLinkIcon;t.classList.add("resource-links"),t.data={issueId:s,issueResolver:this.issueResolver},e.push(t)}return e}#s(t){const s=new f.Button.Button;s.data={size:"SMALL",variant:"icon",iconName:"cookie",jslogContext:"privacy",title:pe(ue.SeeIssueInCookieReport)},s.addEventListener("click",(()=>{e.Revealer.reveal(new S.CookieReportView.CookieReportView)})),t.appendChild(s)}#n(){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(this.message);if(e?.resourceType().isStyleSheet())return m.UserMetrics.Action.StyleSheetInitiatorLinkClicked}buildMessageAnchor(){const e=this.message.runtimeModel();if(!e)return null;if(this.message.isCookieReportIssue&&r.Runtime.hostConfig.devToolsPrivacyUI?.enabled){const e=document.createElement("span");return e.classList.add("console-message-anchor","cookie-report-anchor"),this.#s(e),o.UIUtils.createTextChild(e," "),e}const t=(({stackFrameWithBreakpoint:t,scriptId:n,stackTrace:o,url:i,line:r,column:a})=>{const l=this.#n();return t?this.linkifier.maybeLinkifyConsoleCallFrame(e.target(),t,{inlineFrameIndex:0,revealBreakpoint:!0,userMetric:l}):n?this.linkifier.linkifyScriptLocation(e.target(),n,i||s.DevToolsPath.EmptyUrlString,r,{columnNumber:a,inlineFrameIndex:0,userMetric:l}):o?.callFrames.length?this.linkifier.linkifyStackTraceTopFrame(e.target(),o):i&&"undefined"!==i?this.linkifier.linkifyScriptLocation(e.target(),null,i,r,{columnNumber:a,inlineFrameIndex:0,userMetric:l}):null})(this.message);if(t){t.tabIndex=-1,this.selectableChildren.push({element:t,forceSelect:()=>t.focus()});const e=document.createElement("span");e.classList.add("console-message-anchor"),e.appendChild(t);for(const t of this.createAffectedResourceLinks())o.UIUtils.createTextChild(e," "),e.append(t);return o.UIUtils.createTextChild(e," "),e}return null}buildMessageWithStackTrace(t){const s=h.Icon.create("triangle-right","console-message-expand-icon"),{stackTraceElement:n,contentElement:i,messageElement:r,clickableElement:a,toggleElement:l}=this.buildMessageHelper(t.target(),this.message.stackTrace,s);let c;this.expandTrace=e=>{e?c=window.setTimeout((()=>{m.userMetrics.actionTaken(m.UserMetrics.Action.TraceExpanded)}),300):clearTimeout(c),s.name=e?"triangle-down":"triangle-right",n.classList.toggle("hidden-stack-trace",!e);const t=pe(e?ue.stackMessageExpanded:ue.stackMessageCollapsed);o.ARIAUtils.setLabel(i,`${r.textContent} ${t}`),o.ARIAUtils.alert(t),o.ARIAUtils.setExpanded(a,e),this.traceExpanded=e};return a.addEventListener("click",(e=>{o.UIUtils.isEditing()||i.hasSelection()||(this.expandTrace&&this.expandTrace(n.classList.contains("hidden-stack-trace")),e.consume())}),!1),"trace"===this.message.type&&e.Settings.Settings.instance().moduleSetting("console-trace-expand").get()&&this.expandTrace(!0),l._expandStackTraceForTest=this.expandTrace.bind(this,!0),l}buildMessageWithIgnoreLinks(){const{toggleElement:e}=this.buildMessageHelper(null,void 0,null);return e}buildMessageHelper(e,t,s){const n=document.createElement("div");n.classList.add("console-message-stack-trace-toggle");const i=n.createChild("div","console-message-stack-trace-wrapper"),r=this.buildMessage(),a=i.createChild("div");o.ARIAUtils.setExpanded(a,!1),s&&a.appendChild(s),a.tabIndex=-1,a.appendChild(r);const l=i.createChild("div"),c=u.JSPresentationUtils.buildStackTracePreviewContents(e,this.linkifier,{stackTrace:t,tabStops:void 0,widthConstrained:!0});l.appendChild(c.element);for(const e of c.links)this.selectableChildren.push({element:e,forceSelect:()=>e.focus()});return l.classList.add("hidden-stack-trace"),o.ARIAUtils.setLabel(i,`${r.textContent} ${pe(ue.stackMessageCollapsed)}`),o.ARIAUtils.markAsGroup(l),{stackTraceElement:l,contentElement:i,messageElement:r,clickableElement:a,toggleElement:n}}format(e){const t=document.createElement("span");if(this.messagePrefix&&(t.createChild("span").textContent=this.messagePrefix),!e.length)return t;let s=e.map(be(this.message.runtimeModel()));const i="string"===n.RemoteObject.RemoteObject.type(s[0])&&(this.message.type!==n.ConsoleModel.FrontendMessageType.Result||"error"===this.message.level);i&&(s=this.formatWithSubstitutionString(s[0].description,s.slice(1),t),s.length&&o.UIUtils.createTextChild(t," "));for(let e=0;eAe()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),s,Pe());t.appendChild(e.element)}else o.UIUtils.createTextChild(t,s);return t.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),t}formatParameterAsTrustedType(e){const t=document.createElement("span"),s=document.createElement("span");return s.appendChild(this.formatParameterAsString(e)),s.classList.add("object-value-string"),o.UIUtils.createTextChild(t,`${e.className} `),t.appendChild(s),t}formatParameterAsObject(e,t){const s=document.createElement("span");if(s.classList.add("console-object"),t&&e.preview)s.classList.add("console-object-preview"),this.previewFormatter.appendObjectPreview(s,e.preview,!1),c.ObjectPropertiesSection.ObjectPropertiesSection.appendMemoryIcon(s,e);else if("function"===e.type){const t=s.createChild("span");c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(e,t,!1),s.classList.add("object-value-function")}else"trustedtype"===e.subtype?s.appendChild(this.formatParameterAsTrustedType(e)):o.UIUtils.createTextChild(s,e.description||"");if(!e.hasChildren||e.customPreview())return s;const i=s.createChild("span","object-state-note info-note");this.message.type===n.ConsoleModel.FrontendMessageType.QueryObjectResult?o.Tooltip.Tooltip.install(i,pe(ue.thisValueWillNotBeCollectedUntil)):o.Tooltip.Tooltip.install(i,pe(ue.thisValueWasEvaluatedUponFirst));const r=new c.ObjectPropertiesSection.ObjectPropertiesSection(e,s,this.linkifier);return r.element.classList.add("console-view-object-properties-section"),r.enableContextMenu(),r.setShowSelectionOnKeyboardFocus(!0,!0),this.selectableChildren.push(r),r.addEventListener(o.TreeOutline.Events.ElementAttached,this.messageResized),r.addEventListener(o.TreeOutline.Events.ElementExpanded,this.messageResized),r.addEventListener(o.TreeOutline.Events.ElementCollapsed,this.messageResized),r.element}formatParameterAsFunction(e,t){const s=document.createElement("span");return n.RemoteObject.RemoteFunction.objectAsFunction(e).targetFunction().then(function(n){const i=document.createElement("span"),r=c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(n,i,!0,t);if(s.appendChild(i),n!==e){const e=s.createChild("span","object-state-note info-note");o.Tooltip.Tooltip.install(e,pe(ue.functionWasResolvedFromBound))}s.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),r.then((()=>this.formattedParameterAsFunctionForTest()))}.bind(this)),s}formattedParameterAsFunctionForTest(){}contextMenuEventFired(e,t){const s=new o.ContextMenu.ContextMenu(t);s.appendApplicableItems(e),s.show()}renderPropertyPreviewOrAccessor(e,t,s){return"accessor"===t.type?this.formatAsAccessorProperty(e,s.map((e=>e.name.toString())),!1):this.previewFormatter.renderPropertyPreview(t.type,"subtype"in t?t.subtype:void 0,null,t.value)}formatParameterAsNode(e){const t=document.createElement("span"),s=e.runtimeModel().target().model(n.DOMModel.DOMModel);return s?(s.pushObjectAsNodeToFrontend(e).then((async s=>{if(!s)return void t.appendChild(this.formatParameterAsObject(e,!1));const n=await o.UIUtils.Renderer.render(s);n?(n.tree&&(this.selectableChildren.push(n.tree),n.tree.addEventListener(o.TreeOutline.Events.ElementAttached,this.messageResized),n.tree.addEventListener(o.TreeOutline.Events.ElementExpanded,this.messageResized),n.tree.addEventListener(o.TreeOutline.Events.ElementCollapsed,this.messageResized)),t.appendChild(n.node)):t.appendChild(this.formatParameterAsObject(e,!1)),this.formattedParameterAsNodeForTest()})),t):t}formattedParameterAsNodeForTest(){}formatParameterAsString(e){const t=e.description??"",n=s.StringUtilities.formatAsJSLiteral(t),o=document.createElement("span");return o.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),o.appendChild(this.linkifyStringAsFragment(n)),o}formatParameterAsError(e){const t=document.createElement("span"),s=async(e,o=!1)=>{const i=n.RemoteObject.RemoteError.objectAsError(e),[r,a]=await Promise.all([i.exceptionDetails(),i.cause()]);let l=this.tryFormatAsError(i.errorStack,r);if(l||(l=document.createElement("span"),l.append(this.linkifyStringAsFragment(i.errorStack))),o){const e=document.createElement("div");e.append("Caused by: ",l),t.appendChild(e)}else t.appendChild(l);if(a&&"error"===a.subtype)await s(a,!0);else if(a&&"string"===a.type){const e=document.createElement("div");e.append(`Caused by: ${a.value}`),t.append(e)}};return this.#t=s(e),t}formatAsArrayEntry(e){return this.previewFormatter.renderPropertyPreview(e.type,e.subtype,e.className,e.description)}formatAsAccessorProperty(e,t,n){const i=c.ObjectPropertiesSection.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(e,t,function(e){const t=e.wasThrown,r=e.object;if(!r)return;if(i.removeChildren(),t){const e=i.createChild("span");e.textContent=pe(ue.exception),o.Tooltip.Tooltip.install(e,r.description)}else if(n)i.appendChild(this.formatAsArrayEntry(r));else{const e=100,t=r.type,n=r.subtype;let o="";"function"!==t&&r.description&&(o="string"===t||"regexp"===n||"trustedtype"===n?s.StringUtilities.trimMiddle(r.description,e):s.StringUtilities.trimEndWithMaxLength(r.description,e)),i.appendChild(this.previewFormatter.renderPropertyPreview(t,n,r.className,o))}}.bind(this));return i}formatWithSubstitutionString(e,t,s){const n=new Map,{tokens:o,args:i}=j(e,t);for(const e of o)switch(e.type){case"generic":s.append(this.formatParameter(e.value,!0,!1));break;case"optimal":s.append(this.formatParameter(e.value,!1,!0));break;case"string":if(0===n.size)s.append(this.linkifyStringAsFragment(e.value));else{const t=e.value.split("\n");for(let e=0;e0&&s.append(document.createElement("br"));const o=document.createElement("span");o.style.setProperty("contain","paint"),o.style.setProperty("display","inline-block"),o.style.setProperty("max-width","100%"),o.appendChild(this.linkifyStringAsFragment(t[e]));for(const[e,{value:t,priority:s}]of n)o.style.setProperty(e,t,s);s.append(o)}}break;case"style":O(n,e.value)}return i}matchesFilterRegex(e){e.lastIndex=0;const t=this.contentElement(),s=this.anchorElement?this.anchorElement.deepTextContent():"";return Boolean(s)&&e.test(s.trim())||e.test(t.deepTextContent().slice(s.length))}matchesFilterText(e){return this.contentElement().deepTextContent().toLowerCase().includes(e.toLowerCase())}updateTimestamp(){this.contentElementInternal&&(e.Settings.Settings.instance().moduleSetting("console-timestamps-enabled").get()?(this.timestampElement||(this.timestampElement=document.createElement("span"),this.timestampElement.classList.add("console-timestamp")),this.timestampElement.textContent=o.UIUtils.formatTimestamp(this.message.timestamp,!1)+" ",o.Tooltip.Tooltip.install(this.timestampElement,o.UIUtils.formatTimestamp(this.message.timestamp,!0)),this.contentElementInternal.insertBefore(this.timestampElement,this.contentElementInternal.firstChild)):this.timestampElement&&(this.timestampElement.remove(),this.timestampElement=null))}nestingLevel(){let e=0;for(let t=this.consoleGroup();null!==t;t=t.consoleGroup())e++;return e}setConsoleGroup(e){this.consoleGroupInternal=e}clearConsoleGroup(){this.consoleGroupInternal=null}consoleGroup(){return this.consoleGroupInternal}setInSimilarGroup(e,t){this.inSimilarGroup=e,this.lastInSimilarGroup=e&&Boolean(t),this.similarGroupMarker&&!e?(this.similarGroupMarker.remove(),this.similarGroupMarker=null):this.elementInternal&&!this.similarGroupMarker&&e&&(this.similarGroupMarker=document.createElement("div"),this.similarGroupMarker.classList.add("nesting-level-marker"),this.consoleRowWrapper?.insertBefore(this.similarGroupMarker,this.consoleRowWrapper.firstChild),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup))}isLastInSimilarGroup(){return Boolean(this.inSimilarGroup)&&Boolean(this.lastInSimilarGroup)}resetCloseGroupDecorationCount(){this.closeGroupDecorationCount&&(this.closeGroupDecorationCount=0,this.updateCloseGroupDecorations())}incrementCloseGroupDecorationCount(){++this.closeGroupDecorationCount,this.updateCloseGroupDecorations()}updateCloseGroupDecorations(){if(this.nestingLevelMarkers)for(let e=0,t=this.nestingLevelMarkers.length;ee.element.hasFocus())):-1}onKeyDown(e){!o.UIUtils.isEditing()&&this.elementInternal&&this.elementInternal.hasFocus()&&!this.elementInternal.hasSelection()&&this.maybeHandleOnKeyDown(e)&&e.consume(!0)}maybeHandleOnKeyDown(e){const t=this.focusedChildIndex(),s=-1===t;if(this.expandTrace&&s&&("ArrowLeft"===e.key&&this.traceExpanded||"ArrowRight"===e.key&&!this.traceExpanded))return this.expandTrace(!this.traceExpanded),!0;if(!this.selectableChildren.length)return!1;if("ArrowLeft"===e.key)return this.elementInternal&&this.elementInternal.focus(),!0;if("ArrowRight"===e.key&&s&&this.selectNearestVisibleChild(0))return!0;if("ArrowUp"===e.key){const e=this.nearestVisibleChild(0);if(this.selectableChildren[t]===e&&e)return this.elementInternal&&this.elementInternal.focus(),!0;if(this.selectNearestVisibleChild(t-1,!0))return!0}if("ArrowDown"===e.key){if(s&&this.selectNearestVisibleChild(0))return!0;if(!s&&this.selectNearestVisibleChild(t+1))return!0}return!1}selectNearestVisibleChild(e,t){const s=this.nearestVisibleChild(e,t);return!!s&&(s.forceSelect(),!0)}nearestVisibleChild(e,t){const s=this.selectableChildren.length;if(e<0||e>=s)return null;const n=t?-1:1;let o=e;for(;!this.selectableChildren[o].element.offsetParent;)if(o+=n,o<0||o>=s)return null;return this.selectableChildren[o]}focusLastChildOrSelf(){this.elementInternal&&!this.selectNearestVisibleChild(this.selectableChildren.length-1,!0)&&this.elementInternal.focus()}setContentElement(e){console.assert(!this.contentElementInternal,"Cannot set content element twice"),this.contentElementInternal=e}getContentElement(){return this.contentElementInternal}contentElement(){if(this.contentElementInternal)return this.contentElementInternal;const e=document.createElement("div");e.classList.add("console-message"),this.messageIcon&&e.appendChild(this.messageIcon),this.contentElementInternal=e;const t=this.message.runtimeModel();let s;const n=Boolean(this.message.stackTrace)&&("network"===this.message.source||"violation"===this.message.source||"error"===this.message.level||"warning"===this.message.level||"trace"===this.message.type);return s=t&&n?this.buildMessageWithStackTrace(t):this.buildMessageWithIgnoreLinks(),e.appendChild(s),this.updateTimestamp(),this.contentElementInternal}toMessageElement(){return this.elementInternal||(this.elementInternal=document.createElement("div"),this.elementInternal.tabIndex=-1,this.elementInternal.addEventListener("keydown",this.onKeyDown.bind(this)),this.updateMessageElement(),this.elementInternal.classList.toggle("console-adjacent-user-command-result",this.#e)),this.elementInternal}updateMessageElement(){if(this.elementInternal){this.elementInternal.className="console-message-wrapper",this.elementInternal.setAttribute("jslog",`${d.item("console-message").track({click:!0,keydown:"ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Enter|Space|Home|End"})}`),this.elementInternal.removeChildren(),this.consoleRowWrapper=this.elementInternal.createChild("div"),this.consoleRowWrapper.classList.add("console-row-wrapper"),this.message.isGroupStartMessage()&&this.elementInternal.classList.add("console-group-title"),this.message.source===e.Console.FrontendMessageSource.ConsoleAPI&&this.elementInternal.classList.add("console-from-api"),this.inSimilarGroup&&(this.similarGroupMarker=this.consoleRowWrapper.createChild("div","nesting-level-marker"),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup)),this.nestingLevelMarkers=[];for(let e=0;e1&&this.showRepeatCountElement()}}shouldShowInsights(){return(this.message.source!==e.Console.FrontendMessageSource.ConsoleAPI||""!==this.message.stackTrace?.callFrames[0]?.url)&&(""!==this.message.messageText&&this.message.source!==e.Console.FrontendMessageSource.SELF_XSS&&("error"===this.message.level||"warning"===this.message.level))}getExplainLabel(){return"error"===this.message.level?pe(ue.explainThisError):"warning"===this.message.level?pe(ue.explainThisWarning):pe(ue.explainThisMessage)}#i(){return"error"===this.message.level?pe(ue.explainThisErrorWithAI):"warning"===this.message.level?pe(ue.explainThisWarningWithAI):pe(ue.explainThisMessageWithAI)}getExplainActionId(){return"error"===this.message.level?"explain.console-message.context.error":"warning"===this.message.level?"explain.console-message.context.warning":"explain.console-message.context.other"}#o(){const e=new h.Icon.Icon;e.data={iconName:"lightbulb-spark",color:"var(--devtools-icon-color)",width:"16px",height:"16px"};const t=document.createElement("button");t.append(e),t.onclick=e=>{e.stopPropagation(),o.Context.Context.instance().setFlavor(we,this);o.ActionRegistry.ActionRegistry.instance().getAction(Ce).execute()};const s=document.createElement("div");s.classList.add("button-label");const n=document.createElement("div");return n.innerText=this.getExplainLabel(),s.append(n),t.append(s),t.classList.add("hover-button"),t.ariaLabel=this.#i(),t.tabIndex=0,t.setAttribute("jslog",`${d.action(Ce).track({click:!0})}`),xe.observe(t),t}shouldRenderAsWarning(){return!("verbose"!==this.message.level&&"info"!==this.message.level||"violation"!==this.message.source&&"deprecation"!==this.message.source&&"intervention"!==this.message.source&&"recommendation"!==this.message.source)}updateMessageIcon(){this.messageIcon&&(this.messageIcon.remove(),this.messageIcon=null);let e="",t="",s="";"warning"===this.message.level?(e="var(--icon-warning)",t="warning-filled",s=pe(ue.warning)):"error"===this.message.level?(e="var(--icon-error)",t="cross-circle-filled",s=pe(ue.error)):this.message.originatesFromLogpoint?(t="console-logpoint",s=pe(ue.logpoint)):this.message.originatesFromConditionalBreakpoint&&(t="console-conditional-breakpoint",s=pe(ue.cndBreakpoint)),t&&(this.messageIcon=new h.Icon.Icon,this.messageIcon.data={iconName:t,color:e,width:"14px",height:"14px"},this.messageIcon.classList.add("message-level-icon"),this.contentElementInternal&&this.contentElementInternal.insertBefore(this.messageIcon,this.contentElementInternal.firstChild),o.ARIAUtils.setLabel(this.messageIcon,s))}setAdjacentUserCommandResult(e){this.#e=e,this.elementInternal?.classList.toggle("console-adjacent-user-command-result",this.#e)}repeatCount(){return this.repeatCountInternal||1}resetIncrementRepeatCount(){this.repeatCountInternal=1,this.repeatCountElement&&(this.repeatCountElement.remove(),this.contentElementInternal&&this.contentElementInternal.classList.remove("repeated-message"),this.repeatCountElement=null)}incrementRepeatCount(){this.repeatCountInternal++,this.showRepeatCountElement()}setRepeatCount(e){this.repeatCountInternal=e,this.showRepeatCountElement()}showRepeatCountElement(){if(!this.elementInternal)return;if(!this.repeatCountElement){switch(this.repeatCountElement=document.createElement("dt-small-bubble"),this.repeatCountElement.classList.add("console-message-repeat-count"),this.message.level){case"warning":this.repeatCountElement.type="warning";break;case"error":this.repeatCountElement.type="error";break;case"verbose":this.repeatCountElement.type="verbose";break;default:this.repeatCountElement.type="info"}this.shouldRenderAsWarning()&&(this.repeatCountElement.type="warning"),this.consoleRowWrapper?.insertBefore(this.repeatCountElement,this.contentElementInternal),this.contentElement().classList.add("repeated-message")}let e;this.repeatCountElement.textContent=`${this.repeatCountInternal}`,e="warning"===this.message.level?pe(ue.warningS,{n:this.repeatCountInternal}):"error"===this.message.level?pe(ue.errorS,{n:this.repeatCountInternal}):pe(ue.repeatS,{n:this.repeatCountInternal}),o.ARIAUtils.setLabel(this.repeatCountElement,e)}get text(){return this.message.messageText}toExportString(){const e=[],t=this.contentElement().childTextNodes().map(u.Linkifier.Linkifier.untruncatedNodeText).join("");for(let s=0;se.uiSourceCodeForURL(t))).flat().filter((e=>!!e)).map((e=>i.scriptsForUISourceCode(e))).flat();if(r.length){const t=new n.DebuggerModel.Location(e,r[0].scriptId,s||0,o),a=await i.pluginManager.getFunctionInfo(r[0],t);return a&&"frames"in a?a:{frames:[]}}return{frames:[]}}async expandInlineStackFrames(e,t,s,n,o,i,r,a){const{frames:l}=await this.getInlineFrames(e,n,o,i);if(!l.length)return!1;for(let c=0;cu.focus()}),h.appendChild(u),h.appendChild(this.linkifyStringAsFragment(s)),h.classList.add("formatted-stack-frame"),r.insertBefore(h,a)}return!0}createScriptLocationLinkForSyntaxError(e,t){const{scriptId:s,lineNumber:n,columnNumber:o}=t;if(!s)return;const i=t.url||e.scriptForId(s)?.sourceURL;if(!i)return;const r=this.linkifier.linkifyScriptLocation(e.target(),t.scriptId||null,i,n,{columnNumber:o,inlineFrameIndex:0,showColumnNumber:!0});return r.tabIndex=-1,r}tryFormatAsError(e,t){const s=this.message.runtimeModel();if(!s)return null;const n=t?.exceptionMetaData?.issueSummary;"string"==typeof n&&(e=fe(e,n));const o=ae(s,e);if(!o?.length)return null;t?.stackTrace&&ce(o,t.stackTrace);const i=s.debuggerModel(),r=document.createElement("span");for(let e=0;eh.focus()}),c.appendChild(h),c.appendChild(this.linkifyStringAsFragment(d)),c.classList.add("formatted-stack-frame"),r.appendChild(c),!a.enclosedInBraces)continue;const u=a.prefix.substring(0,a.prefix.lastIndexOf(" ",a.prefix.length-3)),m=this.selectableChildren.length-1;this.expandInlineStackFrames(i,u,d,a.url,a.lineNumber,a.columnNumber,r,c).then((e=>{e&&(r.removeChild(c),this.selectableChildren.splice(m,1))}))}return r}linkifyWithCustomLinkifier(t,n){if(t.length>Ae()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),t,Pe()),s=document.createDocumentFragment();return s.appendChild(e.element),s}const o=document.createDocumentFragment(),i=we.tokenizeMessageText(t);let r=!1;for(const t of i)if(t.text)switch(r&&(t.text=`blob:${t.text}`,r=!r),"'blob:"===t.text&&t===i[0]&&(r=!0,t.text="'"),t.type){case"url":{const i=t.text.startsWith("www.")?"http://"+t.text:t.text,r=e.ParsedURL.ParsedURL.splitLineAndColumn(i),a=e.ParsedURL.ParsedURL.removeWasmFunctionInfoFromURL(r.url);let l;l=r?n(t.text,a,r.lineNumber,r.columnNumber):n(t.text,s.DevToolsPath.EmptyUrlString),o.appendChild(l);break}default:o.appendChild(document.createTextNode(t.text))}return o}linkifyStringAsFragment(e){return this.linkifyWithCustomLinkifier(e,((e,t,s,n)=>{const o={text:e,lineNumber:s,columnNumber:n},i=u.Linkifier.Linkifier.linkifyURL(t,o);return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}))}static tokenizeMessageText(e){const{tokenizerRegexes:t,tokenizerTypes:s}=ye();if(e.length>Ae())return[{text:e,type:void 0}];return i.TextUtils.Utils.splitStringByRegexes(e,t).map((e=>({text:e.value,type:s[e.regexIndex]})))}groupKey(){return this.groupKeyInternal||(this.groupKeyInternal=this.message.groupCategoryKey()+":"+this.groupTitle()),this.groupKeyInternal}groupTitle(){return we.tokenizeMessageText(this.message.messageText).reduce(((e,t)=>{let s=t.text;return"url"===t.type?s=pe(ue.url):"time"===t.type?s=pe(ue.tookNms):"event"===t.type?s=pe(ue.someEvent):"milestone"===t.type?s=pe(ue.Mxx):"autofill"===t.type&&(s=pe(ue.attribute)),e+s}),"").replace(/[%]o/g,"")}}let Se=null,Ie=null;function ye(){if(!Se||!Ie){const e="\\u0000-\\u0020\\u007f-\\u009f",t=new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s"+e+'"]{2,}[^\\s'+e+"\"')}\\],:;.!?]","u"),s=/(?:\/[\w\.-]*)+\:[\d]+/,n=/took [\d]+ms/,o=/'\w+' event/,i=/\sM[6-7]\d/,r=/\(suggested: \"[\w-]+\"\)/,a=new Map;return a.set(t,"url"),a.set(s,"url"),a.set(n,"time"),a.set(o,"event"),a.set(i,"milestone"),a.set(r,"autofill"),Se=Array.from(a.keys()),Ie=Array.from(a.values()),{tokenizerRegexes:Se,tokenizerTypes:Ie}}return{tokenizerRegexes:Se,tokenizerTypes:Ie}}class Me extends we{collapsedInternal;expandGroupIcon;onToggle;groupEndMessageInternal;constructor(e,t,s,n,o,i){console.assert(e.isGroupStartMessage()),super(e,t,s,n,i),this.collapsedInternal="startGroupCollapsed"===e.type,this.expandGroupIcon=null,this.onToggle=o,this.groupEndMessageInternal=null}setCollapsed(e){this.collapsedInternal=e,this.expandGroupIcon&&(this.expandGroupIcon.name=this.collapsedInternal?"triangle-right":"triangle-down"),this.onToggle.call(null)}collapsed(){return this.collapsedInternal}maybeHandleOnKeyDown(e){return-1===this.focusedChildIndex()&&("ArrowLeft"===e.key&&!this.collapsedInternal||"ArrowRight"===e.key&&this.collapsedInternal)?(this.setCollapsed(!this.collapsedInternal),!0):super.maybeHandleOnKeyDown(e)}toMessageElement(){let e=this.elementInternal||null;if(!e){e=super.toMessageElement();const t=this.collapsedInternal?"triangle-right":"triangle-down";this.expandGroupIcon=h.Icon.create(t,"expand-group-icon"),this.contentElement().tabIndex=-1,this.repeatCountElement?this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild):this.consoleRowWrapper?.insertBefore(this.expandGroupIcon,this.contentElementInternal),e.addEventListener("click",(()=>this.setCollapsed(!this.collapsedInternal)))}return e}showRepeatCountElement(){super.showRepeatCountElement(),this.repeatCountElement&&this.expandGroupIcon&&this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild)}messagesHidden(){if(this.collapsed())return!0;const e=this.consoleGroup();return Boolean(e?.messagesHidden())}setGroupEnd(e){if("endGroup"!==e.consoleMessage().type)throw new Error("Invalid console message as group end");if(null!==this.groupEndMessageInternal)throw new Error("Console group already has an end");this.groupEndMessageInternal=e}groupEnd(){return this.groupEndMessageInternal}}class Ee extends we{formattedCommand;constructor(e,t,s,n,o){super(e,t,s,n,o),this.formattedCommand=null}contentElement(){const e=this.getContentElement();if(e)return e;const t=document.createElement("div");this.setContentElement(t),t.classList.add("console-user-command");const n=new h.Icon.Icon;return n.data={iconName:"chevron-right",color:"var(--icon-default)",width:"16px",height:"16px"},n.classList.add("command-result-icon"),t.appendChild(n),ge.set(t,this),this.formattedCommand=document.createElement("span"),this.formattedCommand.classList.add("source-code"),this.formattedCommand.textContent=s.StringUtilities.replaceControlCharacters(this.text),t.appendChild(this.formattedCommand),this.formattedCommand.textContent.lengthe===n?pe(ue.value):e.toString()));if(a.length&&(this.dataGrid=w.SortableDataGrid.SortableDataGrid.create(l,a,pe(ue.console)),this.dataGrid)){this.dataGrid.setStriped(!0),this.dataGrid.setFocusable(!1);const t=document.createElement("span");t.classList.add("console-message-text");const n=t.createChild("div","console-message-formatted-table"),o=n.createChild("span");n.appendChild(this.formatParameter(s,!0,!1));const i=o.attachShadow({mode:"open"}),r=this.dataGrid.asWidget();r.markAsRoot(),r.show(i),r.registerRequiredCSS(ie,N),e.appendChild(t),this.dataGrid.renderInline()}return e}approximateFastHeight(){const e=this.message.parameters?.[0];return e&&"string"!=typeof e&&e.preview?19*e.preview.properties.length:19}}const Le=1e4;let Fe=1e4,Re=5e3;const Ae=()=>Fe,Pe=()=>Re;var Ue=Object.freeze({__proto__:null,ConsoleCommand:Ee,ConsoleCommandResult:ke,ConsoleGroupViewMessage:Me,ConsoleTableMessageView:Te,ConsoleViewMessage:we,MaxLengthForLinks:40,concatErrorDescriptionAndIssueSummary:fe,getLongStringVisibleLength:Pe,getMaxTokenizableStringLength:Ae,getMessageForElement:ve,setLongStringVisibleLength:e=>{Re=e},setMaxTokenizableStringLength:e=>{Fe=e}});class Be{element;topGapElement;topGapElementActive;contentElementInternal;bottomGapElement;bottomGapElementActive;provider;virtualSelectedIndex;firstActiveIndex;lastActiveIndex;renderedItems;anchorSelection;headSelection;itemCount;cumulativeHeights;muteCopyHandler;observer;observerConfig;stickToBottomInternal;selectionIsBackward;lastSelectedElement;cachedProviderElements;constructor(e){this.element=document.createElement("div"),this.element.style.overflow="auto",this.topGapElement=this.element.createChild("div"),this.topGapElement.style.height="0px",this.topGapElement.style.color="transparent",this.topGapElementActive=!1,this.contentElementInternal=this.element.createChild("div"),this.bottomGapElement=this.element.createChild("div"),this.bottomGapElement.style.height="0px",this.bottomGapElement.style.color="transparent",this.bottomGapElementActive=!1,this.topGapElement.textContent="\ufeff",this.bottomGapElement.textContent="\ufeff",o.ARIAUtils.setHidden(this.topGapElement,!0),o.ARIAUtils.setHidden(this.bottomGapElement,!0),this.provider=e,this.element.addEventListener("scroll",this.onScroll.bind(this),!1),this.element.addEventListener("copy",this.onCopy.bind(this),!1),this.element.addEventListener("dragstart",this.onDragStart.bind(this),!1),this.contentElementInternal.addEventListener("focusin",this.onFocusIn.bind(this),!1),this.contentElementInternal.addEventListener("focusout",this.onFocusOut.bind(this),!1),this.contentElementInternal.addEventListener("keydown",this.onKeyDown.bind(this),!1),this.virtualSelectedIndex=-1,this.contentElementInternal.tabIndex=-1,this.firstActiveIndex=-1,this.lastActiveIndex=-1,this.renderedItems=[],this.anchorSelection=null,this.headSelection=null,this.itemCount=0,this.cumulativeHeights=new Int32Array(0),this.muteCopyHandler=!1,this.observer=new MutationObserver(this.refresh.bind(this)),this.observerConfig={childList:!0,subtree:!0},this.stickToBottomInternal=!1,this.selectionIsBackward=!1}stickToBottom(){return this.stickToBottomInternal}setStickToBottom(e){this.stickToBottomInternal=e,this.stickToBottomInternal?this.observer.observe(this.contentElementInternal,this.observerConfig):this.observer.disconnect()}hasVirtualSelection(){return-1!==this.virtualSelectedIndex}copyWithStyles(){this.muteCopyHandler=!0,this.element.ownerDocument.execCommand("copy"),this.muteCopyHandler=!1}onCopy(e){if(this.muteCopyHandler)return;const t=this.selectedText();t&&(e.preventDefault(),this.selectionContainsTable()?this.copyWithStyles():e.clipboardData&&e.clipboardData.setData("text/plain",t))}onFocusIn(e){const t=this.renderedItems.findIndex((t=>t.element().isSelfOrAncestor(e.target)));-1!==t&&(this.virtualSelectedIndex=this.firstActiveIndex+t);let s=!1;-1===this.virtualSelectedIndex&&this.isOutsideViewport(e.relatedTarget)&&e.target===this.contentElementInternal&&this.itemCount&&(s=!0,this.virtualSelectedIndex=this.itemCount-1,this.refresh(),this.scrollItemIntoView(this.virtualSelectedIndex)),this.updateFocusedItem(s)}onFocusOut(e){this.isOutsideViewport(e.relatedTarget)&&(this.virtualSelectedIndex=-1),this.updateFocusedItem()}isOutsideViewport(e){return null!==e&&!e.isSelfOrDescendant(this.contentElementInternal)}onDragStart(e){const t=this.selectedText();return!!t&&(e.dataTransfer&&(e.dataTransfer.clearData(),e.dataTransfer.setData("text/plain",t),e.dataTransfer.effectAllowed="copy"),!0)}onKeyDown(e){if(o.UIUtils.isEditing()||!this.itemCount||e.shiftKey)return;let t=!1;switch(e.key){case"ArrowUp":if(!(this.virtualSelectedIndex>0))return;t=!0,this.virtualSelectedIndex--;break;case"ArrowDown":if(!(this.virtualSelectedIndexthis.itemCount-1&&(this.virtualSelectedIndex=this.itemCount-1),this.rebuildCumulativeHeights(),this.refresh()}providerElement(e){this.cachedProviderElements||(this.cachedProviderElements=new Array(this.itemCount));let t=this.cachedProviderElements[e];return t||(t=this.provider.itemElement(e),this.cachedProviderElements[e]=t),t}rebuildCumulativeHeights(){const e=this.firstActiveIndex,t=this.lastActiveIndex;let s=0;this.cumulativeHeights=new Int32Array(this.itemCount);for(let n=0;n1)return void this.rebuildCumulativeHeights();if(t+=o,e+=n,Math.abs(e-t)>1)return void this.rebuildCumulativeHeights()}}cachedItemHeight(e){return 0===e?this.cumulativeHeights[0]:this.cumulativeHeights[e]-this.cumulativeHeights[e-1]}isSelectionBackwards(e){if(!e?.rangeCount||!e.anchorNode||!e.focusNode)return!1;const t=document.createRange();return t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.collapsed}createSelectionModel(e,t,s){return{item:e,node:t,offset:s}}updateSelectionModel(e){const t=e?.rangeCount?e.getRangeAt(0):null;if(!t||!e||e.isCollapsed||!this.element.hasSelection())return this.headSelection=null,this.anchorSelection=null,!1;let s=Number.MAX_VALUE,n=-1,o=!1;for(let e=0;ec.item?h:c):o?i?d=a?this.headSelection:this.anchorSelection:r&&(h=a?this.anchorSelection:this.headSelection):(d=l,h=c),a?(this.anchorSelection=h,this.headSelection=d):(this.anchorSelection=d,this.headSelection=h),this.selectionIsBackward=a,!0}restoreSelection(e){if(!e||!this.anchorSelection||!this.headSelection)return;const t=(e,t)=>{if(this.firstActiveIndex<=e.item&&e.item<=this.lastActiveIndex)return{element:e.node,offset:e.offset};return{element:e.item!t.has(e)));for(let e=0;e0&&(s[s.length-1]=s[s.length-1].substring(0,e))}const i=this.providerElement(e.item),r=i?.element();if(r&&e.node?.isSelfOrDescendant(r)){const t=this.textOffsetInNode(r,e.node,e.offset);s[0]=s[0].substring(t)}return s.join("\n")}textOffsetInNode(e,t,s){const n=t.textContent?t.textContent.length:0;t.nodeType!==Node.TEXT_NODE&&(s0&&r!==n&&(s=r),o+s}onScroll(e){this.refresh()}firstVisibleIndex(){return this.cumulativeHeights.length?(this.rebuildCumulativeHeightsIfNeeded(),s.ArrayUtilities.lowerBound(this.cumulativeHeights,this.element.scrollTop+1,s.ArrayUtilities.DEFAULT_COMPARATOR)):-1}lastVisibleIndex(){if(!this.cumulativeHeights.length)return-1;this.rebuildCumulativeHeightsIfNeeded();const e=this.element.scrollTop+this.element.clientHeight,t=this.itemCount-1;return s.ArrayUtilities.lowerBound(this.cumulativeHeights,e,s.ArrayUtilities.DEFAULT_COMPARATOR,void 0,t)}renderedElementAt(e){return-1===e||ethis.lastActiveIndex?null:this.renderedItems[e-this.firstActiveIndex].element()}scrollItemIntoView(e,t){const s=this.firstVisibleIndex(),n=this.lastVisibleIndex();e>s&&e=n&&this.forceScrollItemToBeLast(e))}forceScrollItemToBeFirst(e){console.assert(e>=0&&e0?this.cumulativeHeights[e-1]:0,o.UIUtils.isScrolledToBottom(this.element)&&this.setStickToBottom(!0),this.refresh();const t=this.renderedElementAt(e);t&&t.scrollIntoView(!0)}forceScrollItemToBeLast(e){console.assert(e>=0&&e{this.isSidebarOpen="Both"===e.data,this.isSidebarOpen&&(this.userHasOpenedSidebarAtLeastOnce||(m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleSidebarOpened),this.userHasOpenedSidebarAtLeastOnce=!0),this.pendingSidebarMessages.forEach((e=>{this.sidebar.onMessageAdded(e)})),this.pendingSidebarMessages=[]),this.filter.setLevelMenuOverridden(this.isSidebarOpen),this.onFilterChanged()})),this.contentsElement=this.searchableViewInternal.element,this.element.classList.add("console-view"),this.visibleViewMessages=[],this.hiddenByFilterCount=0,this.shouldBeHiddenCache=new Set,this.groupableMessages=new Map,this.groupableMessageTitle=new Map,this.shortcuts=new Map,this.regexMatchRanges=[],this.consoleContextSelector=new F,this.filterStatusText=new o.Toolbar.ToolbarText,this.filterStatusText.element.classList.add("dimmed"),this.showSettingsPaneSetting=e.Settings.Settings.instance().createSetting("console-show-settings-toolbar",!1),this.showSettingsPaneButton=new o.Toolbar.ToolbarSettingToggle(this.showSettingsPaneSetting,"gear",Ve(je.consoleSettings),"gear-filled"),this.showSettingsPaneButton.element.setAttribute("jslog",`${d.toggleSubpane("console-settings").track({click:!0})}`),this.progressToolbarItem=new o.Toolbar.ToolbarItem(document.createElement("div")),this.groupSimilarSetting=e.Settings.Settings.instance().moduleSetting("console-group-similar"),this.groupSimilarSetting.addChangeListener((()=>this.updateMessageList())),this.showCorsErrorsSetting=e.Settings.Settings.instance().moduleSetting("console-shows-cors-errors"),this.showCorsErrorsSetting.addChangeListener((()=>this.updateMessageList()));const s=this.consoleToolbarContainer.createChild("devtools-toolbar","console-main-toolbar");s.setAttribute("jslog",`${d.toolbar()}`),s.role="presentation",s.wrappable=!0,s.appendToolbarItem(this.splitWidget.createShowHideSidebarButton(Ve(je.showConsoleSidebar),Ve(je.hideConsoleSidebar),Ve(je.consoleSidebarShown),Ve(je.consoleSidebarHidden),"console-sidebar")),s.appendToolbarItem(o.Toolbar.Toolbar.createActionButton("console.clear")),s.appendSeparator(),s.appendToolbarItem(this.consoleContextSelector.toolbarItem()),s.appendSeparator(),s.appendSeparator(),s.appendToolbarItem(this.filter.textFilterUI),s.appendToolbarItem(this.filter.levelMenuButton),s.appendToolbarItem(this.progressToolbarItem),s.appendSeparator(),this.issueCounter=new C.IssueCounter.IssueCounter,this.issueCounter.id="console-issues-counter",this.issueCounter.setAttribute("jslog",`${d.counter("issues").track({click:!0})}`);const i=new o.Toolbar.ToolbarItem(this.issueCounter);this.issueCounter.data={clickHandler:()=>{m.userMetrics.issuesPanelOpenedFrom(2),o.ViewManager.ViewManager.instance().showView("issues-pane")},issuesManager:M.IssuesManager.IssuesManager.instance(),accessibleName:Ve(je.issueToolbarTooltipGeneral),displayMode:"OmitEmpty"},s.appendToolbarItem(i),s.appendSeparator(),s.appendToolbarItem(this.filterStatusText),s.appendToolbarItem(this.showSettingsPaneButton);const r=e.Settings.Settings.instance().moduleSetting("monitoring-xhr-enabled");this.timestampsSetting=e.Settings.Settings.instance().moduleSetting("console-timestamps-enabled"),this.consoleHistoryAutocompleteSetting=e.Settings.Settings.instance().moduleSetting("console-history-autocomplete"),this.selfXssWarningDisabledSetting=e.Settings.Settings.instance().createSetting("disable-self-xss-warning",!1,"Synced");const a=this.contentsElement.createChild("div","console-settings-pane");o.ARIAUtils.setLabel(a,Ve(je.consoleSettings)),o.ARIAUtils.markAsGroup(a);const l=e.Settings.Settings.instance().moduleSetting("preserve-console-log"),c=e.Settings.Settings.instance().moduleSetting("console-user-activation-eval");a.append(o.SettingsUI.createSettingCheckbox(Ve(je.hideNetwork),this.filter.hideNetworkMessagesSetting,this.filter.hideNetworkMessagesSetting.title()),o.SettingsUI.createSettingCheckbox(Ve(je.logXMLHttpRequests),r),o.SettingsUI.createSettingCheckbox(Ve(je.preserveLog),l,Ve(je.doNotClearLogOnPageReload)),o.SettingsUI.createSettingCheckbox(Ve(je.selectedContextOnly),this.filter.filterByExecutionContextSetting,Ve(je.onlyShowMessagesFromTheCurrentContext)),o.SettingsUI.createSettingCheckbox(this.consoleHistoryAutocompleteSetting.title(),this.consoleHistoryAutocompleteSetting,Ve(je.autocompleteFromHistory)),o.SettingsUI.createSettingCheckbox(this.groupSimilarSetting.title(),this.groupSimilarSetting,Ve(je.groupSimilarMessagesInConsole)),o.SettingsUI.createSettingCheckbox(c.title(),c,Ve(je.treatEvaluationAsUserActivation)),o.SettingsUI.createSettingCheckbox(this.showCorsErrorsSetting.title(),this.showCorsErrorsSetting,Ve(je.showCorsErrorsInConsole))),this.showSettingsPaneSetting.get()||a.classList.add("hidden"),this.showSettingsPaneSetting.addChangeListener((()=>a.classList.toggle("hidden",!this.showSettingsPaneSetting.get()))),this.viewport=new Be(this),this.viewport.setStickToBottom(!0),this.viewport.contentElement().classList.add("console-group","console-group-messages"),this.contentsElement.appendChild(this.viewport.element),this.messagesElement=this.viewport.element,this.messagesElement.id="console-messages",this.messagesElement.classList.add("monospace"),this.messagesElement.addEventListener("click",this.messagesClicked.bind(this),!1),["paste","clipboard-paste","drop"].forEach((e=>{this.messagesElement.addEventListener(e,this.messagesPasted.bind(this),!0)})),this.messagesCountElement=this.consoleToolbarContainer.createChild("div","message-count"),o.ARIAUtils.markAsPoliteLiveRegion(this.messagesCountElement,!1),this.viewportThrottler=new e.Throttler.Throttler(t),this.pendingBatchResize=!1,this.onMessageResizedBound=e=>{this.onMessageResized(e)},this.promptElement=this.messagesElement.createChild("div","source-code"),this.promptElement.id="console-prompt";const h=this.messagesElement.createChild("div","console-view-fix-select-all");h.textContent=".",o.ARIAUtils.setHidden(h,!0),this.registerShortcuts(),this.messagesElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!1);const p=new e.Throttler.Throttler(100);this.linkifier=new u.Linkifier.Linkifier(40),this.linkifier.addEventListener("liveLocationUpdated",(()=>p.schedule((async()=>this.onFilterChanged())))),this.consoleMessages=[],this.consoleGroupStarts=[],this.prompt=new st,this.prompt.show(this.promptElement),this.prompt.element.addEventListener("keydown",this.promptKeyDown.bind(this),!0),this.prompt.addEventListener("TextChanged",this.promptTextChanged,this),this.messagesElement.addEventListener("keydown",this.messagesKeyDown.bind(this),!1),this.prompt.element.addEventListener("focusin",(()=>{this.isScrolledToBottom()&&this.viewport.setStickToBottom(!0)})),this.consoleHistoryAutocompleteSetting.addChangeListener(this.consoleHistoryAutocompleteChanged,this),this.consoleHistoryAutocompleteChanged(),this.updateFilterStatus(),this.timestampsSetting.addChangeListener(this.consoleTimestampsSettingChanged,this),this.registerWithMessageSink(),o.Context.Context.instance().addFlavorChangeListener(n.RuntimeModel.ExecutionContext,this.executionContextChanged,this),this.messagesElement.addEventListener("mousedown",(e=>this.updateStickToBottomOnPointerDown(2===e.button)),!1),this.messagesElement.addEventListener("mouseup",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("mouseleave",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("wheel",this.updateStickToBottomOnWheel.bind(this),!1),this.messagesElement.addEventListener("touchstart",this.updateStickToBottomOnPointerDown.bind(this,!1),!1),this.messagesElement.addEventListener("touchend",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("touchcancel",this.updateStickToBottomOnPointerUp.bind(this),!1),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.ConsoleCleared,this.consoleCleared,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.MessageAdded,this.onConsoleMessageAdded,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.MessageUpdated,this.onConsoleMessageUpdated,this,{scoped:!0}),n.TargetManager.TargetManager.instance().addModelListener(n.ConsoleModel.ConsoleModel,n.ConsoleModel.Events.CommandEvaluated,this.commandEvaluated,this,{scoped:!0}),n.TargetManager.TargetManager.instance().observeModels(n.ConsoleModel.ConsoleModel,this,{scoped:!0});const g=M.IssuesManager.IssuesManager.instance();this.issueToolbarThrottle=new e.Throttler.Throttler(100),g.addEventListener("IssuesCountUpdated",this.#a)}static instance(e){return Ne&&!e?.forceNew||(Ne=new Ge(e?.viewportThrottlerTimeout??50)),Ne}static clearConsole(){n.ConsoleModel.ConsoleModel.requestClearMessages()}#l(){this.issueToolbarThrottle.schedule((async()=>this.updateIssuesToolbarItem())),this.issuesCountUpdatedForTest()}issuesCountUpdatedForTest(){}modelAdded(e){e.messages().forEach(this.addConsoleMessage,this)}modelRemoved(t){e.Settings.Settings.instance().moduleSetting("preserve-console-log").get()||t.target().outermostTarget()!==t.target()||this.consoleCleared()}onFilterChanged(){if(this.filter.currentFilter.levelsMask=this.isSidebarOpen?P.allLevelsFilterValue():this.filter.messageLevelFiltersSetting.get(),this.cancelBuildHiddenCache(),this.immediatelyFilterMessagesForTest){for(const e of this.consoleMessages)this.computeShouldMessageBeVisible(e);this.updateMessageList()}else this.buildHiddenCache(0,this.consoleMessages.slice())}setImmediatelyFilterMessagesForTest(){this.immediatelyFilterMessagesForTest=!0}searchableView(){return this.searchableViewInternal}clearHistory(){this.prompt.history().clear()}consoleHistoryAutocompleteChanged(){this.prompt.setAddCompletionsFromHistory(this.consoleHistoryAutocompleteSetting.get())}itemCount(){return this.visibleViewMessages.length}itemElement(e){return this.visibleViewMessages[e]}fastHeight(e){return this.visibleViewMessages[e].fastHeight()}minimumRowHeight(){return 16}registerWithMessageSink(){e.Console.Console.instance().messages().forEach(this.addSinkMessage,this),e.Console.Console.instance().addEventListener("messageAdded",(({data:e})=>{this.addSinkMessage(e)}),this)}addSinkMessage(e){let t="verbose";switch(e.level){case"info":t="info";break;case"error":t="error";break;case"warning":t="warning"}const s=e.source||"other",o=new n.ConsoleModel.ConsoleMessage(null,s,t,e.text,{type:n.ConsoleModel.FrontendMessageType.System,timestamp:e.timestamp});this.addConsoleMessage(o)}consoleTimestampsSettingChanged(){this.updateMessageList(),this.consoleMessages.forEach((e=>e.updateTimestamp())),this.groupableMessageTitle.forEach((e=>e.updateTimestamp()))}executionContextChanged(){this.prompt.clearAutocomplete()}willHide(){this.hidePromptSuggestBox()}wasShown(){if(super.wasShown(),this.#r){M.IssuesManager.IssuesManager.instance().addEventListener("IssuesCountUpdated",this.#a)}this.#r=!1,this.updateIssuesToolbarItem(),this.viewport.refresh()}focus(){this.viewport.hasVirtualSelection()?this.viewport.contentElement().focus():this.focusPrompt()}focusPrompt(){if(!this.prompt.hasFocus()){const e=this.viewport.stickToBottom(),t=this.viewport.element.scrollTop;this.prompt.focus(),this.viewport.setStickToBottom(e),this.viewport.element.scrollTop=t}}restoreScrollPositions(){this.viewport.stickToBottom()?this.immediatelyScrollToBottom():super.restoreScrollPositions()}onResize(){this.scheduleViewportRefresh(),this.hidePromptSuggestBox(),this.viewport.stickToBottom()&&this.immediatelyScrollToBottom();for(let e=0;e0?this.consoleMessages.length:s.ArrayUtilities.upperBound(this.consoleMessages,t,l);const i=o=5&&!this.selfXssWarningDisabledSetting.get()&&this.selfXssWarningDisabledSetting.set(!0);else if(e.type!==n.ConsoleModel.FrontendMessageType.Result){const n=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,l)-1;if(n>=0){!function e(t,s){const n=s.groupEnd();if(null!==n&&l(t,n)>0){const n=s.consoleGroup();if(null===n)return;return void e(t,n)}"endGroup"===t.consoleMessage().type?s.setGroupEnd(t):t.setConsoleGroup(s)}(t,this.consoleGroupStarts[n])}e.isGroupStartMessage()&&(o=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,l),this.consoleGroupStarts.splice(o,0,t))}this.filter.onMessageAdded(e),this.isSidebarOpen?this.sidebar.onMessageAdded(t):this.pendingSidebarMessages.push(t);let r=!1;const a=this.groupSimilarSetting.get();if(e.isGroupable()){const e=t.groupKey();r=a&&this.groupableMessages.has(e);let s=this.groupableMessages.get(e);s||(s=[],this.groupableMessages.set(e,s)),s.push(t)}function l(e,t){return(We.get(e)||0)-(We.get(t)||0)}this.computeShouldMessageBeVisible(t),r||i?this.needsFullUpdate=!0:(this.appendMessageToEnd(t,!a),this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length)),this.scheduleViewportRefresh(),this.consoleMessageAddedForTest(t)}onConsoleMessageUpdated(e){const t=e.data,s=_e.get(t);s&&(s.updateMessageElement(),this.computeShouldMessageBeVisible(s),this.updateMessageList())}consoleMessageAddedForTest(e){}shouldMessageBeVisible(e){return!this.shouldBeHiddenCache.has(e)}computeShouldMessageBeVisible(e){!this.filter.shouldBeVisible(e)||this.isSidebarOpen&&!this.sidebar.shouldBeVisible(e)?this.shouldBeHiddenCache.add(e):this.shouldBeHiddenCache.delete(e)}appendMessageToEnd(e,t){if("cors"===e.consoleMessage().category&&!this.showCorsErrorsSetting.get())return;const s=this.visibleViewMessages[this.visibleViewMessages.length-1];if("endGroup"===e.consoleMessage().type){if(s){const e=s.consoleGroup();e&&!e.messagesHidden()&&s.incrementCloseGroupDecorationCount()}return}if(!this.shouldMessageBeVisible(e))return void this.hiddenByFilterCount++;if(!t&&this.tryToCollapseMessages(e,this.visibleViewMessages[this.visibleViewMessages.length-1]))return;const n=e.consoleGroup();if(!n?.messagesHidden()){const t=e.consoleMessage().originatingMessage(),o=Boolean(t&&s?.consoleMessage()===t);e.setAdjacentUserCommandResult(o),function e(t,s){if(null===t)return;if(s.includes(t))return;const n=t.consoleGroup();n&&e(n,s);s.push(t)}(n,this.visibleViewMessages),this.visibleViewMessages.push(e),this.searchMessage(this.visibleViewMessages.length-1)}this.messageAppendedForTests()}messageAppendedForTests(){}createViewMessage(e){switch(e.type){case n.ConsoleModel.FrontendMessageType.Command:return new Ee(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case n.ConsoleModel.FrontendMessageType.Result:return new ke(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case"startGroupCollapsed":case"startGroup":return new Me(e,this.linkifier,this.requestResolver,this.issueResolver,this.updateMessageList.bind(this),this.onMessageResizedBound);case"table":return new Te(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);default:return new we(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound)}}async onMessageResized(e){const t=e.data;if(this.pendingBatchResize||!t.treeOutline)return;this.pendingBatchResize=!0,await Promise.resolve();const s=t.treeOutline.element;this.viewport.setStickToBottom(this.isScrolledToBottom()),s.offsetHeight<=this.messagesElement.offsetHeight&&s.scrollIntoViewIfNeeded(),this.pendingBatchResize=!1}consoleCleared(){const e=this.viewport.element.hasFocus();this.cancelBuildHiddenCache(),this.currentMatchRangeIndex=-1,this.consoleMessages=[],this.groupableMessages.clear(),this.groupableMessageTitle.clear(),this.sidebar.clear(),this.pendingSidebarMessages=[],this.updateMessageList(),this.hidePromptSuggestBox(),this.viewport.setStickToBottom(!0),this.linkifier.reset(),this.filter.clear(),this.requestResolver.clear(),this.consoleGroupStarts=[],e&&this.prompt.focus(),o.ARIAUtils.alert(Ve(je.consoleCleared))}handleContextMenuEvent(t){const s=new o.ContextMenu.ContextMenu(t),i=t.target;if(i.isSelfOrDescendant(this.promptElement))return void s.show();const r=i.enclosingNodeOrSelfWithClass("console-message-wrapper"),a=r&&ve(r),l=a?a.consoleMessage():null;if(a&&o.Context.Context.instance().setFlavor(we,a),l&&!a?.element()?.matches(".has-insight")&&a?.shouldShowInsights()&&s.headerSection().appendAction(a?.getExplainActionId(),void 0,!0),l&&l.url){const t=Ve(je.hideMessagesFromS,{PH1:new e.ParsedURL.ParsedURL(l.url).displayName});s.headerSection().appendItem(t,this.filter.addMessageURLFilter.bind(this.filter,l.url),{jslogContext:"hide-messages-from"})}if(s.defaultSection().appendAction("console.clear"),s.defaultSection().appendAction("console.clear.history"),s.saveSection().appendItem(Ve(je.copyConsole),this.copyConsole.bind(this),{jslogContext:"copy-console"}),s.saveSection().appendItem(Ve(je.saveAs),this.saveConsole.bind(this),{jslogContext:"save-as"}),this.element.hasSelection()&&s.clipboardSection().appendItem(Ve(je.copyVisibleStyledSelection),this.viewport.copyWithStyles.bind(this.viewport),{jslogContext:"copy-visible-styled-selection"}),l){const e=g.NetworkLog.NetworkLog.requestForConsoleMessage(l);e&&n.NetworkManager.NetworkManager.canReplayRequest(e)&&s.debugSection().appendItem(Ve(je.replayXhr),n.NetworkManager.NetworkManager.replayRequest.bind(null,e),{jslogContext:"replay-xhr"})}s.show()}async saveConsole(){const t=n.TargetManager.TargetManager.instance().scopeTarget().inspectedURL(),i=e.ParsedURL.ParsedURL.fromString(t),r=s.StringUtilities.sprintf("%s-%d.log",i?i.host:"console",Date.now()),a=new p.FileUtils.FileOutputStream,l=new o.ProgressIndicator.ProgressIndicator;l.setTitle(Ve(je.writingFile)),l.setTotalWork(this.itemCount());if(!await a.open(r))return;this.progressToolbarItem.element.appendChild(l.element);let c=0;for(;c12));++n);n!==t.length?this.buildHiddenCacheTimeout=this.element.window().requestAnimationFrame(this.buildHiddenCache.bind(this,n+1,t)):this.updateMessageList()}cancelBuildHiddenCache(){this.shouldBeHiddenCache.clear(),this.buildHiddenCacheTimeout&&(this.element.window().cancelAnimationFrame(this.buildHiddenCacheTimeout),delete this.buildHiddenCacheTimeout)}updateMessageList(){this.regexMatchRanges=[],this.hiddenByFilterCount=0;for(const e of this.visibleViewMessages)e.resetCloseGroupDecorationCount(),e.resetIncrementRepeatCount();if(this.visibleViewMessages=[],this.groupSimilarSetting.get())this.addGroupableMessagesToEnd();else for(const e of this.consoleMessages)e.setInSimilarGroup(!1),e.consoleMessage().isGroupable()&&e.clearConsoleGroup(),this.appendMessageToEnd(e,!0);this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length),this.viewport.invalidate(),this.messagesCountElement.setAttribute("aria-label",Ve(je.filteredMessagesInConsole,{PH1:this.visibleViewMessages.length}))}addGroupableMessagesToEnd(){const e=new Set,t=new Set;for(const s of this.consoleMessages){const o=s.consoleMessage();if(e.has(o))continue;if(!o.isGroupable()){this.appendMessageToEnd(s),e.add(o);continue}const i=s.groupKey(),r=this.groupableMessages.get(i);if(!r||r.length<5){s.setInSimilarGroup(!1),this.appendMessageToEnd(s),e.add(o);continue}if(t.has(i))continue;if(!r.find((e=>this.shouldMessageBeVisible(e)))){for(const t of r)e.add(t.consoleMessage());t.add(i);continue}let a=this.groupableMessageTitle.get(i);if(!a){const e=new n.ConsoleModel.ConsoleMessage(null,o.source,o.level,s.groupTitle(),{type:"startGroupCollapsed"});a=this.createViewMessage(e),this.groupableMessageTitle.set(i,a)}a.setRepeatCount(r.length),this.appendMessageToEnd(a);for(const t of r)t.setInSimilarGroup(!0,r[r.length-1]===t),t.setConsoleGroup(a),this.appendMessageToEnd(t,!0),e.add(t.consoleMessage());const l=new n.ConsoleModel.ConsoleMessage(null,o.source,o.level,o.messageText,{type:"endGroup"});this.appendMessageToEnd(this.createViewMessage(l))}}messagesClicked(e){const t=e.target;if(!this.messagesElement.hasSelection()){(t===this.messagesElement||this.prompt.belowEditorElement().isSelfOrAncestor(t))&&(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}}messagesKeyDown(e){const t=e;t.ctrlKey||t.altKey||t.metaKey||1!==t.key.length||o.UIUtils.isEditing()||this.messagesElement.hasSelection()||(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}messagesPasted(e){r.Runtime.Runtime.queryParam("isChromeForTesting")||r.Runtime.Runtime.queryParam("disableSelfXssWarnings")||this.selfXssWarningDisabledSetting.get()||(e.preventDefault(),this.prompt.showSelfXssWarning()),o.UIUtils.isEditing()||this.prompt.focus()}registerShortcuts(){this.shortcuts.set(o.KeyboardShortcut.KeyboardShortcut.makeKey("u",o.KeyboardShortcut.Modifiers.Ctrl.value),this.clearPromptBackwards.bind(this))}clearPromptBackwards(e){this.prompt.clear(),d.logKeyDown(e.currentTarget,e,"clear-prompt")}promptKeyDown(e){const t=e;if("PageUp"===t.key)return void this.updateStickToBottomOnWheel();const s=o.KeyboardShortcut.KeyboardShortcut.makeKeyFromEvent(t),n=this.shortcuts.get(s);n&&(n(t),t.preventDefault())}printResult(e,t,s){if(!e)return;const o=Boolean(s)?"error":"info";let i;i=s?n.ConsoleModel.ConsoleMessage.fromException(e.runtimeModel(),s,n.ConsoleModel.FrontendMessageType.Result,void 0,void 0):new n.ConsoleModel.ConsoleMessage(e.runtimeModel(),"javascript",o,"",{type:n.ConsoleModel.FrontendMessageType.Result,parameters:[e]}),i.setOriginatingMessage(t),e.runtimeModel().target().model(n.ConsoleModel.ConsoleModel)?.addMessage(i)}commandEvaluated(e){const{data:t}=e;this.printResult(t.result,t.commandMessage,t.exceptionDetails)}elementsToRestoreScrollPositionsFor(){return[this.messagesElement]}onSearchCanceled(){this.cleanupAfterSearch();for(const e of this.visibleViewMessages)e.setSearchRegex(null);this.currentMatchRangeIndex=-1,this.regexMatchRanges=[],this.searchRegex=null,this.viewport.refresh()}performSearch(e,t,s){this.onSearchCanceled(),this.searchableViewInternal.updateSearchMatchesCount(0),this.searchRegex=e.toSearchRegex(!0).regex,this.regexMatchRanges=[],this.currentMatchRangeIndex=-1,t&&(this.searchShouldJumpBackwards=Boolean(s)),this.searchProgressIndicator=new o.ProgressIndicator.ProgressIndicator,this.searchProgressIndicator.setTitle(Ve(je.searching)),this.searchProgressIndicator.setTotalWork(this.visibleViewMessages.length),this.progressToolbarItem.element.appendChild(this.searchProgressIndicator.element),this.innerSearch(0)}cleanupAfterSearch(){delete this.searchShouldJumpBackwards,this.innerSearchTimeoutId&&(clearTimeout(this.innerSearchTimeoutId),delete this.innerSearchTimeoutId),this.searchProgressIndicator&&(this.searchProgressIndicator.done(),delete this.searchProgressIndicator)}searchFinishedForTests(){}innerSearch(e){if(delete this.innerSearchTimeoutId,this.searchProgressIndicator?.isCanceled())return void this.cleanupAfterSearch();const t=Date.now();for(;e=0){t=this.regexMatchRanges[this.currentMatchRangeIndex];this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex).classList.remove(o.UIUtils.highlightedCurrentSearchResultClassName)}e=s.NumberUtilities.mod(e,this.regexMatchRanges.length),this.currentMatchRangeIndex=e,this.searchableViewInternal.updateCurrentMatchIndex(e),t=this.regexMatchRanges[e];const n=this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex);n.classList.add(o.UIUtils.highlightedCurrentSearchResultClassName),this.viewport.scrollItemIntoView(t.messageIndex),n.scrollIntoViewIfNeeded()}updateStickToBottomOnPointerDown(e){this.muteViewportUpdates=!e,this.viewport.setStickToBottom(!1),this.waitForScrollTimeout&&(clearTimeout(this.waitForScrollTimeout),delete this.waitForScrollTimeout)}updateStickToBottomOnPointerUp(){this.muteViewportUpdates&&(this.waitForScrollTimeout=window.setTimeout(function(){this.muteViewportUpdates=!1,this.isShowing()&&this.viewport.setStickToBottom(this.isScrolledToBottom());this.maybeDirtyWhileMuted&&(this.scheduleViewportRefresh(),delete this.maybeDirtyWhileMuted);delete this.waitForScrollTimeout,this.updateViewportStickinessForTest()}.bind(this),200))}updateViewportStickinessForTest(){}updateStickToBottomOnWheel(){this.updateStickToBottomOnPointerDown(),this.updateStickToBottomOnPointerUp()}promptTextChanged(){const e=this.viewport.stickToBottom(),t=this.isScrolledToBottom();this.viewport.setStickToBottom(t),t&&!e&&this.scheduleViewportRefresh(),this.promptTextChangedForTest()}promptTextChangedForTest(){}isScrolledToBottom(){return this.messagesElement.scrollHeight-this.messagesElement.scrollTop-this.messagesElement.clientHeight-this.prompt.belowEditorElement().offsetHeight<=2}}globalThis.Console=globalThis.Console||{},globalThis.Console.ConsoleView=Ge;class De{filterChanged;messageLevelFiltersSetting;hideNetworkMessagesSetting;filterByExecutionContextSetting;suggestionBuilder;textFilterUI;textFilterSetting;filterParser;currentFilter;levelLabels;levelMenuButton;constructor(t){this.filterChanged=t,this.messageLevelFiltersSetting=De.levelFilterSetting(),this.hideNetworkMessagesSetting=e.Settings.Settings.instance().moduleSetting("hide-network-messages"),this.filterByExecutionContextSetting=e.Settings.Settings.instance().moduleSetting("selected-context-filter-enabled"),this.messageLevelFiltersSetting.addChangeListener(this.onFilterChanged.bind(this)),this.hideNetworkMessagesSetting.addChangeListener(this.onFilterChanged.bind(this)),this.filterByExecutionContextSetting.addChangeListener(this.onFilterChanged.bind(this)),o.Context.Context.instance().addFlavorChangeListener(n.RuntimeModel.ExecutionContext,this.onFilterChanged,this);const s=Object.values(R);this.suggestionBuilder=new o.FilterSuggestionBuilder.FilterSuggestionBuilder(s),this.textFilterUI=new o.Toolbar.ToolbarFilter(void 0,1,1,Ve(je.egEventdCdnUrlacom),this.suggestionBuilder.completions.bind(this.suggestionBuilder),!0),this.textFilterSetting=e.Settings.Settings.instance().createSetting("console.text-filter",""),this.textFilterSetting.get()&&this.textFilterUI.setValue(this.textFilterSetting.get()),this.textFilterUI.addEventListener("TextChanged",(()=>{this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()})),this.filterParser=new i.TextUtils.FilterParser(s),this.currentFilter=new P("",[],null,this.messageLevelFiltersSetting.get()),this.updateCurrentFilter(),this.levelLabels=new Map([["verbose",Ve(je.verbose)],["info",Ve(je.info)],["warning",Ve(je.warnings)],["error",Ve(je.errors)]]),this.levelMenuButton=new o.Toolbar.ToolbarMenuButton(this.appendLevelMenuItems.bind(this),void 0,void 0,"log-level"),this.updateLevelMenuButtonText(),this.messageLevelFiltersSetting.addChangeListener(this.updateLevelMenuButtonText.bind(this))}onMessageAdded(e){e.type===n.ConsoleModel.FrontendMessageType.Command||e.type===n.ConsoleModel.FrontendMessageType.Result||e.isGroupMessage()||(e.context&&this.suggestionBuilder.addItem(R.Context,e.context),e.source&&this.suggestionBuilder.addItem(R.Source,e.source),e.url&&this.suggestionBuilder.addItem(R.Url,e.url))}setLevelMenuOverridden(e){this.levelMenuButton.setEnabled(!e),e?this.levelMenuButton.setTitle(Ve(je.overriddenByFilterSidebar)):this.updateLevelMenuButtonText()}static levelFilterSetting(){return e.Settings.Settings.instance().createSetting("message-level-filters",P.defaultLevelsFilterValue())}updateCurrentFilter(){const e=this.filterParser.parse(this.textFilterUI.value());for(const{key:t}of e)switch(t){case R.Context:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterByContext);break;case R.Source:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterBySource);break;case R.Url:m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleFilterByUrl)}this.hideNetworkMessagesSetting.get()&&e.push({key:R.Source,text:"network",negative:!0,regex:void 0}),this.currentFilter.executionContext=this.filterByExecutionContextSetting.get()?o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext):null,this.currentFilter.parsedFilters=e,this.currentFilter.levelsMask=this.messageLevelFiltersSetting.get()}onFilterChanged(){this.updateCurrentFilter(),this.filterChanged()}updateLevelMenuButtonText(){let e=!0,t=!0;const s=P.allLevelsFilterValue(),n=P.defaultLevelsFilterValue();let o=null;const i=this.messageLevelFiltersSetting.get(),r={Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"};for(const a of Object.values(r))e=e&&i[a]===s[a],t=t&&i[a]===n[a],i[a]&&(o=o?Ve(je.customLevels):Ve(je.sOnly,{PH1:String(this.levelLabels.get(a))}));o=e?Ve(je.allLevels):t?Ve(je.defaultLevels):o||Ve(je.hideAll),this.levelMenuButton.element.classList.toggle("warning",!e&&!t),this.levelMenuButton.setText(o),this.levelMenuButton.setTitle(Ve(je.logLevelS,{PH1:o}))}appendLevelMenuItems(e){const t=this.messageLevelFiltersSetting,s=t.get();e.headerSection().appendItem(Ve(je.default),(()=>t.set(P.defaultLevelsFilterValue())),{jslogContext:"default"});for(const[t,o]of this.levelLabels.entries())e.defaultSection().appendCheckboxItem(o,n.bind(null,t),{checked:s[t],jslogContext:t});function n(e){s[e]=!s[e],t.set(s)}}addMessageURLFilter(e){if(!e)return;const t=this.textFilterUI.value()?` ${this.textFilterUI.value()}`:"";this.textFilterUI.setValue(`-url:${e}${t}`),this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()}shouldBeVisible(e){return this.currentFilter.shouldBeVisible(e)}clear(){this.suggestionBuilder.clear()}reset(){this.messageLevelFiltersSetting.set(P.defaultLevelsFilterValue()),this.filterByExecutionContextSetting.set(!1),this.hideNetworkMessagesSetting.set(!1),this.textFilterUI.setValue(""),this.onFilterChanged()}}const We=new WeakMap,_e=new WeakMap;var ze=Object.freeze({__proto__:null,ActionDelegate:class{handleAction(t,s){switch(s){case"console.toggle":return Ge.instance().hasFocus()&&o.InspectorView.InspectorView.instance().drawerVisible()?(o.InspectorView.InspectorView.instance().closeDrawer(),!0):(m.InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront(),e.Console.Console.instance().show(),Ge.instance().focusPrompt(),!0);case"console.clear":return Ge.clearConsole(),!0;case"console.clear.history":return Ge.instance().clearHistory(),!0}return!1}},ConsoleView:Ge,ConsoleViewFilter:De});let $e;class qe extends o.Panel.Panel{view;constructor(){super("console"),this.view=Ge.instance()}static instance(e={forceNew:null}){const{forceNew:t}=e;return $e&&!t||($e=new qe),$e}static updateContextFlavor(){const e=qe.instance().view;o.Context.Context.instance().setFlavor(Ge,e.isShowing()?e:null)}wasShown(){super.wasShown();const e=Ke;e?.isShowing()&&o.InspectorView.InspectorView.instance().setDrawerMinimized(!0),this.view.show(this.element),qe.updateContextFlavor()}willHide(){super.willHide(),o.InspectorView.InspectorView.instance().setDrawerMinimized(!1),Ke&&Ke.showViewInWrapper(),qe.updateContextFlavor()}searchableView(){return Ge.instance().searchableView()}}let Ke=null;class Je extends o.Widget.VBox{view;constructor(){super(),this.view=Ge.instance(),this.element.setAttribute("jslog",`${d.panel("console").track({resize:!0})}`)}static instance(){return Ke||(Ke=new Je),Ke}wasShown(){qe.instance().isShowing()?o.InspectorView.InspectorView.instance().setDrawerMinimized(!0):this.showViewInWrapper(),qe.updateContextFlavor()}willHide(){o.InspectorView.InspectorView.instance().setDrawerMinimized(!1),qe.updateContextFlavor()}showViewInWrapper(){this.view.show(this.element)}}var Xe=Object.freeze({__proto__:null,ConsolePanel:qe,ConsoleRevealer:class{async reveal(e){const t=Ge.instance();t.isShowing()?t.focus():await o.ViewManager.ViewManager.instance().showView("console-view")}},WrapperView:Je}),Ze={cssText:`#console-prompt .CodeMirror{padding:3px 0 1px}#console-prompt .CodeMirror-line{padding-top:0}#console-prompt .CodeMirror-lines{padding-top:0}#console-prompt .console-prompt-icon{position:absolute;left:-13px;top:2px;user-select:none}.console-eager-preview{padding-bottom:2px;opacity:60%;position:relative}.console-eager-inner-preview{text-overflow:ellipsis;overflow:hidden;margin-left:4px;height:100%;white-space:nowrap}.preview-result-icon{position:absolute;left:-13px;top:-1px}.console-eager-inner-preview:empty,\n.console-eager-inner-preview:empty + .preview-result-icon{opacity:0%}.console-prompt-icon.console-prompt-incomplete{opacity:65%}\n/*# sourceURL=${import.meta.resolve("./consolePrompt.css")} */\n`};const{Direction:Qe}=l.TextEditorHistory,Ye={consolePrompt:"Console prompt",selfXssWarning:"Warning: Don’t paste code into the DevTools Console that you don’t understand or haven’t reviewed yourself. This could allow attackers to steal your identity or take control of your computer. Please type ‘{PH1}’ below and hit Enter to allow pasting.",allowPasting:"allow pasting"},et=t.i18n.registerUIStrings("panels/console/ConsolePrompt.ts",Ye),tt=t.i18n.getLocalizedString.bind(void 0,et);class st extends(e.ObjectWrapper.eventMixin(o.Widget.Widget)){addCompletionsFromHistory;historyInternal;initialText;editor;eagerPreviewElement;textChangeThrottler;formatter;requestPreviewBound;requestPreviewCurrent=0;innerPreviewElement;promptIcon;iconThrottler;previewRequestForTest;highlightingNode;#c;#d;#h=!1;#u=new a.Compartment;#m(){return this.#h?[]:"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")?[a.javascript.javascript(),l.JavaScript.completion()]:[a.javascript.javascriptLanguage]}#p(){const e=this.#m(),t=this.#u.reconfigure(e);this.editor.dispatch({effects:t})}constructor(){super(),this.registerRequiredCSS(Ze),this.addCompletionsFromHistory=!0,this.historyInternal=new l.AutocompleteHistory.AutocompleteHistory(e.Settings.Settings.instance().createLocalSetting("console-history",[])),this.initialText="",this.eagerPreviewElement=document.createElement("div"),this.eagerPreviewElement.classList.add("console-eager-preview"),this.textChangeThrottler=new e.Throttler.Throttler(150),this.formatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.requestPreviewBound=this.requestPreview.bind(this),this.innerPreviewElement=this.eagerPreviewElement.createChild("div","console-eager-inner-preview");const t=new h.Icon.Icon;t.data={iconName:"chevron-left-dot",color:"var(--icon-default)",width:"16px",height:"16px"},t.classList.add("preview-result-icon"),this.eagerPreviewElement.appendChild(t);const s=this.element.createChild("div","console-prompt-editor-container");this.element.appendChild(this.eagerPreviewElement),this.promptIcon=new h.Icon.Icon,this.promptIcon.data={iconName:"chevron-right",color:"var(--icon-action)",width:"16px",height:"16px"},this.promptIcon.classList.add("console-prompt-icon"),this.element.appendChild(this.promptIcon),this.iconThrottler=new e.Throttler.Throttler(0),this.element.tabIndex=0,this.previewRequestForTest=null,this.highlightingNode=!1;const n=l.JavaScript.argumentHints();this.#c=n[0];const o=l.Config.DynamicSetting.bool("console-autocomplete-on-enter",[],l.Config.conservativeCompletion),i=[a.keymap.of(this.editorKeymap()),a.EditorView.updateListener.of((e=>this.editorUpdate(e))),n,o.instance(),l.Config.showCompletionHint,l.Config.baseConfiguration(this.initialText),l.Config.autocompletion.instance(),a.javascript.javascriptLanguage.data.of({autocomplete:e=>this.addCompletionsFromHistory?this.#d.historyCompletions(e):null}),a.EditorView.contentAttributes.of({"aria-label":tt(Ye.consolePrompt)}),a.EditorView.lineWrapping,a.autocompletion({aboveCursor:!0}),this.#u.of(this.#m())],r=this.initialText,u=a.EditorState.create({doc:r,extensions:i});this.editor=new l.TextEditor.TextEditor(u),this.editor.addEventListener("keydown",(e=>{e.defaultPrevented&&e.stopPropagation()})),s.appendChild(this.editor),this.#d=new l.TextEditorHistory.TextEditorHistory(this.editor,this.historyInternal),this.hasFocus()&&this.focus(),this.element.removeAttribute("tabindex"),this.editorSetForTest(),m.userMetrics.panelLoaded("console","DevTools.Launch.Console"),this.element.setAttribute("jslog",`${d.textField("console-prompt").track({change:!0,keydown:"Enter|ArrowUp|ArrowDown|PageUp"})}`)}belowEditorElement(){return this.eagerPreviewElement}onTextChanged(){this.updatePromptIcon(),this.dispatchEventToListeners("TextChanged")}async requestPreview(){const e=++this.requestPreviewCurrent,t=l.Config.contentIncludingHint(this.editor.editor).trim(),s=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext),{preview:i,result:r}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(t,!0,!0,500);this.requestPreviewCurrent===e&&(this.innerPreviewElement.removeChildren(),i.deepTextContent()!==l.Config.contentIncludingHint(this.editor.editor).trim()&&this.innerPreviewElement.appendChild(i),r&&"object"in r&&r.object&&"node"===r.object.subtype?(this.highlightingNode=!0,n.OverlayModel.OverlayModel.highlightObjectAsDOMNode(r.object)):this.highlightingNode&&(this.highlightingNode=!1,n.OverlayModel.OverlayModel.hideDOMNodeHighlight()),r&&s&&s.runtimeModel.releaseEvaluationResult(r))}willHide(){super.willHide(),this.highlightingNode&&(this.highlightingNode=!1,n.OverlayModel.OverlayModel.hideDOMNodeHighlight())}history(){return this.historyInternal}clearAutocomplete(){a.closeCompletion(this.editor.editor)}isCaretAtEndOfPrompt(){return this.editor.state.selection.main.head===this.editor.state.doc.length}moveCaretToEndOfPrompt(){this.editor.dispatch({selection:a.EditorSelection.cursor(this.editor.state.doc.length)})}clear(){this.editor.dispatch({changes:{from:0,to:this.editor.state.doc.length}})}text(){return this.editor.state.doc.toString()}setAddCompletionsFromHistory(e){this.addCompletionsFromHistory=e}editorKeymap(){return[{key:"ArrowUp",run:()=>this.#d.moveHistory(-1)},{key:"ArrowDown",run:()=>this.#d.moveHistory(1)},{mac:"Ctrl-p",run:()=>this.#d.moveHistory(-1,!0)},{mac:"Ctrl-n",run:()=>this.#d.moveHistory(1,!0)},{key:"Escape",run:()=>l.JavaScript.closeArgumentsHintsTooltip(this.editor.editor,this.#c)},{key:"Ctrl-Enter",run:()=>(this.handleEnter(!0),!0)},{key:"Enter",run:()=>(this.handleEnter(),!0),shift:a.insertNewlineAndIndent}]}async enterWillEvaluate(e){const{doc:t,selection:s}=this.editor.state;if(!t.length)return!1;if(e||s.main.head{this.promptIcon.classList.toggle("console-prompt-incomplete",!await this.enterWillEvaluate())}))}appendCommand(e,t){const s=o.Context.Context.instance().flavor(n.RuntimeModel.ExecutionContext);if(s){const o=s,i=o.target().model(n.ConsoleModel.ConsoleModel);if(i){const s=i.addCommandMessage(o,e),n=c.JavaScriptREPL.JavaScriptREPL.wrapObjectLiteral(e);this.evaluateCommandInConsole(o,s,n,t),qe.instance().isShowing()&&m.userMetrics.actionTaken(m.UserMetrics.Action.CommandEvaluatedInConsolePanel)}}}async evaluateCommandInConsole(e,t,s,o){const i=e.debuggerModel.selectedCallFrame();if(i?.script.isJavaScript()){const e=await y.NamesResolver.allVariablesInCallFrame(i);s=await this.substituteNames(s,e)}await(e.target().model(n.ConsoleModel.ConsoleModel)?.evaluateCommandInConsole(e,t,s,o))}async substituteNames(e,t){try{return await I.FormatterWorkerPool.formatterWorkerPool().javaScriptSubstitute(e,t)}catch{return e}}editorUpdate(e){e.docChanged||a.selectedCompletion(e.state)!==a.selectedCompletion(e.startState)?this.onTextChanged():e.selectionSet&&this.updatePromptIcon()}focus(){this.editor.focus()}editorSetForTest(){}}var nt=Object.freeze({__proto__:null,ConsolePrompt:st});export{A as ConsoleContextSelector,U as ConsoleFilter,V as ConsoleFormat,Xe as ConsolePanel,K as ConsolePinPane,nt as ConsolePrompt,oe as ConsoleSidebar,ze as ConsoleView,Ue as ConsoleViewMessage,He as ConsoleViewport,he as ErrorStackParser}; From f000116197933c852b71d30e3969c078e35f10fe Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Tue, 8 Jul 2025 04:34:14 -0700 Subject: [PATCH 0021/1383] Fix Timestamps conversion for Custom Tracks (#52479) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52479 # Changelog: [Internal] The previous cast is incorrect. Reviewed By: javache Differential Revision: D77894512 fbshipit-source-id: 67e6b9a4ed43020a343a2a9b5d702509c34ae41a --- .../reactperflogger/reactperflogger/ReactPerfetto.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.cpp b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.cpp index c280ad4ca08a2d..c8635e5e0fada6 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.cpp +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.cpp @@ -88,9 +88,7 @@ uint64_t highResTimeStampToPerfettoTraceTime(HighResTimeStamp timestamp) { auto nanoseconds = std::chrono::duration_cast( chronoDurationSinceSteadyClockEpoch); - return std::chrono::duration_cast>( - nanoseconds) - .count(); + return static_cast(nanoseconds.count()); } } // namespace facebook::react From 5a79ece1924661729cc144226377d694eeca6bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Tue, 8 Jul 2025 04:40:49 -0700 Subject: [PATCH 0022/1383] Use structuredClone to copy detail field in performance.mark and performance.measure (#52483) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52483 Changelog: [internal] This is a small refinement for `performance.mark` and `performance.measure` to use `structuredClone` to copy the value of the `detail` field, instead of assigning it by reference. This still doesn't completely fix the semantics of `performance.mark` and `performance.measure`, as the entries returned by those methods aren't referentially equal to the entries reported by `PerformanceObserver` (and the latter don't have the `detail` field yet). Reviewed By: huntie Differential Revision: D77863037 fbshipit-source-id: 54d959612ecd560250e49bb0887bb12112a0142f --- .../src/private/webapis/performance/Performance.js | 13 +++++++++++-- .../performance/__tests__/Performance-itest.js | 6 ++---- .../performance/__tests__/UserTimingAPI-itest.js | 14 ++++++++------ 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index 639b8de9773883..e697e480be980e 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -18,6 +18,7 @@ import type { import type {DetailType, PerformanceMarkOptions} from './UserTiming'; import DOMException from '../errors/DOMException'; +import structuredClone from '../structuredClone/structuredClone'; import {setPlatformObject} from '../webidl/PlatformObjects'; import {EventCounts} from './EventTiming'; import { @@ -122,6 +123,11 @@ export default class Performance { ); } + let resolvedDetail; + if (markOptions?.detail != null) { + resolvedDetail = structuredClone(markOptions.detail); + } + let computedStartTime; if (NativePerformance?.markWithResult) { let resolvedStartTime; @@ -152,7 +158,7 @@ export default class Performance { return new PerformanceMark(markName, { startTime: computedStartTime, - detail: markOptions?.detail, + detail: resolvedDetail, }); } @@ -249,7 +255,10 @@ export default class Performance { ); } - resolvedDetail = startMarkOrOptions.detail; + const detail = startMarkOrOptions.detail; + if (detail != null) { + resolvedDetail = structuredClone(detail); + } break; } diff --git a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js index 6de3dae4ef5911..eba0412dd01bbd 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/Performance-itest.js @@ -75,8 +75,7 @@ describe('Performance', () => { }); expect(mark.detail).toEqual(originalDetail); - // TODO structuredClone - // expect(mark.detail).not.toBe(originalDetail); + expect(mark.detail).not.toBe(originalDetail); }); it('throws if no name is provided', () => { @@ -423,8 +422,7 @@ describe('Performance', () => { }); expect(measure.detail).toEqual(originalDetail); - // TODO structuredClone - // expect(measure.detail).not.toBe(originalDetail); + expect(measure.detail).not.toBe(originalDetail); }); }); diff --git a/packages/react-native/src/private/webapis/performance/__tests__/UserTimingAPI-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/UserTimingAPI-itest.js index c143c940ed3507..52ef87e923240e 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/UserTimingAPI-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/UserTimingAPI-itest.js @@ -32,16 +32,16 @@ describe('User Timing API', () => { expect(callback).not.toHaveBeenCalled(); - const mark1Detail = Symbol('mark1Detail'); + // const mark1Detail = {mark1: 'detail1'}; performance.mark('mark1', { startTime: 100, - detail: mark1Detail, + // detail: mark1Detail, }); - const mark2Detail = Symbol('mark2Detail'); + // const mark2Detail = {mark2: 'detail2'}; performance.mark('mark2', { startTime: 200, - detail: mark2Detail, + // detail: mark2Detail, }); expect(callback).not.toHaveBeenCalled(); @@ -61,14 +61,16 @@ describe('User Timing API', () => { expect(mark1.startTime).toBe(100); expect(mark1.duration).toBe(0); // This doesn't work through PerformanceObserver yet - // expect(mark1.detail).toBe(mark1Detail); + // expect(mark1.detail).toEqual(mark1Detail); + // expect(mark1.detail).not.toBe(mark1Detail); expect(mark2.entryType).toBe('mark'); expect(mark2.name).toBe('mark2'); expect(mark2.startTime).toBe(200); expect(mark2.duration).toBe(0); // This doesn't work through PerformanceObserver yet - // expect(mark2.detail).toBe(mark2Detail); + // expect(mark2.detail).toEqual(mark2Detail); + // expect(mark2.detail).not.toBe(mark2Detail); }); }); }); From 120a417320dbd2628a8d1e39fc32e255717b6934 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Tue, 8 Jul 2025 04:53:51 -0700 Subject: [PATCH 0023/1383] Cleanup react-native-codegen DEFS (#52468) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52468 * Re-enable tests * Simplify logic to avoid bypasses for arc focus Changelog: [Internal] Reviewed By: philIip Differential Revision: D77143018 fbshipit-source-id: 06ec43ce5149a139db78d38630191b01bc520461 --- .../generators/components/GenerateTests.js | 8 +- .../__snapshots__/GenerateTests-test.js.snap | 480 +++++++++--------- 2 files changed, 244 insertions(+), 244 deletions(-) diff --git a/packages/react-native-codegen/src/generators/components/GenerateTests.js b/packages/react-native-codegen/src/generators/components/GenerateTests.js index 9f10a59932e15e..5ec224a2f49aec 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateTests.js +++ b/packages/react-native-codegen/src/generators/components/GenerateTests.js @@ -65,15 +65,15 @@ const TestTemplate = ({ propValue: string, }) => ` TEST(${componentName}_${testName}, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare<${componentName}>(); - auto const &sourceProps = ${componentName}(); - auto const &rawProps = RawProps(folly::dynamic::object("${propName}", ${propValue})); + ${componentName} sourceProps{}; + RawProps rawProps(folly::dynamic::object("${propName}", ${propValue})); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ${componentName}(parserContext, sourceProps, rawProps); } `; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap index d931c4753b08a3..7c84b28cbaf951 100644 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap +++ b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap @@ -23,15 +23,15 @@ Map { using namespace facebook::react; TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ArrayPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ArrayPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -58,15 +58,15 @@ Map { using namespace facebook::react; TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ArrayPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ArrayPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -93,28 +93,28 @@ Map { using namespace facebook::react; TEST(BooleanPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = BooleanPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + BooleanPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(BooleanPropNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = BooleanPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); + BooleanPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -141,28 +141,28 @@ Map { using namespace facebook::react; TEST(ColorPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ColorPropNativeComponentProps_tintColor, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"tintColor\\", 1)); + ColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"tintColor\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -189,15 +189,15 @@ Map { using namespace facebook::react; TEST(CommandNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + CommandNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); CommandNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -224,28 +224,28 @@ Map { using namespace facebook::react; TEST(CommandNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + CommandNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); CommandNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(CommandNativeComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + CommandNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); CommandNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -273,15 +273,15 @@ Map { using namespace facebook::react; TEST(DimensionPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = DimensionPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + DimensionPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); DimensionPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -308,15 +308,15 @@ Map { using namespace facebook::react; TEST(DoublePropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = DoublePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + DoublePropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); DoublePropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -343,28 +343,28 @@ Map { using namespace facebook::react; TEST(EventsNestedObjectNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = EventsNestedObjectNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + EventsNestedObjectNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(EventsNestedObjectNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = EventsNestedObjectNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); + EventsNestedObjectNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -391,28 +391,28 @@ Map { using namespace facebook::react; TEST(EventsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = EventsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + EventsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); EventsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(EventsNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = EventsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); + EventsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); EventsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -439,15 +439,15 @@ Map { using namespace facebook::react; TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + InterfaceOnlyComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); }", } @@ -474,15 +474,15 @@ Map { using namespace facebook::react; TEST(ExcludedAndroidComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ExcludedAndroidComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ExcludedAndroidComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ExcludedAndroidComponentProps(parserContext, sourceProps, rawProps); }", } @@ -509,15 +509,15 @@ Map { using namespace facebook::react; TEST(ExcludedAndroidIosComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ExcludedAndroidIosComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ExcludedAndroidIosComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ExcludedAndroidIosComponentProps(parserContext, sourceProps, rawProps); }", } @@ -544,41 +544,41 @@ Map { using namespace facebook::react; TEST(ExcludedIosComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ExcludedIosComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ExcludedIosComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ExcludedIosComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFileIncludedNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFileIncludedNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MultiFileIncludedNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFileIncludedNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFileIncludedNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); + MultiFileIncludedNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -605,93 +605,93 @@ Map { using namespace facebook::react; TEST(FloatPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius\\", 0)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius2, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius2\\", 0.001)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius2\\", 0.001)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius3, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius3\\", 2.1)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius3\\", 2.1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius4, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius4\\", 0)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius4\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius5, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius5\\", 1)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius5\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius6, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius6\\", 0)); + FloatPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"blurRadius6\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -719,28 +719,28 @@ Map { using namespace facebook::react; TEST(ImagePropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImagePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ImagePropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImagePropNativeComponentProps_thumbImage, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImagePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); + ImagePropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -767,15 +767,15 @@ Map { using namespace facebook::react; TEST(InsetsPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = InsetsPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + InsetsPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); InsetsPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -802,15 +802,15 @@ Map { using namespace facebook::react; TEST(Int32EnumPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = Int32EnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + Int32EnumPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); Int32EnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -837,15 +837,15 @@ Map { using namespace facebook::react; TEST(IntegerPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = IntegerPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + IntegerPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); IntegerPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -872,28 +872,28 @@ Map { using namespace facebook::react; TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + InterfaceOnlyComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); } TEST(InterfaceOnlyComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + InterfaceOnlyComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); }", } @@ -921,15 +921,15 @@ Map { using namespace facebook::react; TEST(MixedPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MixedPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MixedPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MixedPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -957,67 +957,67 @@ Map { using namespace facebook::react; TEST(ImageColorPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ImageColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_thumbImage, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); + ImageColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_color, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"color\\", 1)); + ImageColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"color\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_thumbTintColor, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbTintColor\\", 1)); + ImageColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"thumbTintColor\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_point, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"point\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); + ImageColorPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"point\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1044,15 +1044,15 @@ Map { using namespace facebook::react; TEST(NoPropsNoEventsComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = NoPropsNoEventsComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + NoPropsNoEventsComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); NoPropsNoEventsComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1080,15 +1080,15 @@ Map { using namespace facebook::react; TEST(ObjectPropsProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = ObjectPropsProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + ObjectPropsProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); ObjectPropsProps(parserContext, sourceProps, rawProps); }", } @@ -1115,28 +1115,28 @@ Map { using namespace facebook::react; TEST(PointPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = PointPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + PointPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); PointPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(PointPropNativeComponentProps_startPoint, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = PointPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"startPoint\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); + PointPropNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"startPoint\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); PointPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1163,54 +1163,54 @@ Map { using namespace facebook::react; TEST(StringEnumPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + StringEnumPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_Top, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"top\\")); + StringEnumPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"top\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_Center, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"center\\")); + StringEnumPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"center\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_BottomRight, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"bottom-right\\")); + StringEnumPropsNativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"bottom-right\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1237,41 +1237,41 @@ Map { using namespace facebook::react; TEST(StringPropComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + StringPropComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringPropComponentProps(parserContext, sourceProps, rawProps); } TEST(StringPropComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + StringPropComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringPropComponentProps(parserContext, sourceProps, rawProps); } TEST(StringPropComponentProps_accessibilityRole, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityRole\\", \\"foo\\")); + StringPropComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"accessibilityRole\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); StringPropComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1298,54 +1298,54 @@ Map { using namespace facebook::react; TEST(MultiFile1NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFile1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MultiFile1NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile1NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFile1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); + MultiFile1NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile2NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFile2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MultiFile2NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile2NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiFile2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); + MultiFile2NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1372,54 +1372,54 @@ Map { using namespace facebook::react; TEST(MultiComponent1NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiComponent1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MultiComponent1NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent1NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiComponent1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); + MultiComponent1NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent2NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiComponent2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + MultiComponent2NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent2NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); + RawPropsParser propParser{}; propParser.prepare(); - auto const &sourceProps = MultiComponent2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); + MultiComponent2NativeComponentProps sourceProps{}; + RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser, parserContext); + rawProps.parse(propParser); MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); }", } From a0e11904d6f870ad22c4a8626d128355c0aa4ffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateo=20Guzm=C3=A1n?= Date: Tue, 8 Jul 2025 05:31:11 -0700 Subject: [PATCH 0024/1383] Clean up unnecessary test setup for Android tests (#52471) Summary: This came out of https://github.com/facebook/react-native/issues/52457 as I had to fix some tests and realised there is a lot of setup that could be shadow and other things that are not needed at all. ## Changelog: [INTERNAL] - Clean up unnecessary test setup for Android tests Pull Request resolved: https://github.com/facebook/react-native/pull/52471 Test Plan: ```sh yarn test-android ``` Reviewed By: cortinico Differential Revision: D77926887 Pulled By: javache fbshipit-source-id: ff493d87633fcb4c4194b50cd374ad2e8acda974 --- .../java/com/facebook/react/RootViewTest.kt | 25 +++---------------- .../NativeAnimatedNodeTraversalTest.kt | 19 +++----------- .../fabric/events/TouchEventDispatchTest.kt | 12 ++------- .../modules/appstate/AppStateModuleTest.kt | 22 +++++----------- .../react/modules/blob/BlobModuleTest.kt | 9 ------- .../modules/network/NetworkingModuleTest.kt | 11 +++----- .../react/modules/network/ResponseUtilTest.kt | 21 +++++----------- .../react/modules/timing/TimingModuleTest.kt | 10 +++----- .../react/uimanager/BaseViewManagerTest.kt | 17 +++---------- .../react/uimanager/OnLayoutEventTest.kt | 13 ---------- .../views/image/ReactImagePropertyTest.kt | 11 +++----- .../testutils/shadows/ShadowArguments.kt | 21 +++++++--------- .../testutils/shadows/ShadowNativeArray.kt | 16 ------------ 13 files changed, 41 insertions(+), 166 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.kt index 6fb1d2a21c4a91..820c75d31af680 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.kt @@ -18,11 +18,9 @@ import android.view.WindowManager import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.BridgeReactContext import com.facebook.react.bridge.CatalystInstance -import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReactTestHelper import com.facebook.react.bridge.WritableArray -import com.facebook.react.bridge.WritableMap import com.facebook.react.common.SystemClock import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import com.facebook.react.uimanager.DisplayMetricsHolder @@ -30,14 +28,12 @@ import com.facebook.react.uimanager.UIManagerModule import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.uimanager.events.RCTEventEmitter import com.facebook.react.uimanager.events.TouchEvent +import com.facebook.testutils.shadows.ShadowArguments import java.util.Date import org.assertj.core.api.Assertions.* -import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.mockito.kotlin.KArgumentCaptor import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor @@ -52,16 +48,15 @@ import org.mockito.kotlin.whenever import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class RootViewTest { private lateinit var reactContext: BridgeReactContext private lateinit var catalystInstanceMock: CatalystInstance - private lateinit var arguments: MockedStatic - private lateinit var systemClock: MockedStatic - private lateinit var downEventCaptor: KArgumentCaptor private lateinit var downActionTouchesArgCaptor: KArgumentCaptor @@ -72,14 +67,6 @@ class RootViewTest { fun setUp() { ReactNativeFeatureFlagsForTests.setUp() - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } - - val ts = SystemClock.uptimeMillis() - systemClock = mockStatic(SystemClock::class.java) - systemClock.`when` { SystemClock.uptimeMillis() }.thenReturn(ts) - catalystInstanceMock = ReactTestHelper.createMockCatalystInstance() reactContext = spy(BridgeReactContext(RuntimeEnvironment.getApplication())) reactContext.initializeWithInstance(catalystInstanceMock) @@ -96,12 +83,6 @@ class RootViewTest { upActionTouchesArgCaptor = argumentCaptor() } - @After - fun tearDown() { - systemClock.close() - arguments.close() - } - @Test fun testTouchEmitter() { val instanceManager: ReactInstanceManager = mock() diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.kt index 4f3a9e629cb301..a49c194f579e5c 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.kt @@ -10,23 +10,20 @@ package com.facebook.react.animated import android.annotation.SuppressLint -import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Callback 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.ReadableMap -import com.facebook.react.bridge.WritableArray -import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.UIManagerModule import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.uimanager.events.RCTEventEmitter +import com.facebook.testutils.shadows.ShadowArguments import kotlin.collections.Map import kotlin.math.abs import org.assertj.core.api.Assertions.assertThat -import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -34,8 +31,6 @@ import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.eq -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.mockito.kotlin.atMost import org.mockito.kotlin.mock import org.mockito.kotlin.reset @@ -44,8 +39,10 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** Tests the animated nodes graph traversal algorithm from {@link NativeAnimatedNodesManager}. */ +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class NativeAnimatedNodeTraversalTest { @@ -55,7 +52,6 @@ class NativeAnimatedNodeTraversalTest { private lateinit var uiManagerMock: UIManagerModule private lateinit var eventDispatcherMock: EventDispatcher private lateinit var nativeAnimatedNodesManager: NativeAnimatedNodesManager - private lateinit var arguments: MockedStatic private fun nextFrameTime(): Long { frameTimeNanos += FRAME_LEN_NANOS @@ -64,10 +60,6 @@ class NativeAnimatedNodeTraversalTest { @Before fun setUp() { - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } - frameTimeNanos = INITIAL_FRAME_TIME_NANOS reactApplicationContextMock = mock() @@ -113,11 +105,6 @@ class NativeAnimatedNodeTraversalTest { nativeAnimatedNodesManager = NativeAnimatedNodesManager(reactApplicationContextMock) } - @After - fun tearDown() { - arguments.close() - } - /** * Generates a simple animated nodes graph and attaches the props node to a given {@param viewTag} * Parameter {@param opacity} is used as a initial value for the "opacity" attribute. diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/events/TouchEventDispatchTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/events/TouchEventDispatchTest.kt index 37294fdb4751f5..be6989654454d3 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/events/TouchEventDispatchTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/fabric/events/TouchEventDispatchTest.kt @@ -11,12 +11,10 @@ import android.util.DisplayMetrics import android.view.MotionEvent import android.view.MotionEvent.PointerCoords import android.view.MotionEvent.PointerProperties -import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReactTestHelper import com.facebook.react.bridge.ReadableMap -import com.facebook.react.bridge.WritableArray import com.facebook.react.bridge.WritableMap import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import com.facebook.react.modules.core.ReactChoreographer @@ -26,6 +24,7 @@ import com.facebook.react.uimanager.events.FabricEventDispatcher import com.facebook.react.uimanager.events.TouchEvent import com.facebook.react.uimanager.events.TouchEventCoalescingKeyHelper import com.facebook.react.uimanager.events.TouchEventType +import com.facebook.testutils.shadows.ShadowArguments import com.facebook.testutils.shadows.ShadowSoLoader import org.assertj.core.api.Assertions.assertThat import org.junit.After @@ -34,8 +33,6 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers.* -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -43,7 +40,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) -@Config(shadows = [ShadowSoLoader::class]) +@Config(shadows = [ShadowSoLoader::class, ShadowArguments::class]) class TouchEventDispatchTest { private val touchEventCoalescingKeyHelper = TouchEventCoalescingKeyHelper() @@ -460,16 +457,12 @@ class TouchEventDispatchTest { private lateinit var eventDispatcher: EventDispatcher private lateinit var eventEmitter: FabricEventEmitter - private lateinit var arguments: MockedStatic private var reactChoreographerOriginal: ReactChoreographer? = null @Before fun setUp() { ReactNativeFeatureFlagsForTests.setUp() - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } val metrics = DisplayMetrics() metrics.xdpi = 1f metrics.ydpi = 1f @@ -488,7 +481,6 @@ class TouchEventDispatchTest { @After fun tearDown() { - arguments.close() ReactChoreographer.overrideInstanceForTest(reactChoreographerOriginal) } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/appstate/AppStateModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/appstate/AppStateModuleTest.kt index bc1dbe0df49217..fb1fd44d672e7e 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/appstate/AppStateModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/appstate/AppStateModuleTest.kt @@ -9,49 +9,39 @@ package com.facebook.react.modules.appstate import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Callback -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.bridge.WritableMap +import com.facebook.testutils.shadows.ShadowArguments import org.assertj.core.api.Assertions.assertThat -import org.junit.After import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith import org.mockito.ArgumentCaptor -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +@Config(shadows = [ShadowArguments::class]) +@RunWith(RobolectricTestRunner::class) class AppStateModuleTest { private lateinit var appStateModule: AppStateModule private lateinit var reactContext: ReactApplicationContext - private lateinit var arguments: MockedStatic @Before fun setUp() { reactContext = mock() appStateModule = AppStateModule(reactContext) - arguments = mockStatic(Arguments::class.java) - arguments.`when`(Arguments::createArray).thenAnswer { JavaOnlyArray() } - arguments.`when`(Arguments::createMap).thenAnswer { JavaOnlyMap() } - // we check whether we have an active react instance before emitting an event, // therefore for the tests we need this returning `true`. whenever(reactContext.hasActiveReactInstance()).thenReturn(true) } - @After - fun tearDown() { - arguments.close() - } - @Test fun testGetCurrentAppState() { val successCallbackMock: Callback = mock() diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.kt index b137fcd9e08784..a95b50fd8fdbf2 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.kt @@ -8,11 +8,9 @@ package com.facebook.react.modules.blob import android.net.Uri -import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReactTestHelper -import com.facebook.react.bridge.WritableMap import java.nio.ByteBuffer import java.util.UUID import kotlin.random.Random @@ -21,8 +19,6 @@ import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -32,13 +28,9 @@ class BlobModuleTest { private lateinit var bytes: ByteArray private lateinit var blobId: String private lateinit var blobModule: BlobModule - private lateinit var arguments: MockedStatic @Before fun prepareModules() { - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } - bytes = ByteArray(120) Random.Default.nextBytes(bytes) @@ -49,7 +41,6 @@ class BlobModuleTest { @After fun cleanUp() { blobModule.remove(blobId) - arguments.close() } @Test diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.kt index 1199227852373b..b6bb1f1d6813c6 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.kt @@ -10,13 +10,12 @@ package com.facebook.react.modules.network -import com.facebook.react.bridge.Arguments 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.bridge.WritableMap import com.facebook.react.common.network.OkHttpCallUtil +import com.facebook.testutils.shadows.ShadowArguments import java.io.InputStream import java.nio.charset.StandardCharsets import okhttp3.Call @@ -46,15 +45,16 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.mockito.kotlin.withSettings import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** Tests [NetworkingModule] */ +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class NetworkingModuleTest { private lateinit var networkingModule: NetworkingModule private lateinit var httpClient: OkHttpClient private lateinit var context: ReactApplicationContext - private lateinit var arguments: MockedStatic private lateinit var okHttpCallUtil: MockedStatic private lateinit var requestBodyUtil: MockedStatic private lateinit var requestArgumentCaptor: KArgumentCaptor @@ -74,10 +74,6 @@ class NetworkingModuleTest { networkingModule = NetworkingModule(context, "", httpClient, null) - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } - okHttpCallUtil = mockStatic(OkHttpCallUtil::class.java) requestArgumentCaptor = argumentCaptor() } @@ -92,7 +88,6 @@ class NetworkingModuleTest { @After fun tearDown() { - arguments.close() okHttpCallUtil.close() } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/ResponseUtilTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/ResponseUtilTest.kt index 7c93c321292c93..db378ec8778905 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/ResponseUtilTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/ResponseUtilTest.kt @@ -8,40 +8,31 @@ package com.facebook.react.modules.network import com.facebook.react.bridge.Arguments -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.bridge.WritableMap +import com.facebook.testutils.shadows.ShadowArguments import java.net.SocketTimeoutException import org.assertj.core.api.Assertions.assertThat -import org.junit.After import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith import org.mockito.ArgumentCaptor -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +@Config(shadows = [ShadowArguments::class]) +@RunWith(RobolectricTestRunner::class) class ResponseUtilTest { private lateinit var reactContext: ReactApplicationContext - private lateinit var arguments: MockedStatic @Before fun setUp() { reactContext = mock() - - arguments = mockStatic(Arguments::class.java) - arguments.`when`(Arguments::createArray).thenAnswer { JavaOnlyArray() } - arguments.`when`(Arguments::createMap).thenAnswer { JavaOnlyMap() } - } - - @After - fun tearDown() { - arguments.close() } @Test 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 a94207f46fcba6..21ad2403546c9b 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 @@ -14,12 +14,10 @@ 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.BridgeReactContext import com.facebook.react.bridge.CatalystInstance import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap -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 @@ -29,6 +27,7 @@ import com.facebook.react.modules.core.JSTimers import com.facebook.react.modules.core.ReactChoreographer import com.facebook.react.modules.core.ReactChoreographer.CallbackType import com.facebook.react.modules.core.TimingModule +import com.facebook.testutils.shadows.ShadowArguments import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -49,6 +48,7 @@ import org.mockito.kotlin.whenever import org.mockito.stubbing.Answer import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config object MockCompat { // Same as Mockito's 'eq()', but works for non-nullable types @@ -63,6 +63,7 @@ object MockCompat { @Suppress("UNCHECKED_CAST") fun uninitialized(): T = null as T } +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class TimingModuleTest { companion object { @@ -75,7 +76,6 @@ class TimingModuleTest { private lateinit var postFrameCallbackHandler: PostFrameCallbackHandler private lateinit var idlePostFrameCallbackHandler: PostFrameCallbackHandler private lateinit var jsTimersMock: JSTimers - private lateinit var arguments: MockedStatic private lateinit var systemClock: MockedStatic private lateinit var reactChoreographerMock: ReactChoreographer @@ -84,9 +84,6 @@ class TimingModuleTest { @Before fun prepareModules() { - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - systemClock = mockStatic(SystemClock::class.java) systemClock .`when` { SystemClock.uptimeMillis() } @@ -147,7 +144,6 @@ class TimingModuleTest { @After fun tearDown() { systemClock.close() - arguments.close() ReactChoreographer.overrideInstanceForTest(reactChoreographerOriginal) } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt index f538b5475ee44a..3c47883f0c48e8 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt @@ -11,33 +11,29 @@ package com.facebook.react.uimanager import android.view.View.OnFocusChangeListener import com.facebook.react.R -import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.BridgeReactContext -import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap -import com.facebook.react.bridge.WritableArray import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import com.facebook.react.views.view.ReactViewGroup import com.facebook.react.views.view.ReactViewManager +import com.facebook.testutils.shadows.ShadowArguments import java.util.Locale import org.assertj.core.api.Assertions -import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.MockedStatic -import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class BaseViewManagerTest { private lateinit var viewManager: BaseViewManager private lateinit var view: ReactViewGroup - private lateinit var arguments: MockedStatic private lateinit var themedReactContext: ThemedReactContext @Before @@ -47,13 +43,6 @@ class BaseViewManagerTest { val context = BridgeReactContext(RuntimeEnvironment.getApplication()) themedReactContext = ThemedReactContext(context, context, null, -1) view = ReactViewGroup(themedReactContext) - arguments = Mockito.mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyArray() } - } - - @After - fun tearDown() { - arguments.close() } @Test diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/OnLayoutEventTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/OnLayoutEventTest.kt index 146fb5a4c6f204..4c49c972c43751 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/OnLayoutEventTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/OnLayoutEventTest.kt @@ -7,32 +7,19 @@ package com.facebook.react.uimanager -import com.facebook.react.common.SystemClock import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import org.assertj.core.api.Assertions.assertThat -import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.MockedStatic -import org.mockito.Mockito.mockStatic import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class OnLayoutEventTest { - private lateinit var systemClock: MockedStatic @Before fun setup() { ReactNativeFeatureFlagsForTests.setUp() - val ts = SystemClock.uptimeMillis() - systemClock = mockStatic(SystemClock::class.java) - systemClock.`when` { SystemClock.uptimeMillis() }.thenReturn(ts) - } - - @After - fun tearDown() { - systemClock.close() } @Test diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.kt index db247c3ccf2e99..9f602000217050 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.kt @@ -19,11 +19,8 @@ import com.facebook.drawee.drawable.ScalingUtils import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.BridgeReactContext import com.facebook.react.bridge.CatalystInstance -import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReactTestHelper.createMockCatalystInstance -import com.facebook.react.bridge.WritableArray -import com.facebook.react.bridge.WritableMap import com.facebook.react.common.ReactConstants import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import com.facebook.react.uimanager.DisplayMetricsHolder @@ -32,6 +29,7 @@ import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.util.RNLog import com.facebook.react.views.imagehelper.ImageSource import com.facebook.soloader.SoLoader +import com.facebook.testutils.shadows.ShadowArguments import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -47,26 +45,24 @@ import org.mockito.kotlin.reset import org.mockito.kotlin.verify import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config /** * Verify that [com.facebook.drawee.drawable.ScalingUtils] properties are being applied correctly by * [ReactImageManager]. */ +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class ReactImagePropertyTest { private lateinit var context: BridgeReactContext private lateinit var catalystInstanceMock: CatalystInstance private lateinit var themeContext: ThemedReactContext - private lateinit var arguments: MockedStatic private lateinit var rnLog: MockedStatic private lateinit var flogMock: MockedStatic @Before fun setup() { - arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createArray() }.thenAnswer { JavaOnlyArray() } - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } rnLog = mockStatic(RNLog::class.java) rnLog.`when` { RNLog.w(any(), anyString()) }.thenAnswer {} @@ -87,7 +83,6 @@ class ReactImagePropertyTest { @After fun teardown() { DisplayMetricsHolder.setWindowDisplayMetrics(null) - arguments.close() rnLog.close() flogMock.close() } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt index 6f6d1070651f7b..7987af9ac76f30 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt @@ -18,18 +18,15 @@ import org.robolectric.annotation.Implements import org.robolectric.shadow.api.Shadow @Implements(Arguments::class) -class ShadowArguments { +object ShadowArguments { + @JvmStatic @Implementation fun createArray(): WritableArray = JavaOnlyArray() - companion object { - @JvmStatic @Implementation fun createArray(): WritableArray = JavaOnlyArray() + @JvmStatic @Implementation fun createMap(): WritableMap = JavaOnlyMap() - @JvmStatic @Implementation fun createMap(): WritableMap = JavaOnlyMap() - - @JvmStatic - @Implementation - fun fromJavaArgs(args: Array): WritableNativeArray = - WritableNativeArray().apply { - (Shadow.extract(this) as ShadowNativeArray).backingArray = JavaOnlyArray.of(*args) - } - } + @JvmStatic + @Implementation + fun fromJavaArgs(args: Array): WritableNativeArray = + WritableNativeArray().apply { + (Shadow.extract(this) as ShadowNativeArray).backingArray = JavaOnlyArray.of(*args) + } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowNativeArray.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowNativeArray.kt index dab1fbb534be22..4a4a105248dfeb 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowNativeArray.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowNativeArray.kt @@ -9,8 +9,6 @@ package com.facebook.testutils.shadows import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.NativeArray -import com.facebook.react.bridge.ReadableNativeArray -import com.facebook.react.bridge.WritableNativeArray import org.robolectric.annotation.Implements import org.robolectric.shadow.api.Shadow @@ -19,20 +17,6 @@ import org.robolectric.shadow.api.Shadow open class ShadowNativeArray { var backingArray: JavaOnlyArray = JavaOnlyArray() - @Deprecated( - "Use ShadowReadableNativeArray", - ReplaceWith( - "ShadowReadableNativeArray", "com.facebook.testutils.shadows.ShadowReadableNativeArray")) - @Implements(ReadableNativeArray::class) - class Readable : ShadowNativeArray() - - @Deprecated( - "Use ShadowWritableNativeArray", - ReplaceWith( - "ShadowWritableNativeArray", "com.facebook.testutils.shadows.ShadowWritableNativeArray")) - @Implements(WritableNativeArray::class) - class Writable : ShadowNativeArray() - companion object { fun getContents(array: NativeArray): List = (Shadow.extract(array) as ShadowNativeArray).backingArray.toArrayList() From db65cb70de9a1e9d16589c51b5ad3da46594bc2b Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Tue, 8 Jul 2025 05:48:00 -0700 Subject: [PATCH 0025/1383] Fix typo in new app screen Summary: TSIA bypass-github-export-checks Changelog: [Internal] Reviewed By: vzaidman Differential Revision: D77928389 fbshipit-source-id: 038d11bed3fbbb96c97b7e2c5727e91973de9078 --- packages/new-app-screen/src/Links.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/new-app-screen/src/Links.js b/packages/new-app-screen/src/Links.js index a8239a7544d643..e4756fad380439 100644 --- a/packages/new-app-screen/src/Links.js +++ b/packages/new-app-screen/src/Links.js @@ -65,7 +65,7 @@ const Links: Array<{ }, { title: 'Community', - description: 'Expore & get help', + description: 'Explore & get help', url: 'https://reactnative.dev/community/overview', }, { From 6dfe59e1df983f8225bb0b711d86f368525015a0 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Tue, 8 Jul 2025 05:58:56 -0700 Subject: [PATCH 0026/1383] Fix missing bundle errors not correctly reported on Android (#52441) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52441 When an error is thrown using `handleHostException` from within the (immediate) execution of a `Task`, the `Task` will capture the error. If those errors are never consumed, the error is just silently swallowed. Instead we should make sure that this is raised outside of the context of a `Task` so the error correctly bubbles up and crashes the app (in release). Changelog: [Internal] Reviewed By: rshest Differential Revision: D77798248 fbshipit-source-id: 41803aba0cace0e364a235501cf34bb946e7ff51 --- .../facebook/react/runtime/ReactHostImpl.kt | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt index 536b0542f78678..d34a194f20ee6f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt @@ -829,13 +829,6 @@ public class ReactHostImpl( null }, executor) - .continueWith({ task: Task -> - // TODO: validate whether errors during startup go through here? - if (task.isFaulted()) { - handleHostException(checkNotNull(task.getError())) - } - null - }) private fun getOrCreateReactContext(): BridgelessReactContext { val method = "getOrCreateReactContext()" @@ -952,9 +945,14 @@ public class ReactHostImpl( }, bgExecutor) - val lifecycleUpdateTask = { task: Task -> + val lifecycleUpdateTask = task@{ task: Task -> + if (task.isFaulted()) { + // handleHostException may throw, so move it outside of the task scheduler + uiExecutor.execute { handleHostException(checkNotNull(task.getError())) } + return@task + } + val result = checkNotNull(task.getResult()) - val reactInstance = result.instance val reactContext = result.context val isReloading = result.isReloading val isManagerResumed = reactLifecycleStateManager.lifecycleState == LifecycleState.RESUMED @@ -991,10 +989,9 @@ public class ReactHostImpl( for (listener in reactInstanceEventListeners) { listener.onReactContextInitialized(reactContext) } - reactInstance } - creationTask.onSuccess(lifecycleUpdateTask, uiExecutor) + creationTask.continueWith(lifecycleUpdateTask, uiExecutor) creationTask.onSuccess({ task -> checkNotNull(task.getResult()).instance }) } } From fc5e33b582c6bfe935eccdedbb335aa086a40bb1 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Tue, 8 Jul 2025 06:10:36 -0700 Subject: [PATCH 0027/1383] Reorganise shared script utils (#52473) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52473 Shared utils that were located in the root of `scripts/` are now colocated closer to their dependencies or moved to `scripts/shared/` — simplifying the root directory layout. Changelog: [Internal] Reviewed By: robhogan Differential Revision: D77873875 fbshipit-source-id: e04dba41a1ef811d32793931033fdfa93afad0cd --- jest/preprocessor.js | 2 +- packages/community-cli-plugin/src/index.js | 2 +- packages/core-cli-utils/src/index.js | 2 +- packages/core-cli-utils/src/public/version.js | 2 +- packages/debugger-shell/src/electron/index.js | 2 +- packages/debugger-shell/src/node/index.js | 2 +- packages/dev-middleware/src/index.js | 2 +- packages/metro-config/src/index.js | 2 +- .../scripts/featureflags/index.js | 2 +- packages/rn-tester/cli.js | 2 +- private/helloworld/cli.js | 2 +- .../config/metro-babel-transformer.js | 2 +- private/react-native-fantom/runner/index.js | 2 +- .../runner/warmup/index.js | 2 +- scripts/build/build.js | 4 +- scripts/build/clean.js | 2 +- scripts/debugger-frontend/sync-and-build.js | 2 +- scripts/e2e/init-project-e2e.js | 6 +-- scripts/e2e/utils/verdaccio.js | 2 +- .../js-api/build-types/buildApiSnapshot.js | 4 +- .../js-api/build-types/buildGeneratedTypes.js | 2 +- scripts/js-api/build-types/index.js | 2 +- .../resolution/resolveTypeInputFile.js | 2 +- .../build-types/resolution/simpleResolve.js | 4 +- scripts/js-api/diff-api-snapshot/index.js | 2 +- scripts/monorepo/print/index.js | 48 +++++++++++++++++- scripts/release-testing/test-e2e-local.js | 2 +- .../releases-ci/__tests__/publish-npm-test.js | 16 +++--- .../publish-updated-packages-test.js | 2 +- scripts/releases-ci/publish-npm.js | 6 +-- .../releases-ci/publish-updated-packages.js | 4 +- .../set-rn-artifacts-version-test.js | 2 +- .../releases/__tests__/set-version-test.js | 2 +- scripts/releases/create-release-commit.js | 2 +- scripts/releases/prepare-ios-prebuilds.js | 2 +- scripts/releases/set-rn-artifacts-version.js | 4 +- scripts/releases/set-version.js | 4 +- .../utils}/__tests__/npm-utils-test.js | 47 +---------------- .../utils}/__tests__/scm-utils-test.js | 0 scripts/{ => releases/utils}/npm-utils.js | 50 +------------------ scripts/{ => releases/utils}/scm-utils.js | 0 .../babelRegister.js} | 4 +- scripts/{ => shared}/consts.js | 2 +- scripts/shared/isGitRepo.js | 35 +++++++++++++ .../monorepo.js => shared/monorepoUtils.js} | 2 +- 45 files changed, 141 insertions(+), 153 deletions(-) rename scripts/{ => releases/utils}/__tests__/npm-utils-test.js (64%) rename scripts/{ => releases/utils}/__tests__/scm-utils-test.js (100%) rename scripts/{ => releases/utils}/npm-utils.js (73%) rename scripts/{ => releases/utils}/scm-utils.js (100%) rename scripts/{babel-register.js => shared/babelRegister.js} (91%) rename scripts/{ => shared}/consts.js (95%) create mode 100644 scripts/shared/isGitRepo.js rename scripts/{utils/monorepo.js => shared/monorepoUtils.js} (98%) diff --git a/jest/preprocessor.js b/jest/preprocessor.js index 7436bac2d09286..dc03ccb3ed02f7 100644 --- a/jest/preprocessor.js +++ b/jest/preprocessor.js @@ -32,7 +32,7 @@ if (process.env.FBSOURCE_ENV === '1') { require('@fb-tools/babel-register'); } else { // Register Babel to allow local packages to be loaded from source - require('../scripts/babel-register').registerForMonorepo(); + require('../scripts/shared/babelRegister').registerForMonorepo(); } const transformer = require('@react-native/metro-babel-transformer'); diff --git a/packages/community-cli-plugin/src/index.js b/packages/community-cli-plugin/src/index.js index 81e2ea61e5e30f..275e475bf5839e 100644 --- a/packages/community-cli-plugin/src/index.js +++ b/packages/community-cli-plugin/src/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (!process.env.BUILD_EXCLUDE_BABEL_REGISTER) { - require('../../../scripts/babel-register').registerForMonorepo(); + require('../../../scripts/shared/babelRegister').registerForMonorepo(); } module.exports = require('./index.flow'); diff --git a/packages/core-cli-utils/src/index.js b/packages/core-cli-utils/src/index.js index f7b2e26c41cc2d..8d76ba451f1b0a 100644 --- a/packages/core-cli-utils/src/index.js +++ b/packages/core-cli-utils/src/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (process.env.BUILD_EXCLUDE_BABEL_REGISTER == null) { - require('../../../scripts/babel-register').registerForMonorepo(); + require('../../../scripts/shared/babelRegister').registerForMonorepo(); } module.exports = require('./index.flow'); diff --git a/packages/core-cli-utils/src/public/version.js b/packages/core-cli-utils/src/public/version.js index f003627058c183..a5aa0613fa52ed 100644 --- a/packages/core-cli-utils/src/public/version.js +++ b/packages/core-cli-utils/src/public/version.js @@ -13,7 +13,7 @@ export type * from './version.flow'; */ if (process.env.BUILD_EXCLUDE_BABEL_REGISTER == null) { - require('../../../../scripts/babel-register').registerForMonorepo(); + require('../../../../scripts/shared/babelRegister').registerForMonorepo(); } module.exports = require('./version.flow'); diff --git a/packages/debugger-shell/src/electron/index.js b/packages/debugger-shell/src/electron/index.js index 66d021e59e147a..f1ddf5733923f6 100644 --- a/packages/debugger-shell/src/electron/index.js +++ b/packages/debugger-shell/src/electron/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (!Boolean(process.env.BUILD_EXCLUDE_BABEL_REGISTER)) { - require('../../../../scripts/babel-register').registerForMonorepo(); + require('../../../../scripts/shared/babelRegister').registerForMonorepo(); } module.exports = require('./index.flow'); diff --git a/packages/debugger-shell/src/node/index.js b/packages/debugger-shell/src/node/index.js index 17be3f3de43f78..b30f2d626f93a8 100644 --- a/packages/debugger-shell/src/node/index.js +++ b/packages/debugger-shell/src/node/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (!process.env.BUILD_EXCLUDE_BABEL_REGISTER) { - require('../../../../scripts/babel-register').registerForMonorepo(); + require('../../../../scripts/shared/babelRegister').registerForMonorepo(); } export * from './index.flow'; diff --git a/packages/dev-middleware/src/index.js b/packages/dev-middleware/src/index.js index c94a6211499c7a..900adaec2c4add 100644 --- a/packages/dev-middleware/src/index.js +++ b/packages/dev-middleware/src/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (!process.env.BUILD_EXCLUDE_BABEL_REGISTER) { - require('../../../scripts/babel-register').registerForMonorepo(); + require('../../../scripts/shared/babelRegister').registerForMonorepo(); } export * from './index.flow'; diff --git a/packages/metro-config/src/index.js b/packages/metro-config/src/index.js index 81e2ea61e5e30f..275e475bf5839e 100644 --- a/packages/metro-config/src/index.js +++ b/packages/metro-config/src/index.js @@ -13,7 +13,7 @@ export type * from './index.flow'; */ if (!process.env.BUILD_EXCLUDE_BABEL_REGISTER) { - require('../../../scripts/babel-register').registerForMonorepo(); + require('../../../scripts/shared/babelRegister').registerForMonorepo(); } module.exports = require('./index.flow'); diff --git a/packages/react-native/scripts/featureflags/index.js b/packages/react-native/scripts/featureflags/index.js index c88a46560de3a3..a8f2f7e8a5a176 100644 --- a/packages/react-native/scripts/featureflags/index.js +++ b/packages/react-native/scripts/featureflags/index.js @@ -9,7 +9,7 @@ */ if (require.main === module) { - require('../../../../scripts/babel-register').registerForMonorepo(); + require('../../../../scripts/shared/babelRegister').registerForMonorepo(); let command; diff --git a/packages/rn-tester/cli.js b/packages/rn-tester/cli.js index 3dfd0fbc85338f..72cfc6f7c13960 100644 --- a/packages/rn-tester/cli.js +++ b/packages/rn-tester/cli.js @@ -31,7 +31,7 @@ function injectCoreCLIUtilsRuntimePatch() { if (process.env.BUILD_EXCLUDE_BABEL_REGISTER == null) { // $FlowFixMe[cannot-resolve-module] - require('../../scripts/babel-register').registerForMonorepo(); + require('../../scripts/shared/babelRegister').registerForMonorepo(); } injectCoreCLIUtilsRuntimePatch(); diff --git a/private/helloworld/cli.js b/private/helloworld/cli.js index 3dfd0fbc85338f..72cfc6f7c13960 100644 --- a/private/helloworld/cli.js +++ b/private/helloworld/cli.js @@ -31,7 +31,7 @@ function injectCoreCLIUtilsRuntimePatch() { if (process.env.BUILD_EXCLUDE_BABEL_REGISTER == null) { // $FlowFixMe[cannot-resolve-module] - require('../../scripts/babel-register').registerForMonorepo(); + require('../../scripts/shared/babelRegister').registerForMonorepo(); } injectCoreCLIUtilsRuntimePatch(); diff --git a/private/react-native-fantom/config/metro-babel-transformer.js b/private/react-native-fantom/config/metro-babel-transformer.js index 9d6b82df66cc16..51593b0b4ef61f 100644 --- a/private/react-native-fantom/config/metro-babel-transformer.js +++ b/private/react-native-fantom/config/metro-babel-transformer.js @@ -10,5 +10,5 @@ 'use strict'; -require('../../../scripts/babel-register').registerForMonorepo(); +require('../../../scripts/shared/babelRegister').registerForMonorepo(); module.exports = require('@react-native/metro-babel-transformer'); diff --git a/private/react-native-fantom/runner/index.js b/private/react-native-fantom/runner/index.js index a4bf32ccd4cda0..8486d6a2004866 100644 --- a/private/react-native-fantom/runner/index.js +++ b/private/react-native-fantom/runner/index.js @@ -8,6 +8,6 @@ * @format */ -require('../../../scripts/babel-register').registerForMonorepo(); +require('../../../scripts/shared/babelRegister').registerForMonorepo(); module.exports = require('./runner'); diff --git a/private/react-native-fantom/runner/warmup/index.js b/private/react-native-fantom/runner/warmup/index.js index ef652c3df5d644..83bbd4da75896f 100644 --- a/private/react-native-fantom/runner/warmup/index.js +++ b/private/react-native-fantom/runner/warmup/index.js @@ -8,6 +8,6 @@ * @format */ -require('../../../../scripts/babel-register').registerForMonorepo(); +require('../../../../scripts/shared/babelRegister').registerForMonorepo(); module.exports = require('./warmup'); diff --git a/scripts/build/build.js b/scripts/build/build.js index 884e9d9115eb7f..d44d215ab24728 100644 --- a/scripts/build/build.js +++ b/scripts/build/build.js @@ -8,9 +8,9 @@ * @format */ -require('../babel-register').registerForScript(); +require('../shared/babelRegister').registerForScript(); -const {PACKAGES_DIR, REPO_ROOT} = require('../consts'); +const {PACKAGES_DIR, REPO_ROOT} = require('../shared/consts'); const { buildConfig, getBabelConfig, diff --git a/scripts/build/clean.js b/scripts/build/clean.js index a51413a3659668..13d17b6b9fbd11 100644 --- a/scripts/build/clean.js +++ b/scripts/build/clean.js @@ -8,7 +8,7 @@ * @format */ -require('../babel-register').registerForScript(); +require('../shared/babelRegister').registerForScript(); const {BUILD_DIR, PACKAGES_DIR} = require('./build'); const {buildConfig} = require('./config'); diff --git a/scripts/debugger-frontend/sync-and-build.js b/scripts/debugger-frontend/sync-and-build.js index ccbf62222c6581..53829b92d2c7dc 100644 --- a/scripts/debugger-frontend/sync-and-build.js +++ b/scripts/debugger-frontend/sync-and-build.js @@ -8,7 +8,7 @@ * @format */ -const {PACKAGES_DIR} = require('../consts'); +const {PACKAGES_DIR} = require('../shared/consts'); // $FlowFixMe[untyped-import]: TODO type ansi-styles const ansiStyles = require('ansi-styles'); const {execSync, spawnSync} = require('child_process'); diff --git a/scripts/e2e/init-project-e2e.js b/scripts/e2e/init-project-e2e.js index 2f77e9f8c76dd6..c807038a9e229d 100644 --- a/scripts/e2e/init-project-e2e.js +++ b/scripts/e2e/init-project-e2e.js @@ -10,10 +10,10 @@ 'use strict'; -/*:: import type {ProjectInfo} from '../utils/monorepo'; */ +/*:: import type {ProjectInfo} from '../shared/monorepoUtils'; */ -const {PRIVATE_DIR, REPO_ROOT} = require('../consts'); -const {getPackages} = require('../utils/monorepo'); +const {PRIVATE_DIR, REPO_ROOT} = require('../shared/consts'); +const {getPackages} = require('../shared/monorepoUtils'); const {retry} = require('./utils/retry'); const { VERDACCIO_SERVER_URL, diff --git a/scripts/e2e/utils/verdaccio.js b/scripts/e2e/utils/verdaccio.js index 156e283fe9e2e5..f287a653dbf1eb 100644 --- a/scripts/e2e/utils/verdaccio.js +++ b/scripts/e2e/utils/verdaccio.js @@ -10,7 +10,7 @@ 'use strict'; -const {REPO_ROOT} = require('../../consts'); +const {REPO_ROOT} = require('../../shared/consts'); const {execSync, spawn} = require('child_process'); const fs = require('fs'); const path = require('path'); diff --git a/scripts/js-api/build-types/buildApiSnapshot.js b/scripts/js-api/build-types/buildApiSnapshot.js index eb9af6dce8771d..c0e75fec1399ff 100644 --- a/scripts/js-api/build-types/buildApiSnapshot.js +++ b/scripts/js-api/build-types/buildApiSnapshot.js @@ -11,8 +11,8 @@ import type {PluginObj} from '@babel/core'; -const {PACKAGES_DIR, REACT_NATIVE_PACKAGE_DIR} = require('../../consts'); -const {isGitRepo} = require('../../scm-utils'); +const {PACKAGES_DIR, REACT_NATIVE_PACKAGE_DIR} = require('../../shared/consts'); +const isGitRepo = require('../../shared/isGitRepo'); const {API_EXTRACTOR_CONFIG_FILE, TYPES_OUTPUT_DIR} = require('../config'); const apiSnapshotTemplate = require('./templates/ReactNativeApi.d.ts-template.js'); const applyBabelTransformsSeq = require('./utils/applyBabelTransformsSeq'); diff --git a/scripts/js-api/build-types/buildGeneratedTypes.js b/scripts/js-api/build-types/buildGeneratedTypes.js index 404f14c46290ca..c4572a23ff7574 100644 --- a/scripts/js-api/build-types/buildGeneratedTypes.js +++ b/scripts/js-api/build-types/buildGeneratedTypes.js @@ -8,7 +8,7 @@ * @format */ -const {PACKAGES_DIR, REPO_ROOT} = require('../../consts'); +const {PACKAGES_DIR, REPO_ROOT} = require('../../shared/consts'); const {ENTRY_POINT, IGNORE_PATTERNS, TYPES_OUTPUT_DIR} = require('../config'); const getRequireStack = require('./resolution/getRequireStack'); const translatedModuleTemplate = require('./templates/translatedModule.d.ts-template'); diff --git a/scripts/js-api/build-types/index.js b/scripts/js-api/build-types/index.js index 0a99a33bffe0a0..757fe58663a8b8 100644 --- a/scripts/js-api/build-types/index.js +++ b/scripts/js-api/build-types/index.js @@ -8,7 +8,7 @@ * @format */ -require('../../babel-register').registerForScript(); +require('../../shared/babelRegister').registerForScript(); const buildApiSnapshot = require('./buildApiSnapshot'); const buildGeneratedTypes = require('./buildGeneratedTypes'); diff --git a/scripts/js-api/build-types/resolution/resolveTypeInputFile.js b/scripts/js-api/build-types/resolution/resolveTypeInputFile.js index f1237ca5d2d7fb..bd965c7c79ae33 100644 --- a/scripts/js-api/build-types/resolution/resolveTypeInputFile.js +++ b/scripts/js-api/build-types/resolution/resolveTypeInputFile.js @@ -8,7 +8,7 @@ * @format */ -const {REPO_ROOT} = require('../../../consts'); +const {REPO_ROOT} = require('../../../shared/consts'); const debug = require('debug')('build-types:resolution'); const fs = require('fs'); const path = require('path'); diff --git a/scripts/js-api/build-types/resolution/simpleResolve.js b/scripts/js-api/build-types/resolution/simpleResolve.js index 33e748af3aedf3..a571f04a6424a0 100644 --- a/scripts/js-api/build-types/resolution/simpleResolve.js +++ b/scripts/js-api/build-types/resolution/simpleResolve.js @@ -8,8 +8,8 @@ * @format */ -const {PACKAGES_DIR} = require('../../../consts'); -const {getPackages} = require('../../../utils/monorepo'); +const {PACKAGES_DIR} = require('../../../shared/consts'); +const {getPackages} = require('../../../shared/monorepoUtils'); const {existsSync} = require('fs'); const path = require('path'); diff --git a/scripts/js-api/diff-api-snapshot/index.js b/scripts/js-api/diff-api-snapshot/index.js index 777d281461a5a6..4c9f3fc6c0edc1 100644 --- a/scripts/js-api/diff-api-snapshot/index.js +++ b/scripts/js-api/diff-api-snapshot/index.js @@ -9,7 +9,7 @@ * @oncall react_native */ -require('../../babel-register').registerForScript(); +require('../../shared/babelRegister').registerForScript(); const {diffApiSnapshot} = require('./diffApiSnapshot'); const fs = require('fs'); diff --git a/scripts/monorepo/print/index.js b/scripts/monorepo/print/index.js index 1fc7dd10dc7aa1..7e31f3e98e6d40 100644 --- a/scripts/monorepo/print/index.js +++ b/scripts/monorepo/print/index.js @@ -8,7 +8,6 @@ * @noflow */ -const {getVersionsBySpec} = require('../../npm-utils'); const {getPackages} = require('../../utils/monorepo'); const {exit} = require('shelljs'); const yargs = require('yargs'); @@ -42,6 +41,53 @@ function reversePatchComp(semverA, semverB) { return patchB - patchA; } +/** + * `packageName`: name of npm package + * `spec`: spec range ex. '^0.72.0' + * + * Return an array of versions of the specified spec range or throw an error + */ +function getVersionsBySpec( + packageName /*: string */, + spec /*: string */, +) /*: Array */ { + const npmString = `npm view ${packageName}@'${spec}' version --json`; + const result = exec(npmString, {silent: true}); + + if (result.code) { + // Special handling if no such package spec exists + if (result.stderr.includes('npm ERR! code E404')) { + /** + * npm ERR! code E404 + * npm ERR! 404 No match found for version ^0.72.0 + * npm ERR! 404 + * npm ERR! 404 '@react-native/community-cli-plugin@^0.72.0' is not in this registry. + * npm ERR! 404 + * npm ERR! 404 Note that you can also install from a + * npm ERR! 404 tarball, folder, http url, or git url. + * { + * "error": { + * "code": "E404", + * "summary": "No match found for version ^0.72.0", + * "detail": "\n '@react-native/community-cli-plugin@^0.72.0' is not in this registry.\n\nNote that you can also install from a\ntarball, folder, http url, or git url." + * } + * } + */ + const error = JSON.parse( + result.stderr + .split('\n') + .filter(line => !line.includes('npm ERR')) + .join(''), + ).error; + throw new Error(error.summary); + } else { + throw new Error(`Failed: ${npmString}`); + } + } + const versions = JSON.parse(result.stdout.trim()); + return !Array.isArray(versions) ? [versions] : versions; +} + async function main() { const data = []; const packages = await getPackages({ diff --git a/scripts/release-testing/test-e2e-local.js b/scripts/release-testing/test-e2e-local.js index 5749c19ba640b8..9a0768bb474659 100644 --- a/scripts/release-testing/test-e2e-local.js +++ b/scripts/release-testing/test-e2e-local.js @@ -17,8 +17,8 @@ * and to make it more accessible for other devs to play around with. */ -const {REPO_ROOT} = require('../consts'); const {initNewProjectFromSource} = require('../e2e/init-project-e2e'); +const {REPO_ROOT} = require('../shared/consts'); const { checkPackagerRunning, launchPackagerInSeparateWindow, diff --git a/scripts/releases-ci/__tests__/publish-npm-test.js b/scripts/releases-ci/__tests__/publish-npm-test.js index d289a509d97106..0ab84e5536dedb 100644 --- a/scripts/releases-ci/__tests__/publish-npm-test.js +++ b/scripts/releases-ci/__tests__/publish-npm-test.js @@ -21,7 +21,7 @@ const getNpmInfoMock = jest.fn(); const generateAndroidArtifactsMock = jest.fn(); const getPackagesMock = jest.fn(); -const {REPO_ROOT} = require('../../consts'); +const {REPO_ROOT} = require('../../shared/consts'); const {publishNpm} = require('../publish-npm'); const path = require('path'); @@ -33,7 +33,7 @@ describe('publish-npm', () => { .mock('shelljs', () => ({ exec: execMock, })) - .mock('./../../scm-utils', () => ({ + .mock('../../releases/utils/scm-utils', () => ({ exitIfNotOnGit: command => command(), getCurrentCommit: () => 'currentco_mmit', isTaggedLatest: isTaggedLatestMock, @@ -49,8 +49,8 @@ describe('publish-npm', () => { .mock('../../releases/set-rn-artifacts-version', () => ({ updateReactNativeArtifacts: updateReactNativeArtifactsMock, })) - .mock('../../npm-utils', () => ({ - ...jest.requireActual('../../npm-utils'), + .mock('../../releases/utils/npm-utils', () => ({ + ...jest.requireActual('../../releases/utils/npm-utils'), publishPackage: publishPackageMock, getNpmInfo: getNpmInfoMock, })); @@ -78,7 +78,7 @@ describe('publish-npm', () => { it('should fail when invalid build type is passed', async () => { // Call actual function // $FlowExpectedError[underconstrained-implicit-instantiation] - const npmUtils = jest.requireActual('../../npm-utils'); + const npmUtils = jest.requireActual('../../releases/utils/npm-utils'); getNpmInfoMock.mockImplementation(npmUtils.getNpmInfo); await expect(async () => { @@ -117,14 +117,14 @@ describe('publish-npm', () => { describe("publishNpm('nightly')", () => { beforeAll(() => { - jest.mock('../../utils/monorepo', () => ({ - ...jest.requireActual('../../utils/monorepo'), + jest.mock('../../shared/monorepoUtils', () => ({ + ...jest.requireActual('../../shared/monorepoUtils'), getPackages: getPackagesMock, })); }); afterAll(() => { - jest.unmock('../../utils/monorepo'); + jest.unmock('../../shared/monorepoUtils'); }); it('should publish', async () => { diff --git a/scripts/releases-ci/__tests__/publish-updated-packages-test.js b/scripts/releases-ci/__tests__/publish-updated-packages-test.js index f927fda5c16257..25ffcf2c35851e 100644 --- a/scripts/releases-ci/__tests__/publish-updated-packages-test.js +++ b/scripts/releases-ci/__tests__/publish-updated-packages-test.js @@ -20,7 +20,7 @@ const fetchMock = jest.fn(); jest.mock('child_process', () => ({execSync})); jest.mock('shelljs', () => ({exec: execMock})); -jest.mock('../../utils/monorepo', () => ({ +jest.mock('../../shared/monorepoUtils', () => ({ getPackages: getPackagesMock, })); // $FlowIgnore[cannot-write] diff --git a/scripts/releases-ci/publish-npm.js b/scripts/releases-ci/publish-npm.js index 5bc22c84e97ace..9e01175ac1d67b 100755 --- a/scripts/releases-ci/publish-npm.js +++ b/scripts/releases-ci/publish-npm.js @@ -14,17 +14,17 @@ import type {BuildType} from '../releases/utils/version-utils'; */ -const {REPO_ROOT} = require('../consts'); -const {getNpmInfo, publishPackage} = require('../npm-utils'); const { updateReactNativeArtifacts, } = require('../releases/set-rn-artifacts-version'); const {setVersion} = require('../releases/set-version'); +const {getNpmInfo, publishPackage} = require('../releases/utils/npm-utils'); const { publishAndroidArtifactsToMaven, publishExternalArtifactsToMaven, } = require('../releases/utils/release-utils'); -const {getPackages} = require('../utils/monorepo'); +const {REPO_ROOT} = require('../shared/consts'); +const {getPackages} = require('../shared/monorepoUtils'); const path = require('path'); const yargs = require('yargs'); diff --git a/scripts/releases-ci/publish-updated-packages.js b/scripts/releases-ci/publish-updated-packages.js index 3b6701df304e89..2a9e7c18173af4 100644 --- a/scripts/releases-ci/publish-updated-packages.js +++ b/scripts/releases-ci/publish-updated-packages.js @@ -8,8 +8,8 @@ * @format */ -const {publishPackage} = require('../npm-utils'); -const {getPackages} = require('../utils/monorepo'); +const {publishPackage} = require('../releases/utils/npm-utils'); +const {getPackages} = require('../shared/monorepoUtils'); const {execSync} = require('child_process'); const {parseArgs} = require('util'); diff --git a/scripts/releases/__tests__/set-rn-artifacts-version-test.js b/scripts/releases/__tests__/set-rn-artifacts-version-test.js index 0d1e332a6c908d..109bfff0a4bc90 100644 --- a/scripts/releases/__tests__/set-rn-artifacts-version-test.js +++ b/scripts/releases/__tests__/set-rn-artifacts-version-test.js @@ -20,7 +20,7 @@ jest.mock('fs', () => ({ }, })); -const {REPO_ROOT} = require('../../consts'); +const {REPO_ROOT} = require('../../shared/consts'); const {updateReactNativeArtifacts} = require('../set-rn-artifacts-version'); const path = require('path'); diff --git a/scripts/releases/__tests__/set-version-test.js b/scripts/releases/__tests__/set-version-test.js index 01d6ec976fe77a..fcc18077e805c1 100644 --- a/scripts/releases/__tests__/set-version-test.js +++ b/scripts/releases/__tests__/set-version-test.js @@ -11,7 +11,7 @@ const {setVersion} = require('../set-version'); const path = require('path'); -jest.mock('../../consts', () => ({ +jest.mock('../../shared/consts', () => ({ REPO_ROOT: path.join(__dirname, '__fixtures__', 'set-version'), PACKAGES_DIR: path.join(__dirname, '__fixtures__', 'set-version', 'packages'), REACT_NATIVE_PACKAGE_DIR: path.join( diff --git a/scripts/releases/create-release-commit.js b/scripts/releases/create-release-commit.js index 7d85a7832532d3..50d2f8a8acd99d 100644 --- a/scripts/releases/create-release-commit.js +++ b/scripts/releases/create-release-commit.js @@ -9,7 +9,7 @@ */ const {setVersion} = require('../releases/set-version'); -const {getBranchName} = require('../scm-utils'); +const {getBranchName} = require('../releases/utils/scm-utils'); const {parseVersion} = require('./utils/version-utils'); const {execSync} = require('child_process'); const yargs = require('yargs'); diff --git a/scripts/releases/prepare-ios-prebuilds.js b/scripts/releases/prepare-ios-prebuilds.js index e4d1ebcb888afb..532369817e8924 100644 --- a/scripts/releases/prepare-ios-prebuilds.js +++ b/scripts/releases/prepare-ios-prebuilds.js @@ -16,7 +16,7 @@ const {setupDependencies} = require('./ios-prebuild/setupDependencies'); const {createSwiftPackageFile} = require('./ios-prebuild/swift-package'); const path = require('path'); -require('../babel-register').registerForScript(); +require('../shared/babelRegister').registerForScript(); const THIRD_PARTY_PATH = 'packages/react-native/third-party'; const BUILD_DESTINATION = '.build'; diff --git a/scripts/releases/set-rn-artifacts-version.js b/scripts/releases/set-rn-artifacts-version.js index bb1a2465ff025c..2b1cd29573c481 100755 --- a/scripts/releases/set-rn-artifacts-version.js +++ b/scripts/releases/set-rn-artifacts-version.js @@ -12,8 +12,8 @@ import type {BuildType, Version} from './utils/version-utils'; */ -const {REPO_ROOT} = require('../consts'); -const {getNpmInfo} = require('../npm-utils'); +const {getNpmInfo} = require('../releases/utils/npm-utils'); +const {REPO_ROOT} = require('../shared/consts'); const {parseVersion, validateBuildType} = require('./utils/version-utils'); const {promises: fs} = require('fs'); const path = require('path'); diff --git a/scripts/releases/set-version.js b/scripts/releases/set-version.js index 65f41468474acd..33f5054a0948d2 100644 --- a/scripts/releases/set-version.js +++ b/scripts/releases/set-version.js @@ -11,14 +11,14 @@ 'use strict'; /*:: -import type {PackageJson} from '../utils/monorepo'; +import type {PackageJson} from '../shared/monorepoUtils'; */ const { getPackages, getWorkspaceRoot, updatePackageJson, -} = require('../utils/monorepo'); +} = require('../shared/monorepoUtils'); const {updateReactNativeArtifacts} = require('./set-rn-artifacts-version'); const {parseArgs} = require('util'); diff --git a/scripts/__tests__/npm-utils-test.js b/scripts/releases/utils/__tests__/npm-utils-test.js similarity index 64% rename from scripts/__tests__/npm-utils-test.js rename to scripts/releases/utils/__tests__/npm-utils-test.js index ce52428a1595b0..c0de672328b5de 100644 --- a/scripts/__tests__/npm-utils-test.js +++ b/scripts/releases/utils/__tests__/npm-utils-test.js @@ -8,7 +8,7 @@ * @format */ -const {getNpmInfo, getVersionsBySpec, publishPackage} = require('../npm-utils'); +const {getNpmInfo, publishPackage} = require('../npm-utils'); const execMock = jest.fn(); const getCurrentCommitMock = jest.fn(); @@ -98,49 +98,4 @@ describe('npm-utils', () => { }); }); }); - - describe('getVersionsBySpec', () => { - it('should return array when single version returned', () => { - execMock.mockImplementationOnce(() => ({code: 0, stdout: '"0.72.0" \n'})); - - const versions = getVersionsBySpec('mypackage', '^0.72.0'); - expect(versions).toEqual(['0.72.0']); - }); - - it('should return array of versions', () => { - execMock.mockImplementationOnce(() => ({ - code: 0, - stdout: '[\n"0.73.0",\n"0.73.1"\n]\n', - })); - - const versions = getVersionsBySpec('mypackage', '^0.73.0'); - expect(versions).toEqual(['0.73.0', '0.73.1']); - }); - - it('should return error summary if E404', () => { - const error = - `npm ERR! code E404\n` + - `npm ERR! 404 No match found for version ^0.72.0\n` + - `npm ERR! 404\n` + - `npm ERR! 404 '@react-native/community-cli-plugin@^0.72.0' is not in this registry.\n` + - `npm ERR! 404\n` + - `npm ERR! 404 Note that you can also install from a\n` + - `npm ERR! 404 tarball, folder, http url, or git url.\n` + - `{\n` + - ` "error": {\n` + - ` "code": "E404",\n` + - ` "summary": "No match found for version ^0.72.0",\n` + - ` "detail": "\n '@react-native/community-cli-plugin@^0.72.0' is not in this registry.\n\nNote that you can also install from a\ntarball, folder, http url, or git url."\n` + - ` }\n` + - `}\n`; - execMock.mockImplementationOnce(() => ({ - code: 1, - stderr: error, - })); - - expect(() => { - getVersionsBySpec('mypackage', '^0.72.0'); - }).toThrow('No match found for version ^0.72.0'); - }); - }); }); diff --git a/scripts/__tests__/scm-utils-test.js b/scripts/releases/utils/__tests__/scm-utils-test.js similarity index 100% rename from scripts/__tests__/scm-utils-test.js rename to scripts/releases/utils/__tests__/scm-utils-test.js diff --git a/scripts/npm-utils.js b/scripts/releases/utils/npm-utils.js similarity index 73% rename from scripts/npm-utils.js rename to scripts/releases/utils/npm-utils.js index 5b460513b3d239..9a127b395c327b 100644 --- a/scripts/npm-utils.js +++ b/scripts/releases/utils/npm-utils.js @@ -10,12 +10,12 @@ 'use strict'; -const {parseVersion} = require('./releases/utils/version-utils'); const { exitIfNotOnGit, getCurrentCommit, isTaggedLatest, } = require('./scm-utils'); +const {parseVersion} = require('./version-utils'); const {exec} = require('shelljs'); /*:: @@ -173,55 +173,7 @@ function getPackageVersionStrByTag( return result.stdout.trim(); } -/** - * `packageName`: name of npm package - * `spec`: spec range ex. '^0.72.0' - * - * Return an array of versions of the specified spec range or throw an error - */ -function getVersionsBySpec( - packageName /*: string */, - spec /*: string */, -) /*: Array */ { - const npmString = `npm view ${packageName}@'${spec}' version --json`; - const result = exec(npmString, {silent: true}); - - if (result.code) { - // Special handling if no such package spec exists - if (result.stderr.includes('npm ERR! code E404')) { - /** - * npm ERR! code E404 - * npm ERR! 404 No match found for version ^0.72.0 - * npm ERR! 404 - * npm ERR! 404 '@react-native/community-cli-plugin@^0.72.0' is not in this registry. - * npm ERR! 404 - * npm ERR! 404 Note that you can also install from a - * npm ERR! 404 tarball, folder, http url, or git url. - * { - * "error": { - * "code": "E404", - * "summary": "No match found for version ^0.72.0", - * "detail": "\n '@react-native/community-cli-plugin@^0.72.0' is not in this registry.\n\nNote that you can also install from a\ntarball, folder, http url, or git url." - * } - * } - */ - const error = JSON.parse( - result.stderr - .split('\n') - .filter(line => !line.includes('npm ERR')) - .join(''), - ).error; - throw new Error(error.summary); - } else { - throw new Error(`Failed: ${npmString}`); - } - } - const versions = JSON.parse(result.stdout.trim()); - return !Array.isArray(versions) ? [versions] : versions; -} - module.exports = { getNpmInfo, - getVersionsBySpec, publishPackage, }; diff --git a/scripts/scm-utils.js b/scripts/releases/utils/scm-utils.js similarity index 100% rename from scripts/scm-utils.js rename to scripts/releases/utils/scm-utils.js diff --git a/scripts/babel-register.js b/scripts/shared/babelRegister.js similarity index 91% rename from scripts/babel-register.js rename to scripts/shared/babelRegister.js index 64439cd6355387..876cb367fe242a 100644 --- a/scripts/babel-register.js +++ b/scripts/shared/babelRegister.js @@ -28,7 +28,7 @@ let isRegisteredForMonorepo = false; * ```js * // Place in a package entry point * if (!process.env.BUILD_EXCLUDE_BABEL_REGISTER) { - * require('../../../scripts/babel-register').registerForMonorepo(); + * require('../../../scripts/shared/babelRegister').registerForMonorepo(); * } * ``` */ @@ -57,7 +57,7 @@ function registerForMonorepo() { * * ```js * // Place in a script entry point - * require('../babel-register').registerForScript(); + * require('../shared/babelRegister').registerForScript(); * ``` */ function registerForScript() { diff --git a/scripts/consts.js b/scripts/shared/consts.js similarity index 95% rename from scripts/consts.js rename to scripts/shared/consts.js index a9a07faedff6a8..09801410ef52fe 100644 --- a/scripts/consts.js +++ b/scripts/shared/consts.js @@ -13,7 +13,7 @@ const path = require('path'); /** * The absolute path to the repo root. */ -const REPO_ROOT /*: string */ = path.resolve(__dirname, '..'); +const REPO_ROOT /*: string */ = path.resolve(__dirname, '../..'); /** * The absolute path to the packages directory (note: this directory alone may diff --git a/scripts/shared/isGitRepo.js b/scripts/shared/isGitRepo.js new file mode 100644 index 00000000000000..0e4f6d2ade12f9 --- /dev/null +++ b/scripts/shared/isGitRepo.js @@ -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. + * + * @flow strict-local + * @format + */ + +'use strict'; + +const childProcess = require('child_process'); + +/*:: +type Commit = string; +*/ + +function isGitRepo() /*: boolean */ { + try { + const result = childProcess.execSync( + 'git rev-parse --is-inside-work-tree', + { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + }, + ); + return result.trim() === 'true'; + } catch (error) { + console.error(`Failed to check git repository status: ${error}`); + } + return false; +} + +module.exports = isGitRepo; diff --git a/scripts/utils/monorepo.js b/scripts/shared/monorepoUtils.js similarity index 98% rename from scripts/utils/monorepo.js rename to scripts/shared/monorepoUtils.js index 266e13594e98cb..6fc9a9d9e1edc7 100644 --- a/scripts/utils/monorepo.js +++ b/scripts/shared/monorepoUtils.js @@ -8,7 +8,7 @@ * @format */ -const {REPO_ROOT} = require('../consts'); +const {REPO_ROOT} = require('./consts'); const {promises: fs} = require('fs'); const glob = require('glob'); const path = require('path'); From 5baf1e6d00a3ca0edb9a95e543fbdedc47ece3d6 Mon Sep 17 00:00:00 2001 From: Fabrizio Cucci Date: Tue, 8 Jul 2025 09:24:15 -0700 Subject: [PATCH 0028/1383] Fix all workflows to use node 22.14.0 (#52491) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52491 We hit this error when trying to release 0.81.0 (see [action run](https://github.com/facebook/react-native/actions/runs/16147471618/job/45570030039)): > error react-native/metro-babel-transformer@0.81.0-main: The engine "node" is incompatible with this module. Expected version ">= 22.14.0". Got "20.19.2" This should fix the issue. Changelog: [Internal] Reviewed By: motiz88, cortinico Differential Revision: D77938906 fbshipit-source-id: 48ca412f05d99459c4386499330584d9e560408b --- .github/actions/setup-node/action.yml | 2 +- .github/actions/yarn-install/action.yml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/actions/setup-node/action.yml b/.github/actions/setup-node/action.yml index b22fb3e822dbca..d076bf4acb8bc5 100644 --- a/.github/actions/setup-node/action.yml +++ b/.github/actions/setup-node/action.yml @@ -4,7 +4,7 @@ inputs: node-version: description: 'The node.js version to use' required: false - default: '22' + default: '22.14.0' runs: using: "composite" steps: diff --git a/.github/actions/yarn-install/action.yml b/.github/actions/yarn-install/action.yml index cdb4a85c899ec6..7f7c7bd2bc9293 100644 --- a/.github/actions/yarn-install/action.yml +++ b/.github/actions/yarn-install/action.yml @@ -2,6 +2,8 @@ name: yarn-install runs: using: composite steps: + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Install dependencies shell: bash run: | From df6ba3f1555607c379e33b5201ad4551cc82638b Mon Sep 17 00:00:00 2001 From: Marco Wang Date: Tue, 8 Jul 2025 12:50:53 -0700 Subject: [PATCH 0029/1383] Pre-suppress errors for boolean literals for xplat js (#52482) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52482 Changelog: [Internal] Reviewed By: panagosg7 Differential Revision: D77915593 fbshipit-source-id: 9238b89e92410cea350c6057044167727de3601a --- .../Libraries/Core/ExceptionsManager.js | 2 ++ .../Interaction/InteractionManager.js | 4 +++ .../Libraries/Interaction/TaskQueue.js | 14 ++++++++ .../Libraries/Network/XMLHttpRequest.js | 2 ++ .../Utilities/createPerformanceLogger.js | 32 +++++++++++++++++++ .../virtualized-lists/Lists/FillRateHelper.js | 8 +++++ .../Lists/VirtualizedList.js | 2 ++ 7 files changed, 64 insertions(+) diff --git a/packages/react-native/Libraries/Core/ExceptionsManager.js b/packages/react-native/Libraries/Core/ExceptionsManager.js index cbf854cdbaf25e..413fc15dcfcd28 100644 --- a/packages/react-native/Libraries/Core/ExceptionsManager.js +++ b/packages/react-native/Libraries/Core/ExceptionsManager.js @@ -242,6 +242,8 @@ function reactConsoleErrorHandler(...args) { if (__DEV__) { // If we're not reporting to the console in reportException, // we need to report it as a console.error here. + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (!reportToConsole) { require('../LogBox/LogBox').default.addConsoleLog('error', ...args); } diff --git a/packages/react-native/Libraries/Interaction/InteractionManager.js b/packages/react-native/Libraries/Interaction/InteractionManager.js index 70fc3d728f8d17..f72d37f54e83de 100644 --- a/packages/react-native/Libraries/Interaction/InteractionManager.js +++ b/packages/react-native/Libraries/Interaction/InteractionManager.js @@ -73,6 +73,8 @@ const InteractionManagerImpl = { * Notify manager that an interaction has started. */ createInteractionHandle(): Handle { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('InteractionManager: create interaction handle'); _scheduleUpdate(); const handle = ++_inc; @@ -84,6 +86,8 @@ const InteractionManagerImpl = { * Notify manager that an interaction has completed. */ clearInteractionHandle(handle: Handle) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('InteractionManager: clear interaction handle'); invariant(!!handle, 'InteractionManager: Must provide a handle to clear.'); _scheduleUpdate(); diff --git a/packages/react-native/Libraries/Interaction/TaskQueue.js b/packages/react-native/Libraries/Interaction/TaskQueue.js index 720a286c089029..9b5e487046ff6f 100644 --- a/packages/react-native/Libraries/Interaction/TaskQueue.js +++ b/packages/react-native/Libraries/Interaction/TaskQueue.js @@ -99,9 +99,13 @@ class TaskQueue { const task = queue.shift(); try { if (typeof task === 'object' && task.gen) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: genPromise for task ' + task.name); this._genPromise(task); } else if (typeof task === 'object' && task.run) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: run task ' + task.name); task.run(); } else { @@ -110,6 +114,8 @@ class TaskQueue { 'Expected Function, SimpleTask, or PromiseTask, but got:\n' + JSON.stringify(task, null, 2), ); + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: run anonymous task'); task(); } @@ -139,6 +145,8 @@ class TaskQueue { this._queueStack.length > 1 ) { this._queueStack.pop(); + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: popped queue: ', { stackIdx, @@ -158,11 +166,17 @@ class TaskQueue { this._queueStack.push({tasks: [], popable: false}); const stackIdx = this._queueStack.length - 1; const stackItem = this._queueStack[stackIdx]; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: push new queue: ', {stackIdx}); + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: exec gen task ' + task.name); task .gen() .then(() => { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.log('TaskQueue: onThen for gen task ' + task.name, { stackIdx, diff --git a/packages/react-native/Libraries/Network/XMLHttpRequest.js b/packages/react-native/Libraries/Network/XMLHttpRequest.js index d963e07a474154..113ea1604dc8c7 100644 --- a/packages/react-native/Libraries/Network/XMLHttpRequest.js +++ b/packages/react-native/Libraries/Network/XMLHttpRequest.js @@ -646,6 +646,8 @@ class XMLHttpRequest extends EventTarget { this.withCredentials, ); }; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (DEBUG_NETWORK_SEND_DELAY) { setTimeout(doSend, DEBUG_NETWORK_SEND_DELAY); } else { diff --git a/packages/react-native/Libraries/Utilities/createPerformanceLogger.js b/packages/react-native/Libraries/Utilities/createPerformanceLogger.js index 8db0c9df19b105..410610e8ef64ad 100644 --- a/packages/react-native/Libraries/Utilities/createPerformanceLogger.js +++ b/packages/react-native/Libraries/Utilities/createPerformanceLogger.js @@ -35,6 +35,8 @@ class PerformanceLogger implements IPerformanceLogger { endExtras?: Extras, ) { if (this._closed) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: addTimespan - has closed ignoring: ', @@ -44,6 +46,8 @@ class PerformanceLogger implements IPerformanceLogger { return; } if (this._timespans[key]) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to add a timespan that already exists ', @@ -79,6 +83,8 @@ class PerformanceLogger implements IPerformanceLogger { this._timespans = {}; this._extras = {}; this._points = {}; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE) { console.log('PerformanceLogger.js', 'clear'); } @@ -92,6 +98,8 @@ class PerformanceLogger implements IPerformanceLogger { } this._extras = {}; this._points = {}; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE) { console.log('PerformanceLogger.js', 'clearCompleted'); } @@ -130,6 +138,8 @@ class PerformanceLogger implements IPerformanceLogger { } logEverything() { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE) { // log timespans for (const key in this._timespans) { @@ -156,6 +166,8 @@ class PerformanceLogger implements IPerformanceLogger { extras?: Extras, ) { if (this._closed) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: markPoint - has closed ignoring: ', @@ -165,6 +177,8 @@ class PerformanceLogger implements IPerformanceLogger { return; } if (this._points[key] != null) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to mark a point that has been already logged ', @@ -187,6 +201,8 @@ class PerformanceLogger implements IPerformanceLogger { setExtra(key: string, value: ExtraValue) { if (this._closed) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log('PerformanceLogger: setExtra - has closed ignoring: ', key); } @@ -194,6 +210,8 @@ class PerformanceLogger implements IPerformanceLogger { } if (this._extras.hasOwnProperty(key)) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to set an extra that already exists ', @@ -211,6 +229,8 @@ class PerformanceLogger implements IPerformanceLogger { extras?: Extras, ) { if (this._closed) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: startTimespan - has closed ignoring: ', @@ -221,6 +241,8 @@ class PerformanceLogger implements IPerformanceLogger { } if (this._timespans[key]) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to start a timespan that already exists ', @@ -234,6 +256,8 @@ class PerformanceLogger implements IPerformanceLogger { startTime: timestamp, startExtras: extras, }; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE) { console.log('PerformanceLogger.js', 'start: ' + key); } @@ -245,6 +269,8 @@ class PerformanceLogger implements IPerformanceLogger { extras?: Extras, ) { if (this._closed) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: stopTimespan - has closed ignoring: ', @@ -256,6 +282,8 @@ class PerformanceLogger implements IPerformanceLogger { const timespan = this._timespans[key]; if (!timespan || timespan.startTime == null) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to end a timespan that has not started ', @@ -265,6 +293,8 @@ class PerformanceLogger implements IPerformanceLogger { return; } if (timespan.endTime != null) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE && __DEV__) { console.log( 'PerformanceLogger: Attempting to end a timespan that has already ended ', @@ -277,6 +307,8 @@ class PerformanceLogger implements IPerformanceLogger { timespan.endExtras = extras; timespan.endTime = timestamp; timespan.totalTime = timespan.endTime - (timespan.startTime || 0); + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (PRINT_TO_CONSOLE) { console.log('PerformanceLogger.js', 'end: ' + key); } diff --git a/packages/virtualized-lists/Lists/FillRateHelper.js b/packages/virtualized-lists/Lists/FillRateHelper.js index f09e946e3da30d..22232d6affdb35 100644 --- a/packages/virtualized-lists/Lists/FillRateHelper.js +++ b/packages/virtualized-lists/Lists/FillRateHelper.js @@ -33,6 +33,8 @@ const DEBUG = false; let _listeners: Array<(Info) => void> = []; let _minSampleCount = 10; +/* $FlowFixMe[constant-condition] Error discovered during Constant Condition + * roll out. See https://fburl.com/workplace/1v97vimq. */ let _sampleRate = DEBUG ? 1 : null; /** @@ -82,6 +84,8 @@ class FillRateHelper { activate() { if (this._enabled && this._samplesStartTime == null) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.debug('FillRateHelper: activate'); this._samplesStartTime = global.performance.now(); } @@ -93,6 +97,8 @@ class FillRateHelper { } const start = this._samplesStartTime; // const for flow if (start == null) { + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ DEBUG && console.debug('FillRateHelper: bail on deactivate with no start time'); return; @@ -107,6 +113,8 @@ class FillRateHelper { ...this._info, total_time_spent, }; + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ if (DEBUG) { const derived = { avg_blankness: this._info.pixels_blank / this._info.pixels_sampled, diff --git a/packages/virtualized-lists/Lists/VirtualizedList.js b/packages/virtualized-lists/Lists/VirtualizedList.js index 5b8aaa525bd6bf..bceacf5a1f7d25 100644 --- a/packages/virtualized-lists/Lists/VirtualizedList.js +++ b/packages/virtualized-lists/Lists/VirtualizedList.js @@ -279,6 +279,8 @@ class VirtualizedList extends StateSafePureComponent< const cartOffset = this._listMetrics.cartesianOffset( offset + this._scrollMetrics.visibleLength, ); + /* $FlowFixMe[constant-condition] Error discovered during Constant + * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ return horizontal ? {x: cartOffset} : {y: cartOffset}; } else { return horizontal ? {x: offset} : {y: offset}; From eb61e6f7836aeff1b43df728e5a22a2ecda102bb Mon Sep 17 00:00:00 2001 From: Adan Moreno Date: Tue, 8 Jul 2025 16:29:45 -0700 Subject: [PATCH 0030/1383] Revert D77143018: Cleanup react-native-codegen DEFS Differential Revision: D77143018 Original commit changeset: 06ec43ce5149 Original Phabricator Diff: D77143018 fbshipit-source-id: cec53068f88548c4494da315914763beb6730573 --- .../generators/components/GenerateTests.js | 8 +- .../__snapshots__/GenerateTests-test.js.snap | 480 +++++++++--------- 2 files changed, 244 insertions(+), 244 deletions(-) diff --git a/packages/react-native-codegen/src/generators/components/GenerateTests.js b/packages/react-native-codegen/src/generators/components/GenerateTests.js index 5ec224a2f49aec..9f10a59932e15e 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateTests.js +++ b/packages/react-native-codegen/src/generators/components/GenerateTests.js @@ -65,15 +65,15 @@ const TestTemplate = ({ propValue: string, }) => ` TEST(${componentName}_${testName}, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare<${componentName}>(); - ${componentName} sourceProps{}; - RawProps rawProps(folly::dynamic::object("${propName}", ${propValue})); + auto const &sourceProps = ${componentName}(); + auto const &rawProps = RawProps(folly::dynamic::object("${propName}", ${propValue})); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ${componentName}(parserContext, sourceProps, rawProps); } `; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap index 7c84b28cbaf951..d931c4753b08a3 100644 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap +++ b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap @@ -23,15 +23,15 @@ Map { using namespace facebook::react; TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ArrayPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ArrayPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -58,15 +58,15 @@ Map { using namespace facebook::react; TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ArrayPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ArrayPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -93,28 +93,28 @@ Map { using namespace facebook::react; TEST(BooleanPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - BooleanPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = BooleanPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(BooleanPropNativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - BooleanPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); + auto const &sourceProps = BooleanPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -141,28 +141,28 @@ Map { using namespace facebook::react; TEST(ColorPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ColorPropNativeComponentProps_tintColor, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"tintColor\\", 1)); + auto const &sourceProps = ColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"tintColor\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -189,15 +189,15 @@ Map { using namespace facebook::react; TEST(CommandNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - CommandNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = CommandNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); CommandNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -224,28 +224,28 @@ Map { using namespace facebook::react; TEST(CommandNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - CommandNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = CommandNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); CommandNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(CommandNativeComponentProps_accessibilityHint, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - CommandNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + auto const &sourceProps = CommandNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); CommandNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -273,15 +273,15 @@ Map { using namespace facebook::react; TEST(DimensionPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - DimensionPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = DimensionPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); DimensionPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -308,15 +308,15 @@ Map { using namespace facebook::react; TEST(DoublePropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - DoublePropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = DoublePropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); DoublePropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -343,28 +343,28 @@ Map { using namespace facebook::react; TEST(EventsNestedObjectNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - EventsNestedObjectNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = EventsNestedObjectNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(EventsNestedObjectNativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - EventsNestedObjectNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); + auto const &sourceProps = EventsNestedObjectNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -391,28 +391,28 @@ Map { using namespace facebook::react; TEST(EventsNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - EventsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = EventsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); EventsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(EventsNativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - EventsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); + auto const &sourceProps = EventsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); EventsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -439,15 +439,15 @@ Map { using namespace facebook::react; TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - InterfaceOnlyComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = InterfaceOnlyComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); }", } @@ -474,15 +474,15 @@ Map { using namespace facebook::react; TEST(ExcludedAndroidComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ExcludedAndroidComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ExcludedAndroidComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ExcludedAndroidComponentProps(parserContext, sourceProps, rawProps); }", } @@ -509,15 +509,15 @@ Map { using namespace facebook::react; TEST(ExcludedAndroidIosComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ExcludedAndroidIosComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ExcludedAndroidIosComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ExcludedAndroidIosComponentProps(parserContext, sourceProps, rawProps); }", } @@ -544,41 +544,41 @@ Map { using namespace facebook::react; TEST(ExcludedIosComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ExcludedIosComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ExcludedIosComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ExcludedIosComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFileIncludedNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFileIncludedNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MultiFileIncludedNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFileIncludedNativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFileIncludedNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); + auto const &sourceProps = MultiFileIncludedNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -605,93 +605,93 @@ Map { using namespace facebook::react; TEST(FloatPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius\\", 0)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius2, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius2\\", 0.001)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius2\\", 0.001)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius3, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius3\\", 2.1)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius3\\", 2.1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius4, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius4\\", 0)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius4\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius5, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius5\\", 1)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius5\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(FloatPropNativeComponentProps_blurRadius6, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - FloatPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"blurRadius6\\", 0)); + auto const &sourceProps = FloatPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius6\\", 0)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -719,28 +719,28 @@ Map { using namespace facebook::react; TEST(ImagePropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImagePropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ImagePropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImagePropNativeComponentProps_thumbImage, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImagePropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); + auto const &sourceProps = ImagePropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -767,15 +767,15 @@ Map { using namespace facebook::react; TEST(InsetsPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - InsetsPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = InsetsPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); InsetsPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -802,15 +802,15 @@ Map { using namespace facebook::react; TEST(Int32EnumPropsNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - Int32EnumPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = Int32EnumPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); Int32EnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -837,15 +837,15 @@ Map { using namespace facebook::react; TEST(IntegerPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - IntegerPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = IntegerPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); IntegerPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -872,28 +872,28 @@ Map { using namespace facebook::react; TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - InterfaceOnlyComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = InterfaceOnlyComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); } TEST(InterfaceOnlyComponentProps_accessibilityHint, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - InterfaceOnlyComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + auto const &sourceProps = InterfaceOnlyComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); }", } @@ -921,15 +921,15 @@ Map { using namespace facebook::react; TEST(MixedPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MixedPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MixedPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MixedPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -957,67 +957,67 @@ Map { using namespace facebook::react; TEST(ImageColorPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImageColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ImageColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_thumbImage, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImageColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); + auto const &sourceProps = ImageColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_color, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImageColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"color\\", 1)); + auto const &sourceProps = ImageColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"color\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_thumbTintColor, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImageColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"thumbTintColor\\", 1)); + auto const &sourceProps = ImageColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbTintColor\\", 1)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(ImageColorPropNativeComponentProps_point, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ImageColorPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"point\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); + auto const &sourceProps = ImageColorPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"point\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1044,15 +1044,15 @@ Map { using namespace facebook::react; TEST(NoPropsNoEventsComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - NoPropsNoEventsComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = NoPropsNoEventsComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); NoPropsNoEventsComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1080,15 +1080,15 @@ Map { using namespace facebook::react; TEST(ObjectPropsProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - ObjectPropsProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = ObjectPropsProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); ObjectPropsProps(parserContext, sourceProps, rawProps); }", } @@ -1115,28 +1115,28 @@ Map { using namespace facebook::react; TEST(PointPropNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - PointPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = PointPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); PointPropNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(PointPropNativeComponentProps_startPoint, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - PointPropNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"startPoint\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); + auto const &sourceProps = PointPropNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"startPoint\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); PointPropNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1163,54 +1163,54 @@ Map { using namespace facebook::react; TEST(StringEnumPropsNativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringEnumPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = StringEnumPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_Top, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringEnumPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"top\\")); + auto const &sourceProps = StringEnumPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"top\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_Center, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringEnumPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"center\\")); + auto const &sourceProps = StringEnumPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"center\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); } TEST(StringEnumPropsNativeComponentProps_alignment_BottomRight, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringEnumPropsNativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"alignment\\", \\"bottom-right\\")); + auto const &sourceProps = StringEnumPropsNativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"bottom-right\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1237,41 +1237,41 @@ Map { using namespace facebook::react; TEST(StringPropComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringPropComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = StringPropComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringPropComponentProps(parserContext, sourceProps, rawProps); } TEST(StringPropComponentProps_accessibilityHint, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringPropComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); + auto const &sourceProps = StringPropComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringPropComponentProps(parserContext, sourceProps, rawProps); } TEST(StringPropComponentProps_accessibilityRole, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - StringPropComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"accessibilityRole\\", \\"foo\\")); + auto const &sourceProps = StringPropComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityRole\\", \\"foo\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); StringPropComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1298,54 +1298,54 @@ Map { using namespace facebook::react; TEST(MultiFile1NativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFile1NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MultiFile1NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile1NativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFile1NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); + auto const &sourceProps = MultiFile1NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile2NativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFile2NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MultiFile2NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiFile2NativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiFile2NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); + auto const &sourceProps = MultiFile2NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); }", } @@ -1372,54 +1372,54 @@ Map { using namespace facebook::react; TEST(MultiComponent1NativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiComponent1NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MultiComponent1NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent1NativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiComponent1NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", false)); + auto const &sourceProps = MultiComponent1NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent2NativeComponentProps_DoesNotDie, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiComponent2NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); + auto const &sourceProps = MultiComponent2NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); } TEST(MultiComponent2NativeComponentProps_disabled, etc) { - RawPropsParser propParser{}; + auto propParser = RawPropsParser(); propParser.prepare(); - MultiComponent2NativeComponentProps sourceProps{}; - RawProps rawProps(folly::dynamic::object(\\"disabled\\", true)); + auto const &sourceProps = MultiComponent2NativeComponentProps(); + auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - rawProps.parse(propParser); + rawProps.parse(propParser, parserContext); MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); }", } From 6892dde36373bbef2d0afe535ae818b1a7164f08 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 8 Jul 2025 16:33:18 -0700 Subject: [PATCH 0031/1383] Gradle to 8.14.3 (#52466) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52466 Just another patch bump of Gradle 8.14 Changelog: [Android] [Changed] - Gradle to 8.14.3 Reviewed By: NickGerleman Differential Revision: D77865220 fbshipit-source-id: 450d175242f046909ab1984654d24e92a2536d5d --- gradle/wrapper/gradle-wrapper.properties | 2 +- packages/gradle-plugin/gradle/wrapper/gradle-wrapper.properties | 2 +- .../helloworld/android/gradle/wrapper/gradle-wrapper.properties | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 002b867c48b328..d4081da476bb3e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/packages/gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/packages/gradle-plugin/gradle/wrapper/gradle-wrapper.properties index ff23a68d70f3cd..d4081da476bb3e 100644 --- a/packages/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +++ b/packages/gradle-plugin/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/private/helloworld/android/gradle/wrapper/gradle-wrapper.properties b/private/helloworld/android/gradle/wrapper/gradle-wrapper.properties index ff23a68d70f3cd..d4081da476bb3e 100644 --- a/private/helloworld/android/gradle/wrapper/gradle-wrapper.properties +++ b/private/helloworld/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME From b5329ecd6df75ff98c64a9440694fbbaa3d97be4 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Tue, 8 Jul 2025 21:10:36 -0700 Subject: [PATCH 0032/1383] NativeCxxModuleExample test for testing C++ TM E2E (#52477) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52477 Changelog: [Internal] This adds a Fantom test for https://github.com/facebook/react-native/blob/main/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.js to test a C++ Turbo Module End 2 End (loading the C++ implementation in native code, accessing in JavaScript via Hermes VM and verifying the results of the API calls) Reviewed By: rshest Differential Revision: D77848654 fbshipit-source-id: 48a4ab88a330e9282ae8dab589743eaace62d124 --- .../NativeCxxModuleExample.cpp | 31 +- .../__tests__/NativeCxxModuleExample-itest.js | 351 ++++++++++++++++++ .../react-native-fantom/config/jest.config.js | 1 + .../tester/src/TesterAppDelegate.cpp | 3 + 4 files changed, 379 insertions(+), 7 deletions(-) create mode 100644 packages/rn-tester/NativeCxxModuleExample/__tests__/NativeCxxModuleExample-itest.js diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp index 0789565be9ba2c..f36996e15daeea 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp @@ -7,9 +7,22 @@ #include "NativeCxxModuleExample.h" #include +#include +#include +#include namespace facebook::react { +namespace { + +std::string to_string_with_precision(double value, int precision = 2) { + std::ostringstream oss; + oss << std::setprecision(precision) << std::fixed << value; + return oss.str(); +} + +} // namespace + NativeCxxModuleExample::NativeCxxModuleExample( std::shared_ptr jsInvoker) : NativeCxxModuleExampleCxxSpec(std::move(jsInvoker)) {} @@ -126,10 +139,12 @@ std::string NativeCxxModuleExample::getUnion( float x, std::string y, jsi::Object z) { - std::string result = "x: " + std::to_string(x) + ", y: " + y + ", z: { "; + std::string result = + "x: " + to_string_with_precision(x) + ", y: " + y + ", z: { "; if (z.hasProperty(rt, "value")) { result += "value: "; - result += std::to_string(z.getProperty(rt, "value").getNumber()); + result += + to_string_with_precision(z.getProperty(rt, "value").getNumber(), 0); } else if (z.hasProperty(rt, "low")) { result += "low: "; result += z.getProperty(rt, "low").getString(rt).utf8(rt); @@ -201,11 +216,13 @@ void NativeCxxModuleExample::emitCustomDeviceEvent( eventName, [jsInvoker = jsInvoker_]( jsi::Runtime& rt, std::vector& args) { - args.emplace_back(jsi::Value(true)); - args.emplace_back(jsi::Value(42)); - args.emplace_back(jsi::String::createFromAscii(rt, "stringArg")); - args.emplace_back(bridging::toJs( - rt, CustomDeviceEvent{"one", 2, std::nullopt}, jsInvoker)); + args.emplace_back(jsi::Array::createWithElements( + rt, + jsi::Value(true), + jsi::Value(42), + jsi::String::createFromAscii(rt, "stringArg"), + bridging::toJs( + rt, CustomDeviceEvent{"one", 2, std::nullopt}, jsInvoker))); }); } diff --git a/packages/rn-tester/NativeCxxModuleExample/__tests__/NativeCxxModuleExample-itest.js b/packages/rn-tester/NativeCxxModuleExample/__tests__/NativeCxxModuleExample-itest.js new file mode 100644 index 00000000000000..f75082e26e4297 --- /dev/null +++ b/packages/rn-tester/NativeCxxModuleExample/__tests__/NativeCxxModuleExample-itest.js @@ -0,0 +1,351 @@ +/** + * 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 '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; +import type { + BinaryTreeNode, + GraphNode, + ObjectStruct, +} from '../NativeCxxModuleExample'; + +import NativeCxxModuleExample, { + EnumInt, + EnumNone, + EnumStr, +} from '../NativeCxxModuleExample'; +import RCTDeviceEventEmitter from 'react-native/Libraries/EventEmitter/RCTDeviceEventEmitter'; +import NativeFantom from 'react-native/src/private/testing/fantom/specs/NativeFantom'; + +describe('NativeCxxModuleExample', () => { + it('verifies that the Turbo Module was loaded', () => { + expect(NativeCxxModuleExample).not.toBeNull(); + }); + + it('verifies getArray(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getArray([])).toEqual([]); + expect(NativeCxxModuleExample?.getArray([null])).toEqual([null]); + expect(NativeCxxModuleExample?.getArray([{a: 1, b: '2'}])).toEqual([ + {a: 1, b: '2'}, + ]); + }); + + it('verifies getBool(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getBool(false)).toBe(false); + expect(NativeCxxModuleExample?.getBool(true)).toBe(true); + }); + + it('verifies getConstants(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getConstants()).toEqual({ + const1: true, + const2: 69, + const3: 'react-native', + }); + }); + + it('verifies getCustomEnum(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getCustomEnum(EnumInt.IA)).toBe(EnumInt.IA); + }); + + it('verifies getCustomHostObject(...) returns the correct values', () => { + const customHostObject = NativeCxxModuleExample?.getCustomHostObject(); + expect(customHostObject).not.toBe(null); + if (customHostObject != null) { + expect( + NativeCxxModuleExample?.consumeCustomHostObject(customHostObject), + ).toBe('answer42'); + } + }); + + it('verifies getBinaryTreeNode(...) returns the correct values', () => { + const binaryTreeNode: BinaryTreeNode = { + left: {value: 2}, + value: 4, + right: {value: 6}, + }; + const result = NativeCxxModuleExample?.getBinaryTreeNode(binaryTreeNode); + expect(result).not.toBe(null); + if (result != null) { + expect(result.left?.left).toBeNull(); + expect(result.left?.value).toBe(2); + expect(result.left?.right).toBeNull(); + expect(result.value).toBe(4); + expect(result.right?.left).toBeNull(); + expect(result.right?.value).toBe(6); + expect(result.right?.right).toBeNull(); + } + }); + + it('verifies getGraphNode(...) returns the correct values', () => { + const graphNode: GraphNode = { + label: 'root', + neighbors: [{label: 'child1'}, {label: 'child2'}], + }; + const result = NativeCxxModuleExample?.getGraphNode(graphNode); + expect(result).not.toBe(null); + if (result != null) { + expect(result.label).toBe('root'); + expect(result.neighbors?.length).toBe(4); + expect(result.neighbors?.[0].label).toBe('child1'); + expect(result.neighbors?.[0].neighbors).toBeNull(); + expect(result.neighbors?.[1].label).toBe('child2'); + expect(result.neighbors?.[1].neighbors).toBeNull(); + expect(result.neighbors?.[2].label).toBe('top'); + expect(result.neighbors?.[2].neighbors).toBeNull(); + expect(result.neighbors?.[3].label).toBe('down'); + expect(result.neighbors?.[3].neighbors).toBeNull(); + } + }); + + it('verifies getNumEnum(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getNumEnum(EnumInt.IA)).toBe(EnumInt.IA); + expect(NativeCxxModuleExample?.getNumEnum(EnumInt.IB)).toBe(EnumInt.IB); + }); + + it('verifies getStrEnum(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getStrEnum(EnumNone.NA)).toBe(EnumStr.SB); + expect(NativeCxxModuleExample?.getStrEnum(EnumNone.NB)).toBe(EnumStr.SB); + }); + + it('verifies getMap(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getMap({a: 0, b: null, c: 3})).toEqual({ + a: 0, + b: null, + c: 3, + }); + }); + + it('verifies getNumber(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getNumber(0)).toBe(0); + expect(NativeCxxModuleExample?.getNumber(Math.pow(2, 53))).toBe( + Math.pow(2, 53), + ); + }); + + it('verifies getObject(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getObject({a: 2, b: 'two'})).toEqual({ + a: 2, + b: 'two', + }); + expect( + NativeCxxModuleExample?.getObject({a: 4, b: 'four', c: 'seven'}), + ).toEqual({a: 4, b: 'four', c: 'seven'}); + }); + + it('verifies getSet(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getSet([1, 2, 3, 3, 3])).toEqual([1, 2, 3]); + }); + + it('verifies getString(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getString('')).toBe(''); + expect(NativeCxxModuleExample?.getString('string')).toBe('string'); + }); + + it('verifies getUnion(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getUnion(2.88, 'Two', {value: 2})).toBe( + 'x: 2.88, y: Two, z: { value: 2 }', + ); + expect(NativeCxxModuleExample?.getUnion(5.76, 'One', {low: 'value'})).toBe( + 'x: 5.76, y: One, z: { low: value }', + ); + }); + + it('verifies getValue(...) returns the correct values', () => { + expect( + NativeCxxModuleExample?.getValue(23, 'forty-two', { + a: 4, + b: 'four', + c: 'seven', + }), + ).toEqual({x: 23, y: 'forty-two', z: {a: 4, b: 'four', c: 'seven'}}); + }); + + it('verifies getValueWithCallback(...) returns the correct values', () => { + let result = ''; + NativeCxxModuleExample?.getValueWithCallback((value: string) => { + result = value; + }); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callback + expect(result).toBe('value from callback!'); + }); + + it('verifies setValueCallbackWithSubscription(...) returns the correct values', () => { + let result = ''; + let subscription = NativeCxxModuleExample?.setValueCallbackWithSubscription( + (value: string) => { + result = value; + }, + ); + expect(result).toBe(''); + expect(subscription).not.toBeNull(); + subscription?.(); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callback + expect(result).toBe('value from callback on clean up!'); + }); + + it('verifies getValueWithPromise(...) returns the correct values', () => { + { + let result = ''; + let error = ''; + NativeCxxModuleExample?.getValueWithPromise(false) + .then(value => { + result = value; + }) + .catch(err => { + error = err; + }); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callbacks + expect(result).toBe('result!'); + expect(error).toBe(''); + } + { + let result = ''; + let error = ''; + NativeCxxModuleExample?.getValueWithPromise(true) + .then(value => { + result = value; + }) + .catch(err => { + error = err; + }); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callbacks + expect(result).toBe(''); + expect(error.toString()).toBe('Error: intentional promise rejection'); + } + + it('verifies getWithWithOptionalArgs(...) returns the correct values', () => { + expect(NativeCxxModuleExample?.getWithWithOptionalArgs()).toBeNull(); + expect(NativeCxxModuleExample?.getWithWithOptionalArgs(true)).toBe(true); + expect(NativeCxxModuleExample?.getWithWithOptionalArgs(false)).toBe( + false, + ); + }); + + it('verifies voidFunc(...) returns the correct for EventEmitters', () => { + let eventEmitterCalled = { + onPress: 0, + onClick: 0, + onChange: 0, + onSubmit: 0, + onEvent: 0, + }; + let onClickValue: ?string = null; + let onChangeValue: ?ObjectStruct = null; + let onSubmitValue: ?(ObjectStruct[]) = null; + let onEventValue: ?EnumNone = null; + NativeCxxModuleExample?.onPress(() => { + eventEmitterCalled.onPress++; + }); + NativeCxxModuleExample?.onClick((value: string) => { + eventEmitterCalled.onClick++; + onClickValue = value; + }); + NativeCxxModuleExample?.onChange((value: ObjectStruct) => { + eventEmitterCalled.onChange++; + onChangeValue = value; + }); + NativeCxxModuleExample?.onSubmit((value: ObjectStruct[]) => { + eventEmitterCalled.onSubmit++; + onSubmitValue = value; + }); + NativeCxxModuleExample?.onEvent((value: EnumNone) => { + eventEmitterCalled.onEvent++; + onEventValue = value; + }); + NativeCxxModuleExample?.voidFunc(); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callbacks + + expect(eventEmitterCalled.onPress).toBe(1); + expect(eventEmitterCalled.onClick).toBe(1); + expect(eventEmitterCalled.onChange).toBe(1); + expect(eventEmitterCalled.onSubmit).toBe(1); + expect(eventEmitterCalled.onEvent).toBe(1); + + expect(onClickValue).toBe('value from callback on click!'); + expect(onChangeValue).toEqual({a: 1, b: 'two'}); + expect(onSubmitValue).toEqual([ + {a: 1, b: 'two'}, + {a: 3, b: 'four'}, + {a: 5, b: 'six'}, + ]); + expect(onEventValue).toBe(EnumNone.NA); + }); + }); + + it('verifies voidPromise(...) returns the correct values', () => { + let promiseCalled = { + result: 0, + error: 0, + }; + NativeCxxModuleExample?.voidPromise() + .then(_value => promiseCalled.result++) + .catch(_err => promiseCalled.error++); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callbacks + expect(promiseCalled.result).toBe(1); + expect(promiseCalled.error).toBe(0); + }); + + it('verifies setMenu(...) returns the correct values', () => { + let result: {[key: string]: ?{value: string, flag: boolean}} = { + file: null, + new: null, + }; + let menu = { + label: 'File', + onPress: (value: string, flag: boolean) => { + result.file = {value, flag}; + }, + items: [ + { + label: 'new', + onPress: (value: string, flag: boolean) => { + result.new = {value, flag}; + }, + }, + ], + }; + NativeCxxModuleExample?.setMenu(menu); + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callback + expect(result.file?.value).toBe('value'); + expect(result.file?.flag).toBe(true); + expect(result.new?.value).toBe('another value'); + expect(result.new?.flag).toBe(false); + }); + + it('verifies emitCustomDeviceEvent(...) returns the correct values', () => { + let events: {[key: string]: ?string} = { + foo: null, + bar: null, + }; + RCTDeviceEventEmitter.addListener( + 'foo', + (value: string) => (events.foo = value), + ); + RCTDeviceEventEmitter.addListener( + 'bar', + (value: string) => (events.bar = value), + ); + NativeCxxModuleExample?.emitCustomDeviceEvent('foo'); + NativeCxxModuleExample?.emitCustomDeviceEvent('bar'); + + NativeFantom.flushMessageQueue(); // Flush the message queue to execute the callbacks + expect(events.foo).toEqual([ + true, + 42, + 'stringArg', + {type: 'one', level: 2}, + ]); + expect(events.foo).toEqual([ + true, + 42, + 'stringArg', + {type: 'one', level: 2}, + ]); + }); +}); diff --git a/private/react-native-fantom/config/jest.config.js b/private/react-native-fantom/config/jest.config.js index 63c3809c70245d..908ac1c586b532 100644 --- a/private/react-native-fantom/config/jest.config.js +++ b/private/react-native-fantom/config/jest.config.js @@ -26,6 +26,7 @@ module.exports = { rootDir: path.resolve(__dirname, '../../..') /*:: as string */, roots: [ '/packages/react-native', + '/packages/rn-tester', '/packages/polyfills', '/private/react-native-fantom', ], diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp index e4ec7bba2caf07..757f31ffc17030 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp @@ -7,6 +7,7 @@ #include "TesterAppDelegate.h" +#include #include #include #include @@ -87,6 +88,8 @@ TesterAppDelegate::TesterAppDelegate( return std::make_shared(jsInvoker); } else if (name == NativeFantomTestSpecificMethods::kModuleName) { return std::make_shared(jsInvoker); + } else if (name == NativeCxxModuleExample::kModuleName) { + return std::make_shared(jsInvoker); } else { return nullptr; } From 7725a0aee35ca3f4ac1932fae970d1f13f70c881 Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Wed, 9 Jul 2025 03:03:48 -0700 Subject: [PATCH 0033/1383] Fix CQS signal modernize-concat-nested-namespaces in xplat/js/react-native-github/packages/rn-tester/android/app/src/main/jni (#52501) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52501 Reviewed By: javache, cortinico Differential Revision: D77990137 fbshipit-source-id: 1fe4b7a0a821cf9bff5b21d38b6e78a3b164211d --- packages/rn-tester/android/app/src/main/jni/OnLoad.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/rn-tester/android/app/src/main/jni/OnLoad.cpp b/packages/rn-tester/android/app/src/main/jni/OnLoad.cpp index 803d4bbc50c404..9893ee47b14b73 100644 --- a/packages/rn-tester/android/app/src/main/jni/OnLoad.cpp +++ b/packages/rn-tester/android/app/src/main/jni/OnLoad.cpp @@ -21,8 +21,7 @@ #include REACT_NATIVE_APP_COMPONENT_DESCRIPTORS_HEADER #endif -namespace facebook { -namespace react { +namespace facebook::react { void registerComponents( std::shared_ptr registry) { @@ -62,8 +61,7 @@ std::shared_ptr javaModuleProvider( return nullptr; } -} // namespace react -} // namespace facebook +} // namespace facebook::react JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) { return facebook::jni::initialize(vm, [] { From 9c172fbba346e391ae2646fece1e6288fe326558 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 9 Jul 2025 04:50:29 -0700 Subject: [PATCH 0034/1383] Add more logging around computeNightlyTarballURL Summary: This is a backport of a fix we applied to the 0.81 branch. Changelog: [Internal] [Changed] - bypass-github-export-checks Reviewed By: vzaidman Differential Revision: D78000573 fbshipit-source-id: 64a4e90632158c1f52c45f9fbc3452e848271e94 --- packages/react-native/scripts/ios-prebuild/utils.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/react-native/scripts/ios-prebuild/utils.js b/packages/react-native/scripts/ios-prebuild/utils.js index d9dec121dd55ce..ec14917e668777 100644 --- a/packages/react-native/scripts/ios-prebuild/utils.js +++ b/packages/react-native/scripts/ios-prebuild/utils.js @@ -65,10 +65,13 @@ async function computeNightlyTarballURL( artifactCoordinate /*: string */, artifactName /*: string */, ) /*: Promise */ { + const urlLog = createLogger('NightlyURL'); const xmlUrl = `https://central.sonatype.com/repository/maven-snapshots/com/facebook/react/${artifactCoordinate}/${version}-SNAPSHOT/maven-metadata.xml`; + urlLog(`Attempting to download maven-metadata.xml from: ${xmlUrl}...`); const response = await fetch(xmlUrl); if (!response.ok) { + urlLog(`Downloading maven-metadata.xml failed!`, 'error'); return ''; } const xmlText = await response.text(); @@ -76,6 +79,7 @@ async function computeNightlyTarballURL( // Extract the block const snapshotMatch = xmlText.match(/([\s\S]*?)<\/snapshot>/); if (!snapshotMatch) { + urlLog(`Could not find a tag that matches the regex!`, 'error'); return ''; } const snapshotContent = snapshotMatch[1]; @@ -83,6 +87,10 @@ async function computeNightlyTarballURL( // Extract from the snapshot block const timestampMatch = snapshotContent.match(/(.*?)<\/timestamp>/); if (!timestampMatch) { + urlLog( + `Could not find a tag inside that matches the regex!`, + 'error', + ); return ''; } const timestamp = timestampMatch[1]; @@ -92,12 +100,17 @@ async function computeNightlyTarballURL( /(.*?)<\/buildNumber>/, ); if (!buildNumberMatch) { + urlLog( + `Could not find a tag that matches the regex!`, + 'error', + ); return ''; } const buildNumber = buildNumberMatch[1]; const fullVersion = `${version}-${timestamp}-${buildNumber}`; const finalUrl = `https://central.sonatype.com/repository/maven-snapshots/com/facebook/react/${artifactCoordinate}/${version}-SNAPSHOT/${artifactCoordinate}-${fullVersion}-${artifactName}`; + urlLog(`Final artifact URL found: ${finalUrl}`); return finalUrl; } From 47957f9adcb4ee5f745ba6369fef2bf801d8759c Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Wed, 9 Jul 2025 04:56:35 -0700 Subject: [PATCH 0035/1383] 60 (#52493) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52493 Reviewed By: dtolnay Differential Revision: D77920274 fbshipit-source-id: 42a68d5666f43f606ebcbbe4d207bb9b299760e7 --- .../ReactCommon/reactperflogger/fusebox/FuseboxTracer.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h index 303577792eb7ec..0c415154e7a7d0 100644 --- a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h +++ b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h @@ -7,7 +7,7 @@ #pragma once -#include "folly/dynamic.h" +#include "folly/json/dynamic.h" #include #include From 2ca88a0069969bf115da6f0ea9f2fbbae9c9226c Mon Sep 17 00:00:00 2001 From: Anupriya Verma <54227869+anupriya13@users.noreply.github.com> Date: Wed, 9 Jul 2025 05:05:52 -0700 Subject: [PATCH 0036/1383] 'return': conversion from 'int' to 'uint8_t', possible loss of data in CSSHexColor (#52496) Summary: Resolves https://github.com/microsoft/react-native-windows/issues/14666 We faced this issue while integrating [0.79.0-nightly-20250220-41b597c73](https://github.com/microsoft/react-native-windows/pull/14662/files#top) This warning is treated as error and should be fixed here as well. ## Changelog: - + + + + From 586f5ba89cc20a81a9e2d5d0f2708e9cd1b440c0 Mon Sep 17 00:00:00 2001 From: Vineeth K Date: Wed, 9 Jul 2025 18:33:59 -0700 Subject: [PATCH 0049/1383] Added fix to use accessibility source props (#52397) Summary: accessibilityRole is not getting the default value from sourceProps. This change will fix https://github.com/facebook/react-native/issues/52396 ## Changelog: 0 interactions - /* $FlowFixMe[prop-missing] Natural Inference rollout. See - * https://fburl.com/workplace/6291gfvu */ - /* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See - * https://fburl.com/workplace/6291gfvu */ - _emitter.emit(InteractionManager.Events.interactionComplete); - } else if (interactionCount === 0 && nextInteractionCount !== 0) { - // transition from 0 --> 1+ interactions - /* $FlowFixMe[prop-missing] Natural Inference rollout. See - * https://fburl.com/workplace/6291gfvu */ - /* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See - * https://fburl.com/workplace/6291gfvu */ - _emitter.emit(InteractionManager.Events.interactionStart); - } +export type Handle = number; - // process the queue regardless of a transition - if (nextInteractionCount === 0) { - while (_taskQueue.hasTasksToProcess()) { - _taskQueue.processNext(); - if ( - _deadline > 0 && - BatchedBridge.getEventLoopRunningTime() >= _deadline - ) { - // Hit deadline before processing all tasks, so process more later. - _scheduleUpdate(); - break; - } - } - } - _addInteractionSet.clear(); - _deleteInteractionSet.clear(); +// NOTE: The original implementation of `InteractionManager` never rejected +// the returned promise. This preserves that behavior in the stub. +function reject(error: Error): void { + setTimeout(() => { + throw error; + }, 0); } /** @@ -231,11 +83,106 @@ function _processUpdate() { * * @deprecated */ -const InteractionManager = ( - ReactNativeFeatureFlags.disableInteractionManager() - ? // $FlowFixMe[incompatible-variance] - require('./InteractionManagerStub').default - : InteractionManagerImpl -) as typeof InteractionManagerImpl; +const InteractionManagerStub = { + Events: { + interactionStart: 'interactionStart', + interactionComplete: 'interactionComplete', + }, + + /** + * Schedule a function to run after all interactions have completed. Returns a cancellable + * "promise". + * + * @deprecated + */ + runAfterInteractions(task: ?Task): { + then: ( + onFulfill?: ?(void) => ?(Promise | U), + onReject?: ?(error: mixed) => ?(Promise | U), + ) => Promise, + cancel: () => void, + ... + } { + let immediateID: ?$FlowIssue; + const promise = new Promise(resolve => { + immediateID = setImmediate(() => { + if (typeof task === 'object' && task !== null) { + if (typeof task.gen === 'function') { + task.gen().then(resolve, reject); + } else if (typeof task.run === 'function') { + try { + task.run(); + resolve(); + } catch (error) { + reject(error); + } + } else { + reject(new TypeError(`Task "${task.name}" missing gen or run.`)); + } + } else if (typeof task === 'function') { + try { + task(); + resolve(); + } catch (error) { + reject(error); + } + } else { + reject(new TypeError('Invalid task of type: ' + typeof task)); + } + }); + }); + + return { + // $FlowFixMe[method-unbinding] added when improving typing for this parameters + then: promise.then.bind(promise), + cancel() { + clearImmediate(immediateID); + }, + }; + }, + + /** + * Notify manager that an interaction has started. + * + * @deprecated + */ + createInteractionHandle(): Handle { + return -1; + }, + + /** + * Notify manager that an interaction has completed. + * + * @deprecated + */ + clearInteractionHandle(handle: Handle) { + invariant(!!handle, 'InteractionManager: Must provide a handle to clear.'); + }, + + /** + * @deprecated + */ + addListener( + eventType: string, + // $FlowIgnore[unclear-type] + listener: (...args: any) => mixed, + context: mixed, + ): EventSubscription { + return { + remove() {}, + }; + }, + + /** + * A positive number will use setTimeout to schedule any tasks after the + * eventLoopRunningTime hits the deadline value, otherwise all tasks will be + * executed in one setImmediate batch (default). + * + * @deprecated + */ + setDeadline(deadline: number) { + // Do nothing. + }, +}; -export default InteractionManager; +export default InteractionManagerStub; diff --git a/packages/react-native/Libraries/Interaction/InteractionManagerStub.js b/packages/react-native/Libraries/Interaction/InteractionManagerStub.js deleted file mode 100644 index 4e94dcf40ce86b..00000000000000 --- a/packages/react-native/Libraries/Interaction/InteractionManagerStub.js +++ /dev/null @@ -1,184 +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 - */ - -import type {EventSubscription} from '../vendor/emitter/EventEmitter'; - -const invariant = require('invariant'); - -export type Handle = number; - -type Task = - | { - name: string, - run: () => void, - } - | { - name: string, - gen: () => Promise, - } - | (() => void); - -// NOTE: The original implementation of `InteractionManager` never rejected -// the returned promise. This preserves that behavior in the stub. -function reject(error: Error): void { - setTimeout(() => { - throw error; - }, 0); -} - -/** - * InteractionManager allows long-running work to be scheduled after any - * interactions/animations have completed. In particular, this allows JavaScript - * animations to run smoothly. - * - * Applications can schedule tasks to run after interactions with the following: - * - * ``` - * InteractionManager.runAfterInteractions(() => { - * // ...long-running synchronous task... - * }); - * ``` - * - * Compare this to other scheduling alternatives: - * - * - requestAnimationFrame(): for code that animates a view over time. - * - setImmediate/setTimeout(): run code later, note this may delay animations. - * - runAfterInteractions(): run code later, without delaying active animations. - * - * The touch handling system considers one or more active touches to be an - * 'interaction' and will delay `runAfterInteractions()` callbacks until all - * touches have ended or been cancelled. - * - * InteractionManager also allows applications to register animations by - * creating an interaction 'handle' on animation start, and clearing it upon - * completion: - * - * ``` - * var handle = InteractionManager.createInteractionHandle(); - * // run animation... (`runAfterInteractions` tasks are queued) - * // later, on animation completion: - * InteractionManager.clearInteractionHandle(handle); - * // queued tasks run if all handles were cleared - * ``` - * - * `runAfterInteractions` takes either a plain callback function, or a - * `PromiseTask` object with a `gen` method that returns a `Promise`. If a - * `PromiseTask` is supplied, then it is fully resolved (including asynchronous - * dependencies that also schedule more tasks via `runAfterInteractions`) before - * starting on the next task that might have been queued up synchronously - * earlier. - * - * By default, queued tasks are executed together in a loop in one - * `setImmediate` batch. If `setDeadline` is called with a positive number, then - * tasks will only be executed until the deadline (in terms of js event loop run - * time) approaches, at which point execution will yield via setTimeout, - * allowing events such as touches to start interactions and block queued tasks - * from executing, making apps more responsive. - * - * @deprecated - */ -const InteractionManagerStub = { - Events: { - interactionStart: 'interactionStart', - interactionComplete: 'interactionComplete', - }, - - /** - * Schedule a function to run after all interactions have completed. Returns a cancellable - * "promise". - * - * @deprecated - */ - runAfterInteractions(task: ?Task): { - then: ( - onFulfill?: ?(void) => ?(Promise | U), - onReject?: ?(error: mixed) => ?(Promise | U), - ) => Promise, - cancel: () => void, - ... - } { - let immediateID: ?$FlowIssue; - const promise = new Promise(resolve => { - immediateID = setImmediate(() => { - if (typeof task === 'object' && task !== null) { - if (typeof task.gen === 'function') { - task.gen().then(resolve, reject); - } else if (typeof task.run === 'function') { - try { - task.run(); - resolve(); - } catch (error) { - reject(error); - } - } else { - reject(new TypeError(`Task "${task.name}" missing gen or run.`)); - } - } else if (typeof task === 'function') { - try { - task(); - resolve(); - } catch (error) { - reject(error); - } - } else { - reject(new TypeError('Invalid task of type: ' + typeof task)); - } - }); - }); - - return { - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - then: promise.then.bind(promise), - cancel() { - clearImmediate(immediateID); - }, - }; - }, - - /** - * Notify manager that an interaction has started. - * - * @deprecated - */ - createInteractionHandle(): Handle { - return -1; - }, - - /** - * Notify manager that an interaction has completed. - * - * @deprecated - */ - clearInteractionHandle(handle: Handle) { - invariant(!!handle, 'InteractionManager: Must provide a handle to clear.'); - }, - - /** - * @deprecated - */ - addListener(): EventSubscription { - return { - remove() {}, - }; - }, - - /** - * A positive number will use setTimeout to schedule any tasks after the - * eventLoopRunningTime hits the deadline value, otherwise all tasks will be - * executed in one setImmediate batch (default). - * - * @deprecated - */ - setDeadline(deadline: number) { - // Do nothing. - }, -}; - -export default InteractionManagerStub; diff --git a/packages/react-native/Libraries/Interaction/TaskQueue.js b/packages/react-native/Libraries/Interaction/TaskQueue.js deleted file mode 100644 index 9b5e487046ff6f..00000000000000 --- a/packages/react-native/Libraries/Interaction/TaskQueue.js +++ /dev/null @@ -1,197 +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 - */ - -'use strict'; - -const invariant = require('invariant'); - -export type SimpleTask = { - name: string, - run: () => void, -}; -export type PromiseTask = { - name: string, - gen: () => Promise, -}; -export type Task = SimpleTask | PromiseTask | (() => void); - -const DEBUG: false = false; - -/** - * TaskQueue - A system for queueing and executing a mix of simple callbacks and - * trees of dependent tasks based on Promises. No tasks are executed unless - * `processNext` is called. - * - * `enqueue` takes a Task object with either a simple `run` callback, or a - * `gen` function that returns a `Promise` and puts it in the queue. If a gen - * function is supplied, then the promise it returns will block execution of - * tasks already in the queue until it resolves. This can be used to make sure - * the first task is fully resolved (including asynchronous dependencies that - * also schedule more tasks via `enqueue`) before starting on the next task. - * The `onMoreTasks` constructor argument is used to inform the owner that an - * async task has resolved and that the queue should be processed again. - * - * Note: Tasks are only actually executed with explicit calls to `processNext`. - */ -class TaskQueue { - /** - * TaskQueue instances are self contained and independent, so multiple tasks - * of varying semantics and priority can operate together. - * - * `onMoreTasks` is invoked when `PromiseTask`s resolve if there are more - * tasks to process. - */ - constructor({onMoreTasks}: {onMoreTasks: () => void, ...}) { - this._onMoreTasks = onMoreTasks; - this._queueStack = [{tasks: [], popable: false}]; - } - - /** - * Add a task to the queue. It is recommended to name your tasks for easier - * async debugging. Tasks will not be executed until `processNext` is called - * explicitly. - */ - enqueue(task: Task): void { - this._getCurrentQueue().push(task); - } - - enqueueTasks(tasks: Array): void { - tasks.forEach(task => this.enqueue(task)); - } - - cancelTasks(tasksToCancel: Array): void { - // search through all tasks and remove them. - this._queueStack = this._queueStack - .map(queue => ({ - ...queue, - tasks: queue.tasks.filter(task => tasksToCancel.indexOf(task) === -1), - })) - .filter((queue, idx) => queue.tasks.length > 0 || idx === 0); - } - - /** - * Check to see if `processNext` should be called. - * - * @returns {boolean} Returns true if there are tasks that are ready to be - * processed with `processNext`, or returns false if there are no more tasks - * to be processed right now, although there may be tasks in the queue that - * are blocked by earlier `PromiseTask`s that haven't resolved yet. - * `onMoreTasks` will be called after each `PromiseTask` resolves if there are - * tasks ready to run at that point. - */ - hasTasksToProcess(): boolean { - return this._getCurrentQueue().length > 0; - } - - /** - * Executes the next task in the queue. - */ - processNext(): void { - const queue = this._getCurrentQueue(); - if (queue.length) { - const task = queue.shift(); - try { - if (typeof task === 'object' && task.gen) { - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && console.log('TaskQueue: genPromise for task ' + task.name); - this._genPromise(task); - } else if (typeof task === 'object' && task.run) { - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && console.log('TaskQueue: run task ' + task.name); - task.run(); - } else { - invariant( - typeof task === 'function', - 'Expected Function, SimpleTask, or PromiseTask, but got:\n' + - JSON.stringify(task, null, 2), - ); - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && console.log('TaskQueue: run anonymous task'); - task(); - } - } catch (e) { - e.message = - // $FlowFixMe[incompatible-type] - // $FlowFixMe[incompatible-use] - 'TaskQueue: Error with task ' + (task.name || '') + ': ' + e.message; - throw e; - } - } - } - - _queueStack: Array<{ - tasks: Array, - popable: boolean, - ... - }>; - _onMoreTasks: () => void; - - _getCurrentQueue(): Array { - const stackIdx = this._queueStack.length - 1; - const queue = this._queueStack[stackIdx]; - if ( - queue.popable && - queue.tasks.length === 0 && - this._queueStack.length > 1 - ) { - this._queueStack.pop(); - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && - console.log('TaskQueue: popped queue: ', { - stackIdx, - queueStackSize: this._queueStack.length, - }); - return this._getCurrentQueue(); - } else { - return queue.tasks; - } - } - - _genPromise(task: PromiseTask) { - // Each async task pushes it's own queue onto the queue stack. This - // effectively defers execution of previously queued tasks until the promise - // resolves, at which point we allow the new queue to be popped, which - // happens once it is fully processed. - this._queueStack.push({tasks: [], popable: false}); - const stackIdx = this._queueStack.length - 1; - const stackItem = this._queueStack[stackIdx]; - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && console.log('TaskQueue: push new queue: ', {stackIdx}); - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && console.log('TaskQueue: exec gen task ' + task.name); - task - .gen() - .then(() => { - /* $FlowFixMe[constant-condition] Error discovered during Constant - * Condition roll out. See https://fburl.com/workplace/1v97vimq. */ - DEBUG && - console.log('TaskQueue: onThen for gen task ' + task.name, { - stackIdx, - queueStackSize: this._queueStack.length, - }); - stackItem.popable = true; - this.hasTasksToProcess() && this._onMoreTasks(); - }) - .catch(ex => { - setTimeout(() => { - ex.message = `TaskQueue: Error resolving Promise in task ${task.name}: ${ex.message}`; - throw ex; - }, 0); - }); - } -} - -export default TaskQueue; diff --git a/packages/react-native/Libraries/Interaction/__tests__/InteractionManager-test.js b/packages/react-native/Libraries/Interaction/__tests__/InteractionManager-test.js deleted file mode 100644 index ce654dc0b7886f..00000000000000 --- a/packages/react-native/Libraries/Interaction/__tests__/InteractionManager-test.js +++ /dev/null @@ -1,342 +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. - * - * @noflow - * @format - */ - -'use strict'; - -import type {ReactNativeFeatureFlagsJsOnlyOverrides} from '../../../src/private/featureflags/ReactNativeFeatureFlags'; - -function importModules(overrides: ReactNativeFeatureFlagsJsOnlyOverrides) { - const ReactNativeFeatureFlags = require('../../../src/private/featureflags/ReactNativeFeatureFlags'); - - // Make sure to setup overrides before importing any modules. - ReactNativeFeatureFlags.override(overrides); - - const BatchedBridge = require('../../BatchedBridge/BatchedBridge').default; - const InteractionManager = require('../InteractionManager').default; - - jest.mock('../../vendor/core/ErrorUtils'); - jest.mock('../../BatchedBridge/BatchedBridge'); - - return { - BatchedBridge, - InteractionManager, - }; -} - -const isWindows = process.platform === 'win32'; -const itif = (condition: boolean) => (condition ? it : it.skip); - -function expectToBeCalledOnce( - fn: JestMockFn<$ReadOnlyArray, mixed>, -): void { - expect(fn.mock.calls.length).toBe(1); -} - -describe('InteractionManager', () => { - let InteractionManager; - let interactionStart; - let interactionComplete; - - beforeEach(() => { - jest.resetModules(); - ({InteractionManager} = importModules({ - disableInteractionManager: () => false, - })); - - interactionStart = jest.fn(); - interactionComplete = jest.fn(); - - InteractionManager.addListener( - InteractionManager.Events.interactionStart, - interactionStart, - ); - InteractionManager.addListener( - InteractionManager.Events.interactionComplete, - interactionComplete, - ); - }); - - it('throws when clearing an undefined handle', () => { - // $FlowExpectedError[incompatible-call] - expect(() => InteractionManager.clearInteractionHandle()).toThrow(); - }); - - it('notifies asynchronously when interaction starts', () => { - InteractionManager.createInteractionHandle(); - expect(interactionStart).not.toBeCalled(); - - jest.runAllTimers(); - expect(interactionStart).toBeCalled(); - expect(interactionComplete).not.toBeCalled(); - }); - - it('notifies asynchronously when interaction stops', () => { - const handle = InteractionManager.createInteractionHandle(); - jest.runAllTimers(); - interactionStart.mockClear(); - InteractionManager.clearInteractionHandle(handle); - expect(interactionComplete).not.toBeCalled(); - - jest.runAllTimers(); - expect(interactionStart).not.toBeCalled(); - expect(interactionComplete).toBeCalled(); - }); - - it('does not notify when started & stopped in same event loop', () => { - const handle = InteractionManager.createInteractionHandle(); - InteractionManager.clearInteractionHandle(handle); - - jest.runAllTimers(); - expect(interactionStart).not.toBeCalled(); - expect(interactionComplete).not.toBeCalled(); - }); - - it('does not notify when going from two -> one active interactions', () => { - InteractionManager.createInteractionHandle(); - const handle = InteractionManager.createInteractionHandle(); - jest.runAllTimers(); - - interactionStart.mockClear(); - interactionComplete.mockClear(); - - InteractionManager.clearInteractionHandle(handle); - jest.runAllTimers(); - expect(interactionStart).not.toBeCalled(); - expect(interactionComplete).not.toBeCalled(); - }); - - it('runs tasks asynchronously when there are interactions', () => { - const task = jest.fn(); - InteractionManager.runAfterInteractions(task); - expect(task).not.toBeCalled(); - - jest.runAllTimers(); - expect(task).toBeCalled(); - }); - - it('runs tasks when interactions complete', () => { - const task = jest.fn(); - const handle = InteractionManager.createInteractionHandle(); - InteractionManager.runAfterInteractions(task); - - jest.runAllTimers(); - InteractionManager.clearInteractionHandle(handle); - expect(task).not.toBeCalled(); - - jest.runAllTimers(); - expect(task).toBeCalled(); - }); - - it('does not run tasks twice', () => { - const task1 = jest.fn(); - const task2 = jest.fn(); - InteractionManager.runAfterInteractions(task1); - jest.runAllTimers(); - - InteractionManager.runAfterInteractions(task2); - jest.runAllTimers(); - - expectToBeCalledOnce(task1); - }); - - it('runs tasks added while processing previous tasks', () => { - const task1 = jest.fn(() => { - InteractionManager.runAfterInteractions(task2); - }); - const task2 = jest.fn(); - - InteractionManager.runAfterInteractions(task1); - expect(task2).not.toBeCalled(); - - jest.runAllTimers(); - - expect(task1).toBeCalled(); - expect(task2).toBeCalled(); - }); - - it('allows tasks to be cancelled', () => { - const task1 = jest.fn(); - const task2 = jest.fn(); - const promise1 = InteractionManager.runAfterInteractions(task1); - InteractionManager.runAfterInteractions(task2); - expect(task1).not.toBeCalled(); - expect(task2).not.toBeCalled(); - promise1.cancel(); - - jest.runAllTimers(); - expect(task1).not.toBeCalled(); - expect(task2).toBeCalled(); - }); -}); - -describe('promise tasks', () => { - let BatchedBridge; - let InteractionManager; - let sequenceId; - - function createSequenceTask(expectedSequenceId: number) { - return jest.fn(() => { - expect(++sequenceId).toBe(expectedSequenceId); - }); - } - - beforeEach(() => { - jest.resetModules(); - - ({BatchedBridge, InteractionManager} = importModules({ - disableInteractionManager: () => false, - })); - - sequenceId = 0; - }); - - it('should run a basic promise task', () => { - const task1 = jest.fn(() => { - expect(++sequenceId).toBe(1); - return new Promise(resolve => resolve()); - }); - InteractionManager.runAfterInteractions({gen: task1, name: 'gen1'}); - jest.runAllTimers(); - expectToBeCalledOnce(task1); - }); - - it('should handle nested promises', () => { - const task1 = jest.fn(() => { - expect(++sequenceId).toBe(1); - return new Promise(resolve => { - InteractionManager.runAfterInteractions({ - gen: task2, - name: 'gen2', - }).then(resolve); - }); - }); - const task2 = jest.fn(() => { - expect(++sequenceId).toBe(2); - return new Promise(resolve => resolve()); - }); - InteractionManager.runAfterInteractions({gen: task1, name: 'gen1'}); - jest.runAllTimers(); - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - }); - - it('should pause promise tasks during interactions then resume', () => { - const task1 = createSequenceTask(1); - const task2 = jest.fn(() => { - expect(++sequenceId).toBe(2); - return new Promise(resolve => { - setTimeout(() => { - InteractionManager.runAfterInteractions(task3).then(resolve); - }, 1); - }); - }); - const task3 = createSequenceTask(3); - InteractionManager.runAfterInteractions(task1); - InteractionManager.runAfterInteractions({gen: task2, name: 'gen2'}); - jest.runOnlyPendingTimers(); - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - const handle = InteractionManager.createInteractionHandle(); - jest.runAllTimers(); - jest.runAllTimers(); // Just to be sure... - expect(task3).not.toBeCalled(); - InteractionManager.clearInteractionHandle(handle); - jest.runAllTimers(); - expectToBeCalledOnce(task3); - }); - - it('should execute tasks in loop within deadline', () => { - InteractionManager.setDeadline(100); - BatchedBridge.getEventLoopRunningTime.mockReturnValue(10); - const task1 = createSequenceTask(1); - const task2 = createSequenceTask(2); - InteractionManager.runAfterInteractions(task1); - InteractionManager.runAfterInteractions(task2); - - jest.runOnlyPendingTimers(); - - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - }); - - it('should execute tasks one at a time if deadline exceeded', () => { - InteractionManager.setDeadline(100); - BatchedBridge.getEventLoopRunningTime.mockReturnValue(200); - const task1 = createSequenceTask(1); - const task2 = createSequenceTask(2); - InteractionManager.runAfterInteractions(task1); - InteractionManager.runAfterInteractions(task2); - - jest.runOnlyPendingTimers(); - - expectToBeCalledOnce(task1); - expect(task2).not.toBeCalled(); - - jest.runOnlyPendingTimers(); // resolve1 - jest.runOnlyPendingTimers(); // task2 - - expectToBeCalledOnce(task2); - }); - - const bigAsyncTest = resolveTest => { - jest.useRealTimers(); - - const task1 = createSequenceTask(1); - const task2 = jest.fn(() => { - expect(++sequenceId).toBe(2); - return new Promise(resolve => { - InteractionManager.runAfterInteractions(task3); - setTimeout(() => { - InteractionManager.runAfterInteractions({ - gen: task4, - name: 'gen4', - }).then(resolve); - }, 1); - }); - }); - const task3 = createSequenceTask(3); - const task4 = jest.fn(() => { - expect(++sequenceId).toBe(4); - return new Promise(resolve => { - InteractionManager.runAfterInteractions(task5).then(resolve); - }); - }); - const task5 = createSequenceTask(5); - const task6 = createSequenceTask(6); - - InteractionManager.runAfterInteractions(task1); - InteractionManager.runAfterInteractions({gen: task2, name: 'gen2'}); - InteractionManager.runAfterInteractions(task6); - - setTimeout(() => { - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - expectToBeCalledOnce(task3); - expectToBeCalledOnce(task4); - expectToBeCalledOnce(task5); - expectToBeCalledOnce(task6); - - resolveTest(); - }, 100); - }; - - itif(!isWindows)( - 'resolves async tasks recursively before other queued tasks', - () => { - return new Promise(bigAsyncTest); - }, - ); - - itif(!isWindows)('should also work with a deadline', () => { - InteractionManager.setDeadline(100); - BatchedBridge.getEventLoopRunningTime.mockReturnValue(200); - return new Promise(bigAsyncTest); - }); -}); diff --git a/packages/react-native/Libraries/Interaction/__tests__/TaskQueue-test.js b/packages/react-native/Libraries/Interaction/__tests__/TaskQueue-test.js deleted file mode 100644 index cd8f979afaae0d..00000000000000 --- a/packages/react-native/Libraries/Interaction/__tests__/TaskQueue-test.js +++ /dev/null @@ -1,169 +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. - * - * @noflow - * @format - */ - -'use strict'; - -const Promise = require('promise'); - -function expectToBeCalledOnce(fn) { - expect(fn.mock.calls.length).toBe(1); -} - -function clearTaskQueue(taskQueue) { - do { - jest.runAllTimers(); - taskQueue.processNext(); - jest.runAllTimers(); - } while (taskQueue.hasTasksToProcess()); -} - -describe('TaskQueue', () => { - let taskQueue; - let onMoreTasks; - let sequenceId; - function createSequenceTask(expectedSequenceId) { - return jest.fn(() => { - expect(++sequenceId).toBe(expectedSequenceId); - }); - } - beforeEach(() => { - jest.resetModules(); - onMoreTasks = jest.fn(); - const TaskQueue = require('../TaskQueue').default; - taskQueue = new TaskQueue({onMoreTasks}); - sequenceId = 0; - }); - - it('should run a basic task', () => { - const task1 = createSequenceTask(1); - taskQueue.enqueue({run: task1, name: 'run1'}); - expect(taskQueue.hasTasksToProcess()).toBe(true); - taskQueue.processNext(); - expectToBeCalledOnce(task1); - }); - - it('should handle blocking promise task', () => { - const task1 = jest.fn(() => { - return new Promise(resolve => { - setTimeout(() => { - expect(++sequenceId).toBe(1); - resolve(); - }, 1); - }); - }); - const task2 = createSequenceTask(2); - taskQueue.enqueue({gen: task1, name: 'gen1'}); - taskQueue.enqueue({run: task2, name: 'run2'}); - - taskQueue.processNext(); - - expectToBeCalledOnce(task1); - expect(task2).not.toBeCalled(); - expect(onMoreTasks).not.toBeCalled(); - expect(taskQueue.hasTasksToProcess()).toBe(false); - - clearTaskQueue(taskQueue); - - expectToBeCalledOnce(onMoreTasks); - expectToBeCalledOnce(task2); - }); - - it('should handle nested simple tasks', () => { - const task1 = jest.fn(() => { - expect(++sequenceId).toBe(1); - taskQueue.enqueue({run: task3, name: 'run3'}); - }); - const task2 = createSequenceTask(2); - const task3 = createSequenceTask(3); - taskQueue.enqueue({run: task1, name: 'run1'}); - taskQueue.enqueue({run: task2, name: 'run2'}); // not blocked by task 1 - - clearTaskQueue(taskQueue); - - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - expectToBeCalledOnce(task3); - }); - - it('should handle nested promises', () => { - const task1 = jest.fn(() => { - return new Promise(resolve => { - setTimeout(() => { - expect(++sequenceId).toBe(1); - taskQueue.enqueue({gen: task2, name: 'gen2'}); - taskQueue.enqueue({run: resolve, name: 'resolve1'}); - }, 1); - }); - }); - const task2 = jest.fn(() => { - return new Promise(resolve => { - setTimeout(() => { - expect(++sequenceId).toBe(2); - taskQueue.enqueue({run: task3, name: 'run3'}); - taskQueue.enqueue({run: resolve, name: 'resolve2'}); - }, 1); - }); - }); - const task3 = createSequenceTask(3); - const task4 = createSequenceTask(4); - taskQueue.enqueue({gen: task1, name: 'gen1'}); - taskQueue.enqueue({run: task4, name: 'run4'}); // blocked by task 1 promise - - clearTaskQueue(taskQueue); - - expectToBeCalledOnce(task1); - expectToBeCalledOnce(task2); - expectToBeCalledOnce(task3); - expectToBeCalledOnce(task4); - }); - - it('should be able to cancel tasks', () => { - const task1 = jest.fn(); - const task2 = createSequenceTask(1); - const task3 = jest.fn(); - const task4 = createSequenceTask(2); - taskQueue.enqueue(task1); - taskQueue.enqueue(task2); - taskQueue.enqueue(task3); - taskQueue.enqueue(task4); - taskQueue.cancelTasks([task1, task3]); - clearTaskQueue(taskQueue); - expect(task1).not.toBeCalled(); - expect(task3).not.toBeCalled(); - expectToBeCalledOnce(task2); - expectToBeCalledOnce(task4); - expect(taskQueue.hasTasksToProcess()).toBe(false); - }); - - it('should not crash when last task is cancelled', () => { - const task1 = jest.fn(); - taskQueue.enqueue(task1); - taskQueue.cancelTasks([task1]); - clearTaskQueue(taskQueue); - expect(task1).not.toBeCalled(); - expect(taskQueue.hasTasksToProcess()).toBe(false); - }); - - it('should not crash when task is cancelled between being started and resolved', () => { - const task1 = jest.fn(() => { - return new Promise(resolve => { - setTimeout(() => { - resolve(); - }, 1); - }); - }); - - taskQueue.enqueue({gen: task1, name: 'gen1'}); - taskQueue.processNext(); - taskQueue.cancelTasks([task1]); - - jest.runAllTimers(); - }); -}); diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 768e0c1f96b38d..eee18b46fb735a 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -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<<83d07f37fd6028027511209f02e7f056>> + * @generated SignedSource<> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -257,18 +257,17 @@ declare const Image: ImageType declare const ImageViewNativeComponent_default: HostComponent declare const InputAccessoryView: typeof InputAccessoryView_default declare const InputAccessoryView_default: React.ComponentType -declare const InteractionManager: typeof InteractionManager_default -declare const InteractionManager_default: typeof InteractionManagerImpl -declare const InteractionManagerImpl: { +declare const InteractionManager: typeof InteractionManagerStub_default +declare const InteractionManagerStub_default: { Events: { interactionComplete: "interactionComplete" interactionStart: "interactionStart" } - addListener: ( + addListener( eventType: string, listener: (...args: any) => unknown, context: unknown, - ) => EventSubscription + ): EventSubscription clearInteractionHandle(handle: Handle): void createInteractionHandle(): Handle runAfterInteractions(task: null | Task | undefined): { diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index f3e951d5584c03..ffea499db9b527 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -741,16 +741,6 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, - disableInteractionManager: { - defaultValue: true, - metadata: { - description: - 'Disables InteractionManager and replaces its scheduler with `setImmediate`.', - expectedReleaseValue: true, - purpose: 'release', - }, - ossReleaseStage: 'none', - }, enableAccessToHostTreeInFabric: { defaultValue: false, metadata: { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 91630f14a7cdab..13712805de4fdb 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<<9e32976a750c636ff0187a3530bb0657>> + * @generated SignedSource<<99d6ed3c0a9bfd543d58de5b2fdfffdf>> * @flow strict * @noformat */ @@ -32,7 +32,6 @@ export type ReactNativeFeatureFlagsJsOnly = $ReadOnly<{ animatedShouldDebounceQueueFlush: Getter, animatedShouldUseSingleOp: Getter, deferFlatListFocusChangeRenderUpdate: Getter, - disableInteractionManager: Getter, enableAccessToHostTreeInFabric: Getter, fixVirtualizeListCollapseWindowSize: Getter, isLayoutAnimationEnabled: Getter, @@ -133,11 +132,6 @@ export const animatedShouldUseSingleOp: Getter = createJavaScriptFlagGe */ export const deferFlatListFocusChangeRenderUpdate: Getter = createJavaScriptFlagGetter('deferFlatListFocusChangeRenderUpdate', false); -/** - * Disables InteractionManager and replaces its scheduler with `setImmediate`. - */ -export const disableInteractionManager: Getter = createJavaScriptFlagGetter('disableInteractionManager', true); - /** * Enables access to the host tree in Fabric using DOM-compatible APIs. */ From 5d4d1ce84b89487fb0ad190dc247978ebf33ab1a Mon Sep 17 00:00:00 2001 From: Tim Yung Date: Thu, 17 Jul 2025 12:59:13 -0700 Subject: [PATCH 0171/1383] RN: Cleanup `scheduleAnimatedCleanupInMicrotask ` Flag (#52685) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52685 Cleans up the `scheduleAnimatedCleanupInMicrotask ` feature flag and deletes code paths that are now unreachable. Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D78498600 fbshipit-source-id: 307562030373742e64968ae4c92d6bfbb48ddc71 --- .../Animated/__tests__/Animated-test.js | 55 ------------------- .../ReactNativeFeatureFlags.config.js | 10 ---- .../animated/createAnimatedPropsHook.js | 49 +---------------- .../featureflags/ReactNativeFeatureFlags.js | 8 +-- 4 files changed, 2 insertions(+), 120 deletions(-) diff --git a/packages/react-native/Libraries/Animated/__tests__/Animated-test.js b/packages/react-native/Libraries/Animated/__tests__/Animated-test.js index 2b7a43c95e7566..2853ffdfcc1170 100644 --- a/packages/react-native/Libraries/Animated/__tests__/Animated-test.js +++ b/packages/react-native/Libraries/Animated/__tests__/Animated-test.js @@ -31,12 +31,8 @@ function mockQueueMicrotask() { } describe('Animated', () => { - let ReactNativeFeatureFlags; - beforeEach(() => { jest.resetModules(); - - ReactNativeFeatureFlags = require('../../../src/private/featureflags/ReactNativeFeatureFlags'); }); mockQueueMicrotask(); @@ -113,50 +109,7 @@ describe('Animated', () => { expect(callback.mock.calls.length).toBe(1); }); - it('does not detach on updates', async () => { - ReactNativeFeatureFlags.override({ - scheduleAnimatedCleanupInMicrotask: () => false, - }); - - const opacity = new Animated.Value(0); - jest.spyOn(opacity, '__detach'); - - const root = await create(); - expect(opacity.__detach).not.toBeCalled(); - - await update(root, ); - expect(opacity.__detach).not.toBeCalled(); - - await unmount(root); - expect(opacity.__detach).toBeCalled(); - }); - - it('stops animation when detached', async () => { - ReactNativeFeatureFlags.override({ - scheduleAnimatedCleanupInMicrotask: () => false, - }); - - const opacity = new Animated.Value(0); - const callback = jest.fn(); - - const root = await create(); - - Animated.timing(opacity, { - toValue: 10, - duration: 1000, - useNativeDriver: false, - }).start(callback); - - await unmount(root); - - expect(callback).toBeCalledWith({finished: false}); - }); - it('detaches only on unmount (in a microtask)', async () => { - ReactNativeFeatureFlags.override({ - scheduleAnimatedCleanupInMicrotask: () => true, - }); - const opacity = new Animated.Value(0); jest.spyOn(opacity, '__detach'); @@ -175,10 +128,6 @@ describe('Animated', () => { }); it('restores default values only on update (in a microtask)', async () => { - ReactNativeFeatureFlags.override({ - scheduleAnimatedCleanupInMicrotask: () => true, - }); - const __restoreDefaultValues = jest.spyOn( AnimatedProps.prototype, '__restoreDefaultValues', @@ -213,10 +162,6 @@ describe('Animated', () => { }); it('stops animation when detached (in a microtask)', async () => { - ReactNativeFeatureFlags.override({ - scheduleAnimatedCleanupInMicrotask: () => true, - }); - const opacity = new Animated.Value(0); const callback = jest.fn(); diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index ffea499db9b527..fca0d50a93a932 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -783,16 +783,6 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, - scheduleAnimatedCleanupInMicrotask: { - defaultValue: true, - metadata: { - description: - 'Changes the cleanup of `AnimatedProps` to occur in a microtask instead of synchronously during effect cleanup (for unmount) or subsequent mounts (for updates).', - expectedReleaseValue: true, - purpose: 'release', - }, - ossReleaseStage: 'none', - }, shouldUseAnimatedObjectForTransform: { defaultValue: false, metadata: { diff --git a/packages/react-native/src/private/animated/createAnimatedPropsHook.js b/packages/react-native/src/private/animated/createAnimatedPropsHook.js index 072fdea2510bd7..6c674f1728b14d 100644 --- a/packages/react-native/src/private/animated/createAnimatedPropsHook.js +++ b/packages/react-native/src/private/animated/createAnimatedPropsHook.js @@ -89,13 +89,6 @@ export default function createAnimatedPropsHook( }; }); - // NOTE: This feature flag must be evaluated inside the hook because this - // module factory can be evaluated much sooner, before overrides are set. - const useAnimatedPropsLifecycle = - ReactNativeFeatureFlags.scheduleAnimatedCleanupInMicrotask() - ? useAnimatedPropsLifecycleWithCleanupInMicrotask - : useAnimatedPropsLifecycleWithPrevNodeRef; - useAnimatedPropsLifecycle(node); // TODO: This "effect" does three things: @@ -262,44 +255,6 @@ function addAnimatedValuesListenersToProps( } } -/** - * Manages the lifecycle of the supplied `AnimatedProps` by invoking `__attach` - * and `__detach`. However, this is more complicated because `AnimatedProps` - * uses reference counting to determine when to recursively detach its children - * nodes. So in order to optimize this, we avoid detaching until the next attach - * unless we are unmounting. - */ -function useAnimatedPropsLifecycleWithPrevNodeRef(node: AnimatedProps): void { - const prevNodeRef = useRef(null); - const isUnmountingRef = useRef(false); - - useInsertionEffect(() => { - isUnmountingRef.current = false; - return () => { - isUnmountingRef.current = true; - }; - }, []); - - useInsertionEffect(() => { - node.__attach(); - if (prevNodeRef.current != null) { - const prevNode = prevNodeRef.current; - // TODO: Stop restoring default values (unless `reset` is called). - prevNode.__restoreDefaultValues(); - prevNode.__detach(); - prevNodeRef.current = null; - } - return () => { - if (isUnmountingRef.current) { - // NOTE: Do not restore default values on unmount, see D18197735. - node.__detach(); - } else { - prevNodeRef.current = node; - } - }; - }, [node]); -} - /** * Manages the lifecycle of the supplied `AnimatedProps` by invoking `__attach` * and `__detach`. However, `__detach` occurs in a microtask for these reasons: @@ -314,9 +269,7 @@ function useAnimatedPropsLifecycleWithPrevNodeRef(node: AnimatedProps): void { * callbacks may update state, which is unsupported and will force synchronous * updates. */ -function useAnimatedPropsLifecycleWithCleanupInMicrotask( - node: AnimatedProps, -): void { +function useAnimatedPropsLifecycle(node: AnimatedProps): void { const isMounted = useRef(false); useInsertionEffect(() => { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 13712805de4fdb..d5d72cac560bca 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<<99d6ed3c0a9bfd543d58de5b2fdfffdf>> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -36,7 +36,6 @@ export type ReactNativeFeatureFlagsJsOnly = $ReadOnly<{ fixVirtualizeListCollapseWindowSize: Getter, isLayoutAnimationEnabled: Getter, reduceDefaultPropsInView: Getter, - scheduleAnimatedCleanupInMicrotask: Getter, shouldUseAnimatedObjectForTransform: Getter, shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter, shouldUseSetNativePropsInFabric: Getter, @@ -152,11 +151,6 @@ export const isLayoutAnimationEnabled: Getter = createJavaScriptFlagGet */ export const reduceDefaultPropsInView: Getter = createJavaScriptFlagGetter('reduceDefaultPropsInView', true); -/** - * Changes the cleanup of `AnimatedProps` to occur in a microtask instead of synchronously during effect cleanup (for unmount) or subsequent mounts (for updates). - */ -export const scheduleAnimatedCleanupInMicrotask: Getter = createJavaScriptFlagGetter('scheduleAnimatedCleanupInMicrotask', true); - /** * Enables use of AnimatedObject for animating transform values. */ From d78c242e4d86f2d16aa86c7cff07e823e99c5317 Mon Sep 17 00:00:00 2001 From: Tim Yung Date: Thu, 17 Jul 2025 12:59:13 -0700 Subject: [PATCH 0172/1383] RN: Enable `enableVirtualViewRenderState` by Default (#52686) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52686 Enables the `enableVirtualViewRenderState` feature flag by default. Also, fixed classification for this and the `enableVirtualViewWindowFocusDetection` feature flags. (They were incorrect.) Changelog: [Internal] Reviewed By: lunaleaps Differential Revision: D78500846 fbshipit-source-id: 099adaa4ed0026c8bb7438df869564d76a999007 --- .../featureflags/ReactNativeFeatureFlagsDefaults.kt | 4 ++-- .../react/featureflags/ReactNativeFeatureFlagsDefaults.h | 4 ++-- .../featureflags/ReactNativeFeatureFlags.config.js | 8 +++++--- .../src/private/featureflags/ReactNativeFeatureFlags.js | 4 ++-- 4 files changed, 11 insertions(+), 9 deletions(-) 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 b114b19fca255e..cded63ed7460d5 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<<99019349a8f3642c42e6dac5f1476e7f>> + * @generated SignedSource<> */ /** @@ -101,7 +101,7 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi override fun enableVirtualViewDebugFeatures(): Boolean = false - override fun enableVirtualViewRenderState(): Boolean = false + override fun enableVirtualViewRenderState(): Boolean = true override fun enableVirtualViewWindowFocusDetection(): Boolean = false diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h index 02bc59418b3f47..b90760e874f863 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<> + * @generated SignedSource<<614fe0894f6235d879a0b29e7dab7759>> */ /** @@ -184,7 +184,7 @@ class ReactNativeFeatureFlagsDefaults : public ReactNativeFeatureFlagsProvider { } bool enableVirtualViewRenderState() override { - return false; + return true; } bool enableVirtualViewWindowFocusDetection() override { diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index fca0d50a93a932..97733068a39a43 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -462,22 +462,24 @@ const definitions: FeatureFlagDefinitions = { ossReleaseStage: 'none', }, enableVirtualViewRenderState: { - defaultValue: false, + defaultValue: true, metadata: { + dateAdded: '2025-06-25', description: 'Enables reading render state when dispatching VirtualView events.', expectedReleaseValue: true, - purpose: 'operational', + purpose: 'experimentation', }, ossReleaseStage: 'none', }, enableVirtualViewWindowFocusDetection: { defaultValue: false, metadata: { + dateAdded: '2025-06-24', description: 'Enables window focus detection for prioritizing VirtualView events.', expectedReleaseValue: true, - purpose: 'operational', + purpose: 'experimentation', }, ossReleaseStage: 'none', }, diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index d5d72cac560bca..4e390c88f5b6c0 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<> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -334,7 +334,7 @@ export const enableVirtualViewDebugFeatures: Getter = createNativeFlagG /** * Enables reading render state when dispatching VirtualView events. */ -export const enableVirtualViewRenderState: Getter = createNativeFlagGetter('enableVirtualViewRenderState', false); +export const enableVirtualViewRenderState: Getter = createNativeFlagGetter('enableVirtualViewRenderState', true); /** * Enables window focus detection for prioritizing VirtualView events. */ From 23c8787fe2fe8846178664a4c8c35779079b43a4 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Thu, 17 Jul 2025 17:30:43 -0700 Subject: [PATCH 0173/1383] Add annotations to fix future errors after fix for unsound array types (#52691) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52691 Unannotated array literals are unsound in Flow right now. This diff adds in annotations and makes a few things readonly, to reduce future errors. Changelog: [Internal] Reviewed By: marcoww6 Differential Revision: D78519638 fbshipit-source-id: d98a7668ecf97bcc87dcb3fad25ade736d885d9a --- .../examples/Accessibility/AccessibilityAndroidExample.js | 4 +++- .../js/examples/Accessibility/AccessibilityExample.js | 3 ++- .../js/examples/Accessibility/AccessibilityIOSExample.js | 4 +++- .../js/examples/ActionSheetIOS/ActionSheetIOSExample.js | 3 ++- .../rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js | 4 +++- .../rn-tester/js/examples/Appearance/AppearanceExample.js | 3 ++- .../rn-tester/js/examples/BoxShadow/BoxShadowExample.js | 4 +++- packages/rn-tester/js/examples/Button/ButtonExample.js | 4 +++- .../js/examples/ContentURLAndroid/ContentURLAndroid.js | 4 +++- packages/rn-tester/js/examples/Crash/CrashExample.js | 3 ++- packages/rn-tester/js/examples/Cursor/CursorExample.js | 4 +++- .../rn-tester/js/examples/DevSettings/DevSettingsExample.js | 4 +++- .../rn-tester/js/examples/Dimensions/DimensionsExample.js | 4 +++- .../DrawerLayoutAndroid/DrawerLayoutAndroidExample.js | 3 ++- .../js/examples/FabricInteropLayer/FabricInteropLayer.js | 3 ++- .../FocusEventsExample/FocusEventsExample.android.js | 4 +++- .../InputAccessoryView/InputAccessoryViewExample.js | 4 +++- .../js/examples/InvalidProps/InvalidPropsExample.js | 4 +++- .../JSResponderHandlerExample/JSResponderHandlerExample.js | 4 +++- .../KeyboardAvoidingView/KeyboardAvoidingViewExample.js | 4 +++- .../rn-tester/js/examples/Layout/LayoutAnimationExample.js | 4 +++- .../rn-tester/js/examples/Layout/LayoutEventsExample.js | 3 ++- packages/rn-tester/js/examples/Layout/LayoutExample.js | 3 ++- .../js/examples/LinearGradient/LinearGradientExample.js | 3 ++- packages/rn-tester/js/examples/Linking/LinkingExample.js | 4 +++- .../js/examples/NativeAnimation/NativeAnimationsExample.js | 3 ++- .../js/examples/NewAppScreen/NewAppScreenExample.js | 4 +++- .../js/examples/NewArchitecture/NewArchitectureExample.js | 4 +++- .../js/examples/OSSLibraryExample/OSSLibraryExample.js | 3 ++- .../examples/OrientationChange/OrientationChangeExample.js | 4 +++- .../js/examples/PanResponder/PanResponderExample.js | 4 +++- .../js/examples/PermissionsAndroid/PermissionsExample.js | 3 ++- .../rn-tester/js/examples/PixelRatio/PixelRatioExample.js | 4 +++- .../js/examples/PlatformColor/PlatformColorExample.js | 3 ++- .../js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js | 3 ++- .../js/examples/RCTRootView/RCTRootViewIOSExample.js | 4 +++- packages/rn-tester/js/examples/RTL/RTLExample.js | 4 +++- .../js/examples/RadialGradient/RadialGradientExample.js | 3 ++- .../js/examples/RefreshControl/RefreshControlExample.js | 4 +++- .../js/examples/SafeAreaView/SafeAreaViewExample.js | 4 +++- .../js/examples/ScrollView/ScrollViewAnimatedExample.js | 3 ++- .../ScrollView/ScrollViewIndicatorInsetsIOSExample.js | 4 +++- .../ScrollView/ScrollViewKeyboardInsetsIOSExample.js | 4 +++- .../js/examples/ScrollView/ScrollViewSimpleExample.js | 4 +++- .../rn-tester/js/examples/SectionList/SectionListIndex.js | 4 +++- packages/rn-tester/js/examples/Share/ShareExample.js | 4 +++- packages/rn-tester/js/examples/Snapshot/SnapshotExample.js | 4 +++- .../examples/SwipeableCardExample/SwipeableCardExample.js | 3 ++- packages/rn-tester/js/examples/Switch/SwitchExample.js | 6 +++--- .../rn-tester/js/examples/TextInput/TextInputKeyProp.js | 4 +++- packages/rn-tester/js/examples/Timer/TimerExample.js | 4 +++- .../js/examples/ToastAndroid/ToastAndroidExample.js | 4 +++- .../rn-tester/js/examples/Transform/TransformExample.js | 4 +++- .../TransparentHitTest/TransparentHitTestExample.js | 4 +++- .../js/examples/TurboModule/LegacyModuleExample.js | 4 +++- .../js/examples/TurboModule/TurboCxxModuleExample.js | 4 +++- .../rn-tester/js/examples/TurboModule/TurboModuleExample.js | 4 +++- .../rn-tester/js/examples/Vibration/VibrationExample.js | 4 +++- .../rn-tester/js/examples/WebSocket/WebSocketExample.js | 4 +++- packages/rn-tester/js/examples/XHR/XHRExample.js | 4 +++- 60 files changed, 163 insertions(+), 62 deletions(-) diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityAndroidExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityAndroidExample.js index df92694a0ead6f..accc8b3ff3ae99 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityAndroidExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityAndroidExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterBlock from '../../components/RNTesterBlock'; import RNTesterPage from '../../components/RNTesterPage'; import RNTesterText from '../../components/RNTesterText'; @@ -282,4 +284,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js index 32955d3d9ef565..696de6e68d3f6c 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {EventSubscription, GestureResponderEvent} from 'react-native'; import RNTesterBlock from '../../components/RNTesterBlock'; @@ -2250,4 +2251,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityIOSExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityIOSExample.js index 9271ad55471e68..0c96afb4afb42e 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityIOSExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityIOSExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const {RNTesterThemeContext} = require('../../components/RNTesterTheme'); const React = require('react'); const {Alert, Text, View} = require('react-native'); @@ -83,4 +85,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js b/packages/rn-tester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js index 8052c83066f65d..68c0e255ea6778 100644 --- a/packages/rn-tester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js +++ b/packages/rn-tester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {HostInstance} from 'react-native'; import {RNTesterThemeContext} from '../../components/RNTesterTheme'; @@ -573,4 +574,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js index 02def051b954ff..f5447314416cfd 100644 --- a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js +++ b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import AnExSet from './AnExSet'; import React from 'react'; import { @@ -396,4 +398,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Appearance/AppearanceExample.js b/packages/rn-tester/js/examples/Appearance/AppearanceExample.js index 23751f76b93b92..427653514f68c1 100644 --- a/packages/rn-tester/js/examples/Appearance/AppearanceExample.js +++ b/packages/rn-tester/js/examples/Appearance/AppearanceExample.js @@ -8,6 +8,7 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ColorSchemeName} from 'react-native'; import RNTesterText from '../../components/RNTesterText'; @@ -245,4 +246,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/BoxShadow/BoxShadowExample.js b/packages/rn-tester/js/examples/BoxShadow/BoxShadowExample.js index a6d66167b06502..9a69c6b6d2580b 100644 --- a/packages/rn-tester/js/examples/BoxShadow/BoxShadowExample.js +++ b/packages/rn-tester/js/examples/BoxShadow/BoxShadowExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {Image, StyleSheet, View} from 'react-native'; @@ -191,4 +193,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Button/ButtonExample.js b/packages/rn-tester/js/examples/Button/ButtonExample.js index d9c30a8b938c2c..cbedc3f8f11d41 100644 --- a/packages/rn-tester/js/examples/Button/ButtonExample.js +++ b/packages/rn-tester/js/examples/Button/ButtonExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const {RNTesterThemeContext} = require('../../components/RNTesterTheme'); const React = require('react'); const {Alert, Button, StyleSheet, View} = require('react-native'); @@ -221,7 +223,7 @@ exports.examples = [ ); }, }, -]; +] as Array; const styles = StyleSheet.create({ container: { diff --git a/packages/rn-tester/js/examples/ContentURLAndroid/ContentURLAndroid.js b/packages/rn-tester/js/examples/ContentURLAndroid/ContentURLAndroid.js index 650986c7097ce3..81f88a78bf16d7 100644 --- a/packages/rn-tester/js/examples/ContentURLAndroid/ContentURLAndroid.js +++ b/packages/rn-tester/js/examples/ContentURLAndroid/ContentURLAndroid.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterBlock from '../../components/RNTesterBlock'; import RNTesterPage from '../../components/RNTesterPage'; import RNTesterText from '../../components/RNTesterText'; @@ -116,4 +118,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Crash/CrashExample.js b/packages/rn-tester/js/examples/Crash/CrashExample.js index e85482a1ee296f..c492f75488921e 100644 --- a/packages/rn-tester/js/examples/Crash/CrashExample.js +++ b/packages/rn-tester/js/examples/Crash/CrashExample.js @@ -8,6 +8,7 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {Node} from 'react'; import React from 'react'; @@ -37,4 +38,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Cursor/CursorExample.js b/packages/rn-tester/js/examples/Cursor/CursorExample.js index 231f3a5338c837..4a1b04f8d7ce28 100644 --- a/packages/rn-tester/js/examples/Cursor/CursorExample.js +++ b/packages/rn-tester/js/examples/Cursor/CursorExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -107,4 +109,4 @@ exports.examples = [ description: 'Views with a cursor do not get flattened', render: CursorExampleViewFlattening, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/DevSettings/DevSettingsExample.js b/packages/rn-tester/js/examples/DevSettings/DevSettingsExample.js index 2210bfd612af4a..fa6064b667615d 100644 --- a/packages/rn-tester/js/examples/DevSettings/DevSettingsExample.js +++ b/packages/rn-tester/js/examples/DevSettings/DevSettingsExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {Alert, Button, DevSettings} from 'react-native'; @@ -44,4 +46,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js index 8d246d09aa1f7b..ccc067bffec644 100644 --- a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js +++ b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React, {useEffect, useState} from 'react'; import {Dimensions, useWindowDimensions} from 'react-native'; @@ -60,4 +62,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js b/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js index 92a034ae195991..c0360008167ce6 100644 --- a/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js +++ b/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {Node} from 'react'; import {RNTesterThemeContext} from '../../components/RNTesterTheme'; @@ -104,4 +105,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/FabricInteropLayer/FabricInteropLayer.js b/packages/rn-tester/js/examples/FabricInteropLayer/FabricInteropLayer.js index 75a4c5f1019cf5..3d41657654dcae 100644 --- a/packages/rn-tester/js/examples/FabricInteropLayer/FabricInteropLayer.js +++ b/packages/rn-tester/js/examples/FabricInteropLayer/FabricInteropLayer.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ViewProps} from 'react-native'; import React, {useState} from 'react'; @@ -155,4 +156,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js b/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js index f52a8e723d47c1..547c9908fad6fe 100644 --- a/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js +++ b/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import {useState} from 'react'; import {Alert, Pressable, StyleSheet, TextInput, View} from 'react-native'; @@ -184,5 +186,5 @@ export default { return ; }, }, - ], + ] as Array, }; diff --git a/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js b/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js index 532a9ea2837bd9..9d4e551bc0b18d 100644 --- a/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js +++ b/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import {useTheme} from '../../components/RNTesterTheme'; import {useState} from 'react'; import { @@ -111,4 +113,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/InvalidProps/InvalidPropsExample.js b/packages/rn-tester/js/examples/InvalidProps/InvalidPropsExample.js index a24116faa38712..bff02276eb22a0 100644 --- a/packages/rn-tester/js/examples/InvalidProps/InvalidPropsExample.js +++ b/packages/rn-tester/js/examples/InvalidProps/InvalidPropsExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import * as React from 'react'; import {View} from 'react-native'; @@ -19,7 +21,7 @@ export const category = 'Other'; export const description = 'Examples of passing invalid prop values and how they fall back to expected defaults.'; -export const examples = [ +export const examples: Array = [ { title: 'View flex', render(): React.Node { diff --git a/packages/rn-tester/js/examples/JSResponderHandlerExample/JSResponderHandlerExample.js b/packages/rn-tester/js/examples/JSResponderHandlerExample/JSResponderHandlerExample.js index 35a03e96aef254..01968efb3e20d4 100644 --- a/packages/rn-tester/js/examples/JSResponderHandlerExample/JSResponderHandlerExample.js +++ b/packages/rn-tester/js/examples/JSResponderHandlerExample/JSResponderHandlerExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {PanResponder, ScrollView, StyleSheet, View} from 'react-native'; @@ -60,7 +62,7 @@ exports.examples = [ ); }, }, -]; +] as Array; const styles = StyleSheet.create({ container: { diff --git a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js index 62f66258d9c9b3..610ec9588d4a41 100644 --- a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js +++ b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import React, {useState} from 'react'; import { Alert, @@ -276,4 +278,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Layout/LayoutAnimationExample.js b/packages/rn-tester/js/examples/Layout/LayoutAnimationExample.js index b9f12ee89e2738..a83d552799dce7 100644 --- a/packages/rn-tester/js/examples/Layout/LayoutAnimationExample.js +++ b/packages/rn-tester/js/examples/Layout/LayoutAnimationExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import { @@ -389,4 +391,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Layout/LayoutEventsExample.js b/packages/rn-tester/js/examples/Layout/LayoutEventsExample.js index a93d4ac4fc9aab..ee4e78ccefdfb6 100644 --- a/packages/rn-tester/js/examples/Layout/LayoutEventsExample.js +++ b/packages/rn-tester/js/examples/Layout/LayoutEventsExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type { ViewLayout, ViewLayoutEvent, @@ -163,4 +164,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Layout/LayoutExample.js b/packages/rn-tester/js/examples/Layout/LayoutExample.js index 27af6b6acc36e7..f0bd1d27aa6542 100644 --- a/packages/rn-tester/js/examples/Layout/LayoutExample.js +++ b/packages/rn-tester/js/examples/Layout/LayoutExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet'; import RNTesterBlock from '../../components/RNTesterBlock'; @@ -210,4 +211,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js b/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js index 359604f3ebcf76..ed787dfc4e2371 100644 --- a/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js +++ b/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet'; import RNTesterText from '../../components/RNTesterText'; @@ -305,4 +306,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Linking/LinkingExample.js b/packages/rn-tester/js/examples/Linking/LinkingExample.js index 57df6c12eed614..34a45fcbd8aa93 100644 --- a/packages/rn-tester/js/examples/Linking/LinkingExample.js +++ b/packages/rn-tester/js/examples/Linking/LinkingExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterBlock from '../../components/RNTesterBlock'; import RNTesterText from '../../components/RNTesterText'; import React from 'react'; @@ -168,4 +170,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/NativeAnimation/NativeAnimationsExample.js b/packages/rn-tester/js/examples/NativeAnimation/NativeAnimationsExample.js index 42ca8d021348dc..7aab9b50ddad15 100644 --- a/packages/rn-tester/js/examples/NativeAnimation/NativeAnimationsExample.js +++ b/packages/rn-tester/js/examples/NativeAnimation/NativeAnimationsExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; import RNTesterSettingSwitchRow from '../../components/RNTesterSettingSwitchRow'; @@ -657,4 +658,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/NewAppScreen/NewAppScreenExample.js b/packages/rn-tester/js/examples/NewAppScreen/NewAppScreenExample.js index 519728dc4399ba..6e3fc3a6c55f30 100644 --- a/packages/rn-tester/js/examples/NewAppScreen/NewAppScreenExample.js +++ b/packages/rn-tester/js/examples/NewAppScreen/NewAppScreenExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const {NewAppScreen} = require('@react-native/new-app-screen'); const React = require('react'); const {ScrollView} = require('react-native'); @@ -27,4 +29,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/NewArchitecture/NewArchitectureExample.js b/packages/rn-tester/js/examples/NewArchitecture/NewArchitectureExample.js index 30e5d17f6ea312..0b68c170f09351 100644 --- a/packages/rn-tester/js/examples/NewArchitecture/NewArchitectureExample.js +++ b/packages/rn-tester/js/examples/NewArchitecture/NewArchitectureExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import MyNativeView from '../../../NativeComponentExample/js/MyNativeView'; import * as React from 'react'; @@ -28,4 +30,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js b/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js index 82048172a55615..c7217a33c663c5 100644 --- a/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js +++ b/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {NativeComponentType} from '@react-native/oss-library-example'; import RNTesterText from '../../components/RNTesterText'; @@ -126,4 +127,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/OrientationChange/OrientationChangeExample.js b/packages/rn-tester/js/examples/OrientationChange/OrientationChangeExample.js index 2bfcdc2a325f4f..bcf6e345b09f2b 100644 --- a/packages/rn-tester/js/examples/OrientationChange/OrientationChangeExample.js +++ b/packages/rn-tester/js/examples/OrientationChange/OrientationChangeExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {useEffect, useState} from 'react'; @@ -57,4 +59,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js b/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js index e7019c6fd1a8d4..ac5b246762dbaf 100644 --- a/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js +++ b/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {useMemo, useRef, useState} from 'react'; import {PanResponder, StyleSheet, View} from 'react-native'; @@ -88,4 +90,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/PermissionsAndroid/PermissionsExample.js b/packages/rn-tester/js/examples/PermissionsAndroid/PermissionsExample.js index 71c17ab6dcead7..94f9eedbadbbec 100644 --- a/packages/rn-tester/js/examples/PermissionsAndroid/PermissionsExample.js +++ b/packages/rn-tester/js/examples/PermissionsAndroid/PermissionsExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {Permission} from 'react-native'; import RNTesterButton from '../../components/RNTesterButton'; @@ -158,4 +159,4 @@ exports.examples = [ 'Short example of how to use the runtime permissions API introduced in Android M.', render: (): React.Node => , }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/PixelRatio/PixelRatioExample.js b/packages/rn-tester/js/examples/PixelRatio/PixelRatioExample.js index edf50c40e18f71..5bd4ee6b6d5689 100644 --- a/packages/rn-tester/js/examples/PixelRatio/PixelRatioExample.js +++ b/packages/rn-tester/js/examples/PixelRatio/PixelRatioExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import {RNTesterThemeContext} from '../../components/RNTesterTheme'; import * as React from 'react'; @@ -209,4 +211,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js b/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js index 8285842c8adede..9bc01fcd3af237 100644 --- a/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js +++ b/packages/rn-tester/js/examples/PlatformColor/PlatformColorExample.js @@ -8,6 +8,7 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ColorValue} from 'react-native'; import RNTesterText from '../../components/RNTesterText'; @@ -357,4 +358,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js b/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js index 2bcf54f758b5dd..f2e7de238e6013 100644 --- a/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js +++ b/packages/rn-tester/js/examples/PopupMenuAndroid/PopupMenuAndroidExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {PopupMenuAndroidInstance} from '@react-native/popup-menu-android'; import type {Node} from 'react'; @@ -69,4 +70,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/RCTRootView/RCTRootViewIOSExample.js b/packages/rn-tester/js/examples/RCTRootView/RCTRootViewIOSExample.js index d60602438a2bd5..00a192d0915728 100644 --- a/packages/rn-tester/js/examples/RCTRootView/RCTRootViewIOSExample.js +++ b/packages/rn-tester/js/examples/RCTRootView/RCTRootViewIOSExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const React = require('react'); const { StyleSheet, @@ -95,4 +97,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/RTL/RTLExample.js b/packages/rn-tester/js/examples/RTL/RTLExample.js index e0e7c075745a09..608fd35c8a5a5b 100644 --- a/packages/rn-tester/js/examples/RTL/RTLExample.js +++ b/packages/rn-tester/js/examples/RTL/RTLExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTexterText from '../../components/RNTesterText'; import React from 'react'; import { @@ -830,4 +832,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js b/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js index 8f60ceb758b675..b15453e8a316a1 100644 --- a/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js +++ b/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet'; import RNTesterText from '../../components/RNTesterText'; @@ -286,4 +287,4 @@ exports.examples = [ ); }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/RefreshControl/RefreshControlExample.js b/packages/rn-tester/js/examples/RefreshControl/RefreshControlExample.js index d9301a46b3d061..0e02f68e0312ff 100644 --- a/packages/rn-tester/js/examples/RefreshControl/RefreshControlExample.js +++ b/packages/rn-tester/js/examples/RefreshControl/RefreshControlExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import { @@ -154,4 +156,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js b/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js index d5905a95acfff0..d1e6b31c209dfb 100644 --- a/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js +++ b/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {useState} from 'react'; @@ -104,4 +106,4 @@ exports.examples = [ 'Use instead.': string), render: (): React.Node => , }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewAnimatedExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewAnimatedExample.js index 35f15cf801b766..c19c1cdb198f04 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewAnimatedExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewAnimatedExample.js @@ -10,6 +10,7 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; const React = require('react'); @@ -97,4 +98,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewIndicatorInsetsIOSExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewIndicatorInsetsIOSExample.js index 3dec167843d39a..0649f16954e77e 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewIndicatorInsetsIOSExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewIndicatorInsetsIOSExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {useState} from 'react'; import { @@ -134,4 +136,4 @@ exports.examples = [ title: ' automaticallyAdjustsScrollIndicatorInsets Example', render: (): React.Node => , }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewKeyboardInsetsIOSExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewKeyboardInsetsIOSExample.js index 28ddbd77867f8a..a3dac7c5ddfe37 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewKeyboardInsetsIOSExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewKeyboardInsetsIOSExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {useState} from 'react'; import { @@ -185,4 +187,4 @@ exports.examples = [ title: ' automaticallyAdjustKeyboardInsets Example', render: (): React.Node => , }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewSimpleExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewSimpleExample.js index a83cf2b4a605a2..ff9c35f91ebe2f 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewSimpleExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewSimpleExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const React = require('react'); const { ScrollView, @@ -141,4 +143,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/SectionList/SectionListIndex.js b/packages/rn-tester/js/examples/SectionList/SectionListIndex.js index 0c92485428c212..6754c87962b45e 100644 --- a/packages/rn-tester/js/examples/SectionList/SectionListIndex.js +++ b/packages/rn-tester/js/examples/SectionList/SectionListIndex.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import ContentInset from './SectionList-contentInset'; import inverted from './SectionList-inverted'; import onEndReached from './SectionList-onEndReached'; @@ -43,4 +45,4 @@ exports.examples = [ onViewableItemsChanged_horizontal_waitForInteraction, onViewableItemsChanged_horizontal_offScreen_noWaitForInteraction, onViewableItemsChanged_offScreen_noWaitForInteraction, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Share/ShareExample.js b/packages/rn-tester/js/examples/Share/ShareExample.js index 7734d64bf9c9fa..8c06c4f01be6f1 100644 --- a/packages/rn-tester/js/examples/Share/ShareExample.js +++ b/packages/rn-tester/js/examples/Share/ShareExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {useState} from 'react'; @@ -156,4 +158,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Snapshot/SnapshotExample.js b/packages/rn-tester/js/examples/Snapshot/SnapshotExample.js index f5584d1eba5046..91dcf8d856512b 100644 --- a/packages/rn-tester/js/examples/Snapshot/SnapshotExample.js +++ b/packages/rn-tester/js/examples/Snapshot/SnapshotExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const ScreenshotManager = require('../../../NativeModuleExample/NativeScreenshotManager'); const {RNTesterThemeContext} = require('../../components/RNTesterTheme'); const React = require('react'); @@ -71,4 +73,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js b/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js index df711a3a887a4d..99a6830e7f9561 100644 --- a/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js +++ b/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js @@ -8,6 +8,7 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import type {ListRenderItemInfo} from 'react-native'; import * as React from 'react'; @@ -39,7 +40,7 @@ module.exports = { return ; }, }, - ], + ] as Array, }; function SwipeableCardExample() { diff --git a/packages/rn-tester/js/examples/Switch/SwitchExample.js b/packages/rn-tester/js/examples/Switch/SwitchExample.js index 18f28aa5e7acc0..6e24845e708ad3 100644 --- a/packages/rn-tester/js/examples/Switch/SwitchExample.js +++ b/packages/rn-tester/js/examples/Switch/SwitchExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {Platform, Switch, View} from 'react-native'; @@ -318,11 +320,9 @@ exports.examples = [ return ; }, }, -]; +] as Array; if (Platform.OS === 'ios') { - /* $FlowFixMe[incompatible-call] error found during natural inference roll- - * out. See https://fburl.com/workplace/tc9m3tcf */ exports.examples.push({ title: '[iOS Only] Custom background colors can be set', render(): React.MixedElement { diff --git a/packages/rn-tester/js/examples/TextInput/TextInputKeyProp.js b/packages/rn-tester/js/examples/TextInput/TextInputKeyProp.js index 5d2330c3b5736e..3e25d843dbd67f 100644 --- a/packages/rn-tester/js/examples/TextInput/TextInputKeyProp.js +++ b/packages/rn-tester/js/examples/TextInput/TextInputKeyProp.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import React, {useEffect, useState} from 'react'; import {TextInput, View} from 'react-native'; @@ -48,4 +50,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Timer/TimerExample.js b/packages/rn-tester/js/examples/Timer/TimerExample.js index 995a8fbf5761fc..5a0965105ed097 100644 --- a/packages/rn-tester/js/examples/Timer/TimerExample.js +++ b/packages/rn-tester/js/examples/Timer/TimerExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterButton from '../../components/RNTesterButton'; import RNTesterText from '../../components/RNTesterText'; import React from 'react'; @@ -376,4 +378,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/ToastAndroid/ToastAndroidExample.js b/packages/rn-tester/js/examples/ToastAndroid/ToastAndroidExample.js index 55a2837b9361a2..3d992bcabe59ce 100644 --- a/packages/rn-tester/js/examples/ToastAndroid/ToastAndroidExample.js +++ b/packages/rn-tester/js/examples/ToastAndroid/ToastAndroidExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import {Pressable, StyleSheet, ToastAndroid} from 'react-native'; @@ -166,4 +168,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Transform/TransformExample.js b/packages/rn-tester/js/examples/Transform/TransformExample.js index ab833adc4397cc..963dd89b106005 100644 --- a/packages/rn-tester/js/examples/Transform/TransformExample.js +++ b/packages/rn-tester/js/examples/Transform/TransformExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import * as React from 'react'; import {useEffect, useRef, useState} from 'react'; import {Animated, Easing, StyleSheet, Text, View} from 'react-native'; @@ -412,4 +414,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/TransparentHitTest/TransparentHitTestExample.js b/packages/rn-tester/js/examples/TransparentHitTest/TransparentHitTestExample.js index 1f5cb185954339..7f28d49302d76b 100644 --- a/packages/rn-tester/js/examples/TransparentHitTest/TransparentHitTestExample.js +++ b/packages/rn-tester/js/examples/TransparentHitTest/TransparentHitTestExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const React = require('react'); const {Alert, Text, TouchableOpacity, View} = require('react-native'); @@ -48,4 +50,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/TurboModule/LegacyModuleExample.js b/packages/rn-tester/js/examples/TurboModule/LegacyModuleExample.js index ce2afdb4b05823..1bd83920c29354 100644 --- a/packages/rn-tester/js/examples/TurboModule/LegacyModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/LegacyModuleExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const { default: SampleLegacyModuleExample, } = require('./SampleLegacyModuleExample'); @@ -27,4 +29,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/TurboModule/TurboCxxModuleExample.js b/packages/rn-tester/js/examples/TurboModule/TurboCxxModuleExample.js index b56187cd57c5b3..65771081a1708b 100644 --- a/packages/rn-tester/js/examples/TurboModule/TurboCxxModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/TurboCxxModuleExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const NativeCxxModuleExampleExample = require('./NativeCxxModuleExampleExample'); const React = require('react'); @@ -24,4 +26,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/TurboModule/TurboModuleExample.js b/packages/rn-tester/js/examples/TurboModule/TurboModuleExample.js index af38ece2eef1f9..b3174fa721215d 100644 --- a/packages/rn-tester/js/examples/TurboModule/TurboModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/TurboModuleExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const SampleTurboModuleExample = require('./SampleTurboModuleExample'); const React = require('react'); @@ -24,4 +26,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/Vibration/VibrationExample.js b/packages/rn-tester/js/examples/Vibration/VibrationExample.js index 3dffd38525d1bd..0592b4913b3b63 100644 --- a/packages/rn-tester/js/examples/Vibration/VibrationExample.js +++ b/packages/rn-tester/js/examples/Vibration/VibrationExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import { @@ -116,7 +118,7 @@ exports.examples = [ ); }, }, -]; +] as Array; const styles = StyleSheet.create({ wrapper: { diff --git a/packages/rn-tester/js/examples/WebSocket/WebSocketExample.js b/packages/rn-tester/js/examples/WebSocket/WebSocketExample.js index 49644f806e2387..22aed358946cb9 100644 --- a/packages/rn-tester/js/examples/WebSocket/WebSocketExample.js +++ b/packages/rn-tester/js/examples/WebSocket/WebSocketExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + import RNTesterText from '../../components/RNTesterText'; import React from 'react'; import { @@ -380,4 +382,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; diff --git a/packages/rn-tester/js/examples/XHR/XHRExample.js b/packages/rn-tester/js/examples/XHR/XHRExample.js index 7630306e702d53..99a2929134416b 100644 --- a/packages/rn-tester/js/examples/XHR/XHRExample.js +++ b/packages/rn-tester/js/examples/XHR/XHRExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + const XHRExampleAbortController = require('./XHRExampleAbortController'); const XHRExampleBinaryUpload = require('./XHRExampleBinaryUpload'); const XHRExampleDownload = require('./XHRExampleDownload'); @@ -60,4 +62,4 @@ exports.examples = [ return ; }, }, -]; +] as Array; From 862e8c70493be6ac04b07ef7c78f9cf97d051901 Mon Sep 17 00:00:00 2001 From: Ramanpreet Nara Date: Thu, 17 Jul 2025 17:35:22 -0700 Subject: [PATCH 0174/1383] IntersectionObserver: Clean up legacy observe/unobserve methods Summary: In this diff, we migrated IntersectionObserver to tokens: D74262804. So that we wouldn't have to store shadow nodes on the javascript side. Storing shadow nodes lead to a memory leak in the past. Changelog: [internal] Reviewed By: rubennorte Differential Revision: D78494075 fbshipit-source-id: 38923ca4b265de6ff81ea20e5649e0bd2e39afc9 --- .../NativeIntersectionObserver.cpp | 15 --- .../NativeIntersectionObserver.h | 13 --- .../ReactNativeFeatureFlags.config.js | 10 -- .../featureflags/ReactNativeFeatureFlags.js | 8 +- .../__tests__/IntersectionObserver-itest.js | 64 ++++++------- .../internals/IntersectionObserverManager.js | 93 ++++--------------- .../specs/NativeIntersectionObserver.js | 4 - 7 files changed, 50 insertions(+), 157 deletions(-) diff --git a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.cpp b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.cpp index fe8e26efabbb68..725a46c3bdbd4d 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.cpp @@ -49,21 +49,6 @@ NativeIntersectionObserver::NativeIntersectionObserver( std::shared_ptr jsInvoker) : NativeIntersectionObserverCxxSpec(std::move(jsInvoker)) {} -void NativeIntersectionObserver::observe( - jsi::Runtime& runtime, - NativeIntersectionObserverObserveOptions options) { - observeV2(runtime, std::move(options)); -} - -void NativeIntersectionObserver::unobserve( - jsi::Runtime& runtime, - IntersectionObserverObserverId intersectionObserverId, - std::shared_ptr targetShadowNode) { - auto token = - tokenFromShadowNodeFamily(runtime, targetShadowNode->getFamilyShared()); - unobserveV2(runtime, intersectionObserverId, std::move(token)); -} - jsi::Object NativeIntersectionObserver::observeV2( jsi::Runtime& runtime, NativeIntersectionObserverObserveOptions options) { diff --git a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h index 08cddb59adf4f9..87fae93125b5c6 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h @@ -64,19 +64,6 @@ class NativeIntersectionObserver public: NativeIntersectionObserver(std::shared_ptr jsInvoker); - // TODO(T223605846): Remove legacy observe method - [[deprecated("Please use observeV2")]] - void observe( - jsi::Runtime& runtime, - NativeIntersectionObserverObserveOptions options); - - // TODO(T223605846): Remove legacy unobserve method - [[deprecated("Please use unobserveV2")]] - void unobserve( - jsi::Runtime& runtime, - IntersectionObserverObserverId intersectionObserverId, - std::shared_ptr targetShadowNode); - jsi::Object observeV2( jsi::Runtime& runtime, NativeIntersectionObserverObserveOptions options); diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index 97733068a39a43..96c351da54fbf5 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -817,16 +817,6 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, - utilizeTokensInIntersectionObserver: { - defaultValue: true, - metadata: { - dateAdded: '2025-05-06', - description: 'Use tokens in IntersectionObserver vs ShadowNode.', - expectedReleaseValue: true, - purpose: 'experimentation', - }, - ossReleaseStage: 'none', - }, }, }; diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 4e390c88f5b6c0..110148e3c1a0ad 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<> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -39,7 +39,6 @@ export type ReactNativeFeatureFlagsJsOnly = $ReadOnly<{ shouldUseAnimatedObjectForTransform: Getter, shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter, shouldUseSetNativePropsInFabric: Getter, - utilizeTokensInIntersectionObserver: Getter, }>; export type ReactNativeFeatureFlagsJsOnlyOverrides = OverridesFor; @@ -166,11 +165,6 @@ export const shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter = cre */ export const shouldUseSetNativePropsInFabric: Getter = createJavaScriptFlagGetter('shouldUseSetNativePropsInFabric', true); -/** - * Use tokens in IntersectionObserver vs ShadowNode. - */ -export const utilizeTokensInIntersectionObserver: Getter = createJavaScriptFlagGetter('utilizeTokensInIntersectionObserver', true); - /** * Common flag for testing. Do NOT modify. */ diff --git a/packages/react-native/src/private/webapis/intersectionobserver/__tests__/IntersectionObserver-itest.js b/packages/react-native/src/private/webapis/intersectionobserver/__tests__/IntersectionObserver-itest.js index e70a705ee6550f..0341ff5c5d0a73 100644 --- a/packages/react-native/src/private/webapis/intersectionobserver/__tests__/IntersectionObserver-itest.js +++ b/packages/react-native/src/private/webapis/intersectionobserver/__tests__/IntersectionObserver-itest.js @@ -4,7 +4,6 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @fantom_flags utilizeTokensInIntersectionObserver:* * @flow strict-local * @format */ @@ -20,7 +19,6 @@ import * as Fantom from '@react-native/fantom'; import * as React from 'react'; import {createRef, useState} from 'react'; import {ScrollView, View} from 'react-native'; -import * as ReactNativeFeatureFlags from 'react-native/src/private/featureflags/ReactNativeFeatureFlags'; import setUpIntersectionObserver from 'react-native/src/private/setup/setUpIntersectionObserver'; import ReactNativeElement from 'react-native/src/private/webapis/dom/nodes/ReactNativeElement'; import DOMRectReadOnly from 'react-native/src/private/webapis/geometry/DOMRectReadOnly'; @@ -1494,44 +1492,42 @@ describe('IntersectionObserver', () => { }); }); - if (ReactNativeFeatureFlags.utilizeTokensInIntersectionObserver()) { - it('should not retain initial children of observed targets', () => { - const root = Fantom.createRoot(); - observer = new IntersectionObserver(() => {}); - - const [getReferenceCount, ref] = createShadowNodeReferenceCountingRef(); - - const observeRef: React.RefSetter< - React.ElementRef, - > = instance => { - const element = ensureReactNativeElement(instance); - observer.observe(element); - return () => { - observer.unobserve(element); - }; - }; + it('should not retain initial children of observed targets', () => { + const root = Fantom.createRoot(); + observer = new IntersectionObserver(() => {}); - function Observe({children}: $ReadOnly<{children?: React.Node}>) { - return {children}; - } + const [getReferenceCount, ref] = createShadowNodeReferenceCountingRef(); - Fantom.runTask(() => { - root.render( - - - , - ); - }); + const observeRef: React.RefSetter< + React.ElementRef, + > = instance => { + const element = ensureReactNativeElement(instance); + observer.observe(element); + return () => { + observer.unobserve(element); + }; + }; - expect(getReferenceCount()).toBeGreaterThan(0); + function Observe({children}: $ReadOnly<{children?: React.Node}>) { + return {children}; + } - Fantom.runTask(() => { - root.render(); - }); + Fantom.runTask(() => { + root.render( + + + , + ); + }); - expect(getReferenceCount()).toBe(0); + expect(getReferenceCount()).toBeGreaterThan(0); + + Fantom.runTask(() => { + root.render(); }); - } + + expect(getReferenceCount()).toBe(0); + }); it('should NOT report multiple entries when observing a target that exists and we modify it later in the same tick', () => { const root = Fantom.createRoot({ diff --git a/packages/react-native/src/private/webapis/intersectionobserver/internals/IntersectionObserverManager.js b/packages/react-native/src/private/webapis/intersectionobserver/internals/IntersectionObserverManager.js index 6cbd285d110a67..db9e17db8bf642 100644 --- a/packages/react-native/src/private/webapis/intersectionobserver/internals/IntersectionObserverManager.js +++ b/packages/react-native/src/private/webapis/intersectionobserver/internals/IntersectionObserverManager.js @@ -27,13 +27,13 @@ import type {NativeIntersectionObserverToken} from '../specs/NativeIntersectionO import * as Systrace from '../../../../../Libraries/Performance/Systrace'; import warnOnce from '../../../../../Libraries/Utilities/warnOnce'; -import * as ReactNativeFeatureFlags from '../../../featureflags/ReactNativeFeatureFlags'; import { getInstanceHandle, getNativeNodeReference, } from '../../dom/nodes/internals/NodeInternals'; import {createIntersectionObserverEntry} from '../IntersectionObserverEntry'; import NativeIntersectionObserver from '../specs/NativeIntersectionObserver'; +import nullthrows from 'nullthrows'; export type IntersectionObserverId = number; @@ -69,36 +69,11 @@ function setTargetForInstanceHandle( instanceHandleToTargetMap.set(key, target); } -// The mapping between ReactNativeElement and their corresponding shadow node -// also needs to be kept here because React removes the link when unmounting. -const targetToShadowNodeMap: WeakMap< - ReactNativeElement, - ReturnType, -> = new WeakMap(); - const targetToTokenMap: WeakMap< ReactNativeElement, NativeIntersectionObserverToken, > = new WeakMap(); -let modernNativeIntersectionObserver = - NativeIntersectionObserver == null - ? null - : NativeIntersectionObserver.observeV2 == null || - NativeIntersectionObserver.unobserveV2 == null - ? null - : { - observe: NativeIntersectionObserver.observeV2, - unobserve: NativeIntersectionObserver.unobserveV2, - }; - -if ( - modernNativeIntersectionObserver && - !ReactNativeFeatureFlags.utilizeTokensInIntersectionObserver() -) { - modernNativeIntersectionObserver = null; -} - /** * Registers the given intersection observer and returns a unique ID for it, * which is required to start observing targets. @@ -189,34 +164,19 @@ export function observe({ // access it even after the instance handle has been unmounted. setTargetForInstanceHandle(instanceHandle, target); - if (modernNativeIntersectionObserver == null) { - // Same for the mapping between the target and its shadow node. - targetToShadowNodeMap.set(target, targetNativeNodeReference); - } - if (!isConnected) { NativeIntersectionObserver.connect(notifyIntersectionObservers); isConnected = true; } - if (modernNativeIntersectionObserver == null) { - NativeIntersectionObserver.observe({ - intersectionObserverId, - rootShadowNode: rootNativeNodeReference, - targetShadowNode: targetNativeNodeReference, - thresholds: registeredObserver.observer.thresholds, - rootThresholds: registeredObserver.observer.rnRootThresholds, - }); - } else { - const token = modernNativeIntersectionObserver.observe({ - intersectionObserverId, - rootShadowNode: rootNativeNodeReference, - targetShadowNode: targetNativeNodeReference, - thresholds: registeredObserver.observer.thresholds, - rootThresholds: registeredObserver.observer.rnRootThresholds, - }); - targetToTokenMap.set(target, token); - } + const token = nullthrows(NativeIntersectionObserver.observeV2)({ + intersectionObserverId, + rootShadowNode: rootNativeNodeReference, + targetShadowNode: targetNativeNodeReference, + thresholds: registeredObserver.observer.thresholds, + rootThresholds: registeredObserver.observer.rnRootThresholds, + }); + targetToTokenMap.set(target, token); return true; } @@ -240,33 +200,18 @@ export function unobserve( return; } - if (modernNativeIntersectionObserver == null) { - const targetNativeNodeReference = targetToShadowNodeMap.get(target); - if (targetNativeNodeReference == null) { - console.error( - 'IntersectionObserverManager: could not find registration data for target', - ); - return; - } - - NativeIntersectionObserver.unobserve( - intersectionObserverId, - targetNativeNodeReference, - ); - } else { - const targetToken = targetToTokenMap.get(target); - if (targetToken == null) { - console.error( - 'IntersectionObserverManager: could not find registration data for target', - ); - return; - } - - modernNativeIntersectionObserver.unobserve( - intersectionObserverId, - targetToken, + const targetToken = targetToTokenMap.get(target); + if (targetToken == null) { + console.error( + 'IntersectionObserverManager: could not find registration data for target', ); + return; } + + nullthrows(NativeIntersectionObserver.unobserveV2)( + intersectionObserverId, + targetToken, + ); } /** diff --git a/packages/react-native/src/private/webapis/intersectionobserver/specs/NativeIntersectionObserver.js b/packages/react-native/src/private/webapis/intersectionobserver/specs/NativeIntersectionObserver.js index af1cac035ab061..f5e36098787bf2 100644 --- a/packages/react-native/src/private/webapis/intersectionobserver/specs/NativeIntersectionObserver.js +++ b/packages/react-native/src/private/webapis/intersectionobserver/specs/NativeIntersectionObserver.js @@ -34,10 +34,6 @@ export type NativeIntersectionObserverObserveOptions = { export opaque type NativeIntersectionObserverToken = mixed; export interface Spec extends TurboModule { - // TODO(T223605846): Remove legacy observe method - +observe: (options: NativeIntersectionObserverObserveOptions) => void; - // TODO(T223605846): Remove legacy unobserve method - +unobserve: (intersectionObserverId: number, targetShadowNode: mixed) => void; +observeV2?: ( options: NativeIntersectionObserverObserveOptions, ) => NativeIntersectionObserverToken; From 3f9b19eb892af2d842c058198a5fea7531faa1af Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Thu, 17 Jul 2025 20:42:02 -0700 Subject: [PATCH 0175/1383] Fix build_android GHA Job (#52694) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52694 build_android job is always failing, with this assertion. Seems like find/replace in D78484060 gone wrong? Changelog: [Internal] Reviewed By: sbuggay Differential Revision: D78534334 fbshipit-source-id: 291bdd01b41fa6efea00ed63a0dee8bdb14cbc3a --- .../shared/src/test/kotlin/com/facebook/react/utils/OsTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gradle-plugin/shared/src/test/kotlin/com/facebook/react/utils/OsTest.kt b/packages/gradle-plugin/shared/src/test/kotlin/com/facebook/react/utils/OsTest.kt index 85b8dc28dafc0c..bf535ade745533 100644 --- a/packages/gradle-plugin/shared/src/test/kotlin/com/facebook/react/utils/OsTest.kt +++ b/packages/gradle-plugin/shared/src/test/kotlin/com/facebook/react/utils/OsTest.kt @@ -55,7 +55,7 @@ class OsTest { @Test fun unixifyPath_withAWindowsPath_convertsItCorrectly() { - val aWindowsPath = "C:\\just\\a\\windows\\path\\" + val aWindowsPath = "D:\\just\\a\\windows\\path\\" assertThat("/D/just/a/windows/path/").isEqualTo(aWindowsPath.unixifyPath()) } From e247be793c70a374955d798d8cbbc6eba58080ec Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Fri, 18 Jul 2025 03:32:13 -0700 Subject: [PATCH 0176/1383] Lower minimum Node.js version to 20.19.4 (#52678) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52678 From partner feedback, there's still appetite to support Node 20.x for the next <1y of life. Lower min version to `20.19.4` (Jul 2025) and widen test matrix in CI. Changelog: [General][Breaking] - Our new minimum Node version is Node.js 20 (Overrides #51840) Reviewed By: cortinico Differential Revision: D78494491 fbshipit-source-id: c8d9dc6250cb11f8a12ca7e761b65f4a8dae9265 --- .github/workflows/test-all.yml | 2 +- packages/assets/package.json | 2 +- packages/babel-plugin-codegen/package.json | 2 +- packages/community-cli-plugin/package.json | 2 +- packages/core-cli-utils/package.json | 2 +- packages/debugger-frontend/package.json | 2 +- packages/debugger-shell/package.json | 2 +- packages/dev-middleware/package.json | 2 +- packages/eslint-config-react-native/package.json | 2 +- packages/eslint-plugin-react-native/package.json | 2 +- packages/eslint-plugin-specs/package.json | 2 +- packages/gradle-plugin/package.json | 2 +- packages/metro-config/package.json | 2 +- packages/new-app-screen/package.json | 2 +- packages/polyfills/package.json | 2 +- packages/react-native-babel-preset/package.json | 2 +- packages/react-native-babel-transformer/package.json | 2 +- packages/react-native-codegen/package.json | 2 +- packages/react-native-compatibility-check/package.json | 2 +- packages/react-native/package.json | 2 +- packages/rn-tester/package.json | 2 +- packages/virtualized-lists/package.json | 2 +- private/helloworld/package.json | 2 +- private/react-native-bots/package.json | 2 +- private/react-native-codegen-typescript-test/package.json | 2 +- 25 files changed, 25 insertions(+), 25 deletions(-) diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml index 06200dbdec2a1b..2a57995aea90b5 100644 --- a/.github/workflows/test-all.yml +++ b/.github/workflows/test-all.yml @@ -583,7 +583,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: ["24", "22"] + node-version: ["24", "22", "20"] steps: - name: Checkout uses: actions/checkout@v4 diff --git a/packages/assets/package.json b/packages/assets/package.json index 1b15cd15041f6b..b36696ca1298b6 100644 --- a/packages/assets/package.json +++ b/packages/assets/package.json @@ -17,7 +17,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "files": [ "path-support.js", diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json index 0be39ceb9224e1..366fabe53ba341 100644 --- a/packages/babel-plugin-codegen/package.json +++ b/packages/babel-plugin-codegen/package.json @@ -19,7 +19,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "files": [ "index.js" diff --git a/packages/community-cli-plugin/package.json b/packages/community-cli-plugin/package.json index 68e4d2af636b2f..1bbb6171da1c6f 100644 --- a/packages/community-cli-plugin/package.json +++ b/packages/community-cli-plugin/package.json @@ -43,6 +43,6 @@ } }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/packages/core-cli-utils/package.json b/packages/core-cli-utils/package.json index 24f6810e3aa72c..78e68ece88b820 100644 --- a/packages/core-cli-utils/package.json +++ b/packages/core-cli-utils/package.json @@ -21,7 +21,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "files": [ "dist" diff --git a/packages/debugger-frontend/package.json b/packages/debugger-frontend/package.json index 8ca79a5c39d00f..70ba87b219703c 100644 --- a/packages/debugger-frontend/package.json +++ b/packages/debugger-frontend/package.json @@ -20,6 +20,6 @@ "BUILD_INFO" ], "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/packages/debugger-shell/package.json b/packages/debugger-shell/package.json index cbafe6bf36b162..44e6389f0ec52c 100644 --- a/packages/debugger-shell/package.json +++ b/packages/debugger-shell/package.json @@ -26,7 +26,7 @@ }, "license": "MIT", "engines": { - "node": ">= 22.14.0", + "node": ">= 20.19.4", "electron": ">=36.3.0" }, "dependencies": { diff --git a/packages/dev-middleware/package.json b/packages/dev-middleware/package.json index ece94b94e65866..ad0b5f327bfd7d 100644 --- a/packages/dev-middleware/package.json +++ b/packages/dev-middleware/package.json @@ -35,7 +35,7 @@ "ws": "^6.2.3" }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "devDependencies": { "selfsigned": "^2.4.1", diff --git a/packages/eslint-config-react-native/package.json b/packages/eslint-config-react-native/package.json index 0d43e6e7675edb..a7e7481edc5e48 100644 --- a/packages/eslint-config-react-native/package.json +++ b/packages/eslint-config-react-native/package.json @@ -16,7 +16,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "main": "index.js", "dependencies": { diff --git a/packages/eslint-plugin-react-native/package.json b/packages/eslint-plugin-react-native/package.json index 48263c87d2c006..d7db05218a633b 100644 --- a/packages/eslint-plugin-react-native/package.json +++ b/packages/eslint-plugin-react-native/package.json @@ -22,6 +22,6 @@ "hermes-eslint": "0.29.1" }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json index 299f145e4e6b74..1c8fe173a38fa4 100644 --- a/packages/eslint-plugin-specs/package.json +++ b/packages/eslint-plugin-specs/package.json @@ -36,6 +36,6 @@ "hermes-eslint": "0.29.1" }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/packages/gradle-plugin/package.json b/packages/gradle-plugin/package.json index 5897ef53b24449..9675ec0401c9c9 100644 --- a/packages/gradle-plugin/package.json +++ b/packages/gradle-plugin/package.json @@ -16,7 +16,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "scripts": { "build": "./gradlew build", diff --git a/packages/metro-config/package.json b/packages/metro-config/package.json index 29500f139e13aa..a649cbe470754f 100644 --- a/packages/metro-config/package.json +++ b/packages/metro-config/package.json @@ -16,7 +16,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "exports": { ".": "./src/index.js", diff --git a/packages/new-app-screen/package.json b/packages/new-app-screen/package.json index ccfe78e7afa480..915753cfa157c9 100644 --- a/packages/new-app-screen/package.json +++ b/packages/new-app-screen/package.json @@ -30,6 +30,6 @@ } }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/packages/polyfills/package.json b/packages/polyfills/package.json index baf6f178868d2d..647594e12ec283 100644 --- a/packages/polyfills/package.json +++ b/packages/polyfills/package.json @@ -18,7 +18,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "files": [ "console.js", diff --git a/packages/react-native-babel-preset/package.json b/packages/react-native-babel-preset/package.json index 17aaae7809ac0d..1fc6149ea3475c 100644 --- a/packages/react-native-babel-preset/package.json +++ b/packages/react-native-babel-preset/package.json @@ -13,7 +13,7 @@ ], "license": "MIT", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "main": "src/index.js", "files": [ diff --git a/packages/react-native-babel-transformer/package.json b/packages/react-native-babel-transformer/package.json index bf4a934ebcc43b..e41576ee44e8d8 100644 --- a/packages/react-native-babel-transformer/package.json +++ b/packages/react-native-babel-transformer/package.json @@ -14,7 +14,7 @@ ], "license": "MIT", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "main": "src/index.js", "files": [ diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 16068f79d45b8c..7c727645e3a705 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -18,7 +18,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "scripts": { "build": "yarn clean && node scripts/build.js --verbose", diff --git a/packages/react-native-compatibility-check/package.json b/packages/react-native-compatibility-check/package.json index abe99392696dff..258ac6d0729f1e 100644 --- a/packages/react-native-compatibility-check/package.json +++ b/packages/react-native-compatibility-check/package.json @@ -19,7 +19,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "exports": { ".": "./src/index.js", diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 05c7a71fea47b0..a3e2f40b0f907c 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -21,7 +21,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "bin": { "react-native": "cli.js" diff --git a/packages/rn-tester/package.json b/packages/rn-tester/package.json index 9c6463d3367316..cfde9ad7b0c4fa 100644 --- a/packages/rn-tester/package.json +++ b/packages/rn-tester/package.json @@ -10,7 +10,7 @@ "directory": "packages/rn-tester" }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "scripts": { "start": "react-native start", diff --git a/packages/virtualized-lists/package.json b/packages/virtualized-lists/package.json index dd596f66ec2595..f208d9d8cb05a7 100644 --- a/packages/virtualized-lists/package.json +++ b/packages/virtualized-lists/package.json @@ -17,7 +17,7 @@ ], "bugs": "https://github.com/facebook/react-native/issues", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "exports": { ".": { diff --git a/private/helloworld/package.json b/private/helloworld/package.json index daa3725bc1683d..3a59bcbb34ce90 100644 --- a/private/helloworld/package.json +++ b/private/helloworld/package.json @@ -33,6 +33,6 @@ "rxjs": "^7.8.1" }, "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" } } diff --git a/private/react-native-bots/package.json b/private/react-native-bots/package.json index a67e918abb7f4a..471c2ef3c24a80 100644 --- a/private/react-native-bots/package.json +++ b/private/react-native-bots/package.json @@ -4,7 +4,7 @@ "private": true, "license": "MIT", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "devDependencies": { "@rnx-kit/rn-changelog-generator": "^0.4.0", diff --git a/private/react-native-codegen-typescript-test/package.json b/private/react-native-codegen-typescript-test/package.json index b5edd1b1739424..9e68a255d084a0 100644 --- a/private/react-native-codegen-typescript-test/package.json +++ b/private/react-native-codegen-typescript-test/package.json @@ -5,7 +5,7 @@ "description": "TypeScript related unit test for @react-native/codegen", "license": "MIT", "engines": { - "node": ">= 22.14.0" + "node": ">= 20.19.4" }, "scripts": { "build": "yarn clean && node scripts/build.js --verbose && tsc", From c9367a8d869ed252ed496338c2d0d5e8c0307917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Fri, 18 Jul 2025 03:44:21 -0700 Subject: [PATCH 0177/1383] Remove optionality for stable methods of the NativePerformance module (#52668) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52668 Changelog: [internal] These methods have been available for months so no need to consider backwards compatibility with older binaries. Reviewed By: huntie Differential Revision: D78412932 fbshipit-source-id: 0f1d541c36c98a4cc8c847d1ee7a08a9d0f4b849 --- .../webapis/performance/EventTiming.js | 4 +- .../webapis/performance/Performance.js | 90 ++++++++++--------- .../performance/specs/NativePerformance.js | 26 +++--- 3 files changed, 62 insertions(+), 58 deletions(-) diff --git a/packages/react-native/src/private/webapis/performance/EventTiming.js b/packages/react-native/src/private/webapis/performance/EventTiming.js index 5e2b446dcfdaac..76d62a18b9dfdb 100644 --- a/packages/react-native/src/private/webapis/performance/EventTiming.js +++ b/packages/react-native/src/private/webapis/performance/EventTiming.js @@ -86,14 +86,14 @@ function getCachedEventCounts(): Map { return cachedEventCounts; } - if (!NativePerformance || !NativePerformance?.getEventCounts) { + if (!NativePerformance) { warnNoNativePerformance(); cachedEventCounts = new Map(); return cachedEventCounts; } const eventCounts = new Map( - NativePerformance.getEventCounts?.() ?? [], + NativePerformance.getEventCounts() ?? [], ); cachedEventCounts = eventCounts; diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index 789e901a14ec6b..d6725d5bfdf58d 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -98,53 +98,56 @@ export default class Performance { // Get the current JS memory information. get memory(): MemoryInfo { - if (NativePerformance?.getSimpleMemoryInfo) { - // JSI API implementations may have different variants of names for the JS - // heap information we need here. We will parse the result based on our - // guess of the implementation for now. - const memoryInfo = NativePerformance.getSimpleMemoryInfo(); - if (memoryInfo.hasOwnProperty('hermes_heapSize')) { - // We got memory information from Hermes - const { - hermes_heapSize: totalJSHeapSize, - hermes_allocatedBytes: usedJSHeapSize, - } = memoryInfo; - - return new MemoryInfo({ - jsHeapSizeLimit: null, // We don't know the heap size limit from Hermes. - totalJSHeapSize, - usedJSHeapSize, - }); - } else { - // JSC and V8 has no native implementations for memory information in JSI::Instrumentation - return new MemoryInfo(); - } + if (!NativePerformance) { + warnNoNativePerformance(); + return new MemoryInfo(); } - return new MemoryInfo(); + // JSI API implementations may have different variants of names for the JS + // heap information we need here. We will parse the result based on our + // guess of the implementation for now. + const memoryInfo = NativePerformance.getSimpleMemoryInfo(); + if (memoryInfo.hasOwnProperty('hermes_heapSize')) { + // We got memory information from Hermes + const { + hermes_heapSize: totalJSHeapSize, + hermes_allocatedBytes: usedJSHeapSize, + } = memoryInfo; + + return new MemoryInfo({ + jsHeapSizeLimit: null, // We don't know the heap size limit from Hermes. + totalJSHeapSize, + usedJSHeapSize, + }); + } else { + // JSC and V8 has no native implementations for memory information in JSI::Instrumentation + return new MemoryInfo(); + } } // Startup metrics is not used in web, but only in React Native. get rnStartupTiming(): ReactNativeStartupTiming { - if (NativePerformance?.getReactNativeStartupTiming) { - const { - startTime, - endTime, - initializeRuntimeStart, - initializeRuntimeEnd, - executeJavaScriptBundleEntryPointStart, - executeJavaScriptBundleEntryPointEnd, - } = NativePerformance.getReactNativeStartupTiming(); - return new ReactNativeStartupTiming({ - startTime, - endTime, - initializeRuntimeStart, - initializeRuntimeEnd, - executeJavaScriptBundleEntryPointStart, - executeJavaScriptBundleEntryPointEnd, - }); + if (!NativePerformance) { + warnNoNativePerformance(); + return new ReactNativeStartupTiming(); } - return new ReactNativeStartupTiming(); + + const { + startTime, + endTime, + initializeRuntimeStart, + initializeRuntimeEnd, + executeJavaScriptBundleEntryPointStart, + executeJavaScriptBundleEntryPointEnd, + } = NativePerformance.getReactNativeStartupTiming(); + return new ReactNativeStartupTiming({ + startTime, + endTime, + initializeRuntimeStart, + initializeRuntimeEnd, + executeJavaScriptBundleEntryPointStart, + executeJavaScriptBundleEntryPointEnd, + }); } mark( @@ -434,10 +437,11 @@ export default class Performance { * https://www.w3.org/TR/performance-timeline/#extensions-to-the-performance-interface */ getEntries(): PerformanceEntryList { - if (!NativePerformance?.getEntries) { + if (!NativePerformance) { warnNoNativePerformance(); return []; } + return NativePerformance.getEntries().map(rawToPerformanceEntry); } @@ -450,7 +454,7 @@ export default class Performance { return []; } - if (!NativePerformance?.getEntriesByType) { + if (!NativePerformance) { warnNoNativePerformance(); return []; } @@ -472,7 +476,7 @@ export default class Performance { return []; } - if (!NativePerformance?.getEntriesByName) { + if (!NativePerformance) { warnNoNativePerformance(); return []; } diff --git a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js index eeb08d788e0d49..640138cee0abb3 100644 --- a/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js +++ b/packages/react-native/src/private/webapis/performance/specs/NativePerformance.js @@ -53,7 +53,7 @@ export type PerformanceObserverInit = { }; export interface Spec extends TurboModule { - +now?: () => number; + +now: () => number; +reportMark?: (name: string, startTime: number, entry: mixed) => void; +reportMeasure?: ( name: string, @@ -62,36 +62,36 @@ export interface Spec extends TurboModule { entry: mixed, ) => void; +getMarkTime?: (name: string) => ?number; - +clearMarks?: (entryName?: string) => void; - +clearMeasures?: (entryName?: string) => void; - +getEntries?: () => $ReadOnlyArray; - +getEntriesByName?: ( + +clearMarks: (entryName?: string) => void; + +clearMeasures: (entryName?: string) => void; + +getEntries: () => $ReadOnlyArray; + +getEntriesByName: ( entryName: string, entryType?: ?RawPerformanceEntryType, ) => $ReadOnlyArray; - +getEntriesByType?: ( + +getEntriesByType: ( entryType: RawPerformanceEntryType, ) => $ReadOnlyArray; - +getEventCounts?: () => $ReadOnlyArray<[string, number]>; + +getEventCounts: () => $ReadOnlyArray<[string, number]>; +getSimpleMemoryInfo: () => NativeMemoryInfo; +getReactNativeStartupTiming: () => ReactNativeStartupTiming; - +createObserver?: ( + +createObserver: ( callback: NativeBatchedObserverCallback, ) => OpaqueNativeObserverHandle; - +getDroppedEntriesCount?: (observer: OpaqueNativeObserverHandle) => number; + +getDroppedEntriesCount: (observer: OpaqueNativeObserverHandle) => number; - +observe?: ( + +observe: ( observer: OpaqueNativeObserverHandle, options: PerformanceObserverInit, ) => void; - +disconnect?: (observer: OpaqueNativeObserverHandle) => void; - +takeRecords?: ( + +disconnect: (observer: OpaqueNativeObserverHandle) => void; + +takeRecords: ( observer: OpaqueNativeObserverHandle, sort: boolean, ) => $ReadOnlyArray; - +getSupportedPerformanceEntryTypes?: () => $ReadOnlyArray; + +getSupportedPerformanceEntryTypes: () => $ReadOnlyArray; +setCurrentTimeStampForTesting?: (timeStamp: number) => void; +clearEventCountsForTesting?: () => void; From adef486333e8e674dffb72bf29e5db9c3126f6e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Fri, 18 Jul 2025 03:44:21 -0700 Subject: [PATCH 0178/1383] Assume NativePerformance will be available if the Performance module is loaded (#52671) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52671 Changelog: [internal] When setting up the global `performance` value, we check if the native module exists to decide what version to setup: the legacy "barebones" version or the modern version that's mostly spec compliant. As we do that check and we shouldn't be requiring the module from anywhere else, it should be safe to always assume the module will be defined if we load the `Performance` class, so we can avoid checks in all methods. NOTE: I've kept some checks for a few methods that are still not fully propagated (new methods like `reportMark`, `reportMeasure` and `getMarkTime`). This improves performance slightly for `performance` methods: * Before | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '1803.32 ± 0.71%' | '1763.00' | '563849 ± 0.01%' | '567215' | 554908 | | 1 | 'mark (with custom startTime)' | '1762.39 ± 1.67%' | '1692.00' | '587832 ± 0.01%' | '591017' | 567414 | | 2 | 'measure (default)' | '1879.47 ± 1.44%' | '1813.00' | '548962 ± 0.01%' | '551572' | 532064 | | 3 | 'measure (with start and end timestamps)' | '1916.65 ± 0.84%' | '1873.00' | '531258 ± 0.01%' | '533903' | 521743 | | 4 | 'measure (with mark names)' | '2049.84 ± 0.44%' | '2013.00' | '492799 ± 0.01%' | '496771' | 487844 | | 5 | 'clearMarks' | '719.87 ± 0.04%' | '711.00' | '1403602 ± 0.01%' | '1406470' | 1389136 | | 6 | 'clearMeasures' | '710.04 ± 0.04%' | '701.00' | '1421610 ± 0.01%' | '1426534' | 1408373 | | 7 | 'mark + clearMarks' | '2256.56 ± 1.10%' | '2143.00' | '460721 ± 0.02%' | '466636' | 443152 | | 8 | 'measure + clearMeasures (with start and end timestamps)' | '2345.44 ± 1.11%' | '2244.00' | '442395 ± 0.02%' | '445633' | 426360 | | 9 | 'measure + clearMeasures (with mark names)' | '2349.55 ± 0.61%' | '2283.00' | '434370 ± 0.02%' | '438020' | 425613 | * After | (index) | Task name | Latency average (ns) | Latency median (ns) | Throughput average (ops/s) | Throughput median (ops/s) | Samples | | ------- | --------------------------------------------------------- | -------------------- | ------------------- | -------------------------- | ------------------------- | ------- | | 0 | 'mark (default)' | '1791.47 ± 1.08%' | '1732.00' | '573787 ± 0.01%' | '577367' | 558202 | | 1 | 'mark (with custom startTime)' | '1699.41 ± 1.27%' | '1642.00' | '605188 ± 0.01%' | '609013' | 588441 | | 2 | 'measure (default)' | '1820.92 ± 1.39%' | '1763.00' | '563437 ± 0.01%' | '567215' | 549173 | | 3 | 'measure (with start and end timestamps)' | '1923.57 ± 1.65%' | '1852.00' | '537112 ± 0.01%' | '539957' | 519867 | | 4 | 'measure (with mark names)' | '2036.09 ± 1.05%' | '1983.00' | '500406 ± 0.01%' | '504286' | 491139 | | 5 | 'clearMarks' | '657.49 ± 0.07%' | '641.00' | '1543793 ± 0.01%' | '1560062' | 1520939 | | 6 | 'clearMeasures' | '669.02 ± 0.09%' | '651.00' | '1520386 ± 0.01%' | '1536098' | 1494730 | | 7 | 'mark + clearMarks' | '2213.09 ± 1.53%' | '2103.00' | '470008 ± 0.02%' | '475511' | 451858 | | 8 | 'measure + clearMeasures (with start and end timestamps)' | '2353.15 ± 1.27%' | '2214.00' | '448563 ± 0.02%' | '451671' | 424962 | | 9 | 'measure + clearMeasures (with mark names)' | '2298.28 ± 0.62%' | '2243.00' | '441703 ± 0.02%' | '445831' | 435108 | Reviewed By: hoxyq Differential Revision: D78412931 fbshipit-source-id: 07390722bb00a51847cb5625b2adb4e26f89e5d2 --- .../Libraries/Core/setUpPerformance.js | 3 +- .../webapis/performance/EventTiming.js | 12 ++--- .../webapis/performance/Performance.js | 50 ++++--------------- .../performance/PerformanceObserver.js | 37 +++----------- .../__tests__/EventTimingAPI-itest.js | 6 ++- .../performance/__tests__/UserTiming-itest.js | 23 +++++---- 6 files changed, 40 insertions(+), 91 deletions(-) diff --git a/packages/react-native/Libraries/Core/setUpPerformance.js b/packages/react-native/Libraries/Core/setUpPerformance.js index 2087c74cc1e5c1..edb00ce81e211b 100644 --- a/packages/react-native/Libraries/Core/setUpPerformance.js +++ b/packages/react-native/Libraries/Core/setUpPerformance.js @@ -8,12 +8,13 @@ * @format */ -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()' if (NativePerformance) { + const Performance = + require('../../src/private/webapis/performance/Performance').default; // $FlowExpectedError[cannot-write] global.performance = new Performance(); } else { diff --git a/packages/react-native/src/private/webapis/performance/EventTiming.js b/packages/react-native/src/private/webapis/performance/EventTiming.js index 76d62a18b9dfdb..8f96f8d6ba8b65 100644 --- a/packages/react-native/src/private/webapis/performance/EventTiming.js +++ b/packages/react-native/src/private/webapis/performance/EventTiming.js @@ -15,9 +15,11 @@ import type { PerformanceEntryJSON, } from './PerformanceEntry'; -import {warnNoNativePerformance} from './internals/Utilities'; import {PerformanceEntry} from './PerformanceEntry'; -import NativePerformance from './specs/NativePerformance'; +import MaybeNativePerformance from './specs/NativePerformance'; +import nullthrows from 'nullthrows'; + +const NativePerformance = nullthrows(MaybeNativePerformance); export type PerformanceEventTimingJSON = { ...PerformanceEntryJSON, @@ -86,12 +88,6 @@ function getCachedEventCounts(): Map { return cachedEventCounts; } - if (!NativePerformance) { - warnNoNativePerformance(); - cachedEventCounts = new Map(); - return cachedEventCounts; - } - const eventCounts = new Map( NativePerformance.getEventCounts() ?? [], ); diff --git a/packages/react-native/src/private/webapis/performance/Performance.js b/packages/react-native/src/private/webapis/performance/Performance.js index d6725d5bfdf58d..c652481cd376cb 100644 --- a/packages/react-native/src/private/webapis/performance/Performance.js +++ b/packages/react-native/src/private/webapis/performance/Performance.js @@ -35,8 +35,9 @@ import { } from './internals/Utilities'; import MemoryInfo from './MemoryInfo'; import ReactNativeStartupTiming from './ReactNativeStartupTiming'; -import NativePerformance from './specs/NativePerformance'; +import MaybeNativePerformance from './specs/NativePerformance'; import {PerformanceMark, PerformanceMeasure} from './UserTiming'; +import nullthrows from 'nullthrows'; export type PerformanceMeasureOptions = | $ReadOnly<{ @@ -58,11 +59,13 @@ export type PerformanceMeasureOptions = const ENTRY_TYPES_AVAILABLE_FROM_TIMELINE: $ReadOnlyArray = ['mark', 'measure']; -const cachedReportMark = NativePerformance?.reportMark; -const cachedReportMeasure = NativePerformance?.reportMeasure; -const cachedGetMarkTime = NativePerformance?.getMarkTime; -const cachedNativeClearMarks = NativePerformance?.clearMarks; -const cachedNativeClearMeasures = NativePerformance?.clearMeasures; +const NativePerformance = nullthrows(MaybeNativePerformance); + +const cachedReportMark = NativePerformance.reportMark; +const cachedReportMeasure = NativePerformance.reportMeasure; +const cachedGetMarkTime = NativePerformance.getMarkTime; +const cachedNativeClearMarks = NativePerformance.clearMarks; +const cachedNativeClearMeasures = NativePerformance.clearMeasures; const MARK_OPTIONS_REUSABLE_OBJECT: {...PerformanceMarkOptions} = { startTime: 0, @@ -98,11 +101,6 @@ export default class Performance { // Get the current JS memory information. get memory(): MemoryInfo { - if (!NativePerformance) { - warnNoNativePerformance(); - return new MemoryInfo(); - } - // JSI API implementations may have different variants of names for the JS // heap information we need here. We will parse the result based on our // guess of the implementation for now. @@ -127,11 +125,6 @@ export default class Performance { // Startup metrics is not used in web, but only in React Native. get rnStartupTiming(): ReactNativeStartupTiming { - if (!NativePerformance) { - warnNoNativePerformance(); - return new ReactNativeStartupTiming(); - } - const { startTime, endTime, @@ -220,11 +213,6 @@ export default class Performance { } clearMarks(markName?: string): void { - if (!cachedNativeClearMarks) { - warnNoNativePerformance(); - return; - } - cachedNativeClearMarks(markName); } @@ -417,11 +405,6 @@ export default class Performance { } clearMeasures(measureName?: string): void { - if (!cachedNativeClearMeasures) { - warnNoNativePerformance(); - return; - } - cachedNativeClearMeasures(measureName); } @@ -437,11 +420,6 @@ export default class Performance { * https://www.w3.org/TR/performance-timeline/#extensions-to-the-performance-interface */ getEntries(): PerformanceEntryList { - if (!NativePerformance) { - warnNoNativePerformance(); - return []; - } - return NativePerformance.getEntries().map(rawToPerformanceEntry); } @@ -454,11 +432,6 @@ export default class Performance { return []; } - if (!NativePerformance) { - warnNoNativePerformance(); - return []; - } - return NativePerformance.getEntriesByType( performanceEntryTypeToRaw(entryType), ).map(rawToPerformanceEntry); @@ -476,11 +449,6 @@ export default class Performance { return []; } - if (!NativePerformance) { - warnNoNativePerformance(); - return []; - } - return NativePerformance.getEntriesByName( entryName, entryType != null ? performanceEntryTypeToRaw(entryType) : undefined, diff --git a/packages/react-native/src/private/webapis/performance/PerformanceObserver.js b/packages/react-native/src/private/webapis/performance/PerformanceObserver.js index 6870d4a9f2a4f5..c576a4451f6658 100644 --- a/packages/react-native/src/private/webapis/performance/PerformanceObserver.js +++ b/packages/react-native/src/private/webapis/performance/PerformanceObserver.js @@ -21,12 +21,13 @@ import { rawToPerformanceEntry, rawToPerformanceEntryType, } from './internals/RawPerformanceEntry'; -import {warnNoNativePerformance} from './internals/Utilities'; -import NativePerformance from './specs/NativePerformance'; +import MaybeNativePerformance from './specs/NativePerformance'; import nullthrows from 'nullthrows'; export {PerformanceEntry} from './PerformanceEntry'; +const NativePerformance = nullthrows(MaybeNativePerformance); + export class PerformanceObserverEntryList { #entries: PerformanceEntryList; @@ -75,13 +76,6 @@ export interface PerformanceObserverInit { } function getSupportedPerformanceEntryTypes(): $ReadOnlyArray { - if (!NativePerformance) { - return Object.freeze([]); - } - if (!NativePerformance.getSupportedPerformanceEntryTypes) { - // fallback if getSupportedPerformanceEntryTypes is not defined on native side - return Object.freeze(['mark', 'measure', 'event']); - } return Object.freeze( NativePerformance.getSupportedPerformanceEntryTypes().map( rawToPerformanceEntryType, @@ -120,11 +114,6 @@ export class PerformanceObserver { } observe(options: PerformanceObserverInit): void { - if (!NativePerformance || NativePerformance.observe == null) { - warnNoNativePerformance(); - return; - } - this.#validateObserveOptions(options); if (this.#nativeObserverHandle == null) { @@ -135,12 +124,12 @@ export class PerformanceObserver { if (options.entryTypes) { this.#type = 'multiple'; - NativePerformance.observe?.(observerHandle, { + NativePerformance.observe(observerHandle, { entryTypes: options.entryTypes.map(performanceEntryTypeToRaw), }); } else if (options.type) { this.#type = 'single'; - NativePerformance.observe?.(observerHandle, { + NativePerformance.observe(observerHandle, { type: performanceEntryTypeToRaw(options.type), buffered: options.buffered, durationThreshold: options.durationThreshold, @@ -149,12 +138,7 @@ export class PerformanceObserver { } disconnect(): void { - if (!NativePerformance) { - warnNoNativePerformance(); - return; - } - - if (this.#nativeObserverHandle == null || !NativePerformance.disconnect) { + if (this.#nativeObserverHandle == null) { return; } @@ -162,16 +146,11 @@ export class PerformanceObserver { } #createNativeObserver(): OpaqueNativeObserverHandle | null { - if (!NativePerformance || !NativePerformance.createObserver) { - warnNoNativePerformance(); - return null; - } - this.#calledAtLeastOnce = false; const observerHandle: OpaqueNativeObserverHandle = NativePerformance.createObserver(() => { - const rawEntries = NativePerformance.takeRecords?.( + const rawEntries = NativePerformance.takeRecords( observerHandle, true, // sort records ); @@ -185,7 +164,7 @@ export class PerformanceObserver { let droppedEntriesCount = 0; if (!this.#calledAtLeastOnce) { droppedEntriesCount = - NativePerformance.getDroppedEntriesCount?.(observerHandle) ?? 0; + NativePerformance.getDroppedEntriesCount(observerHandle); this.#calledAtLeastOnce = true; } diff --git a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js index 9f9e6615ccf6ff..5c46106f95d7fb 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/EventTimingAPI-itest.js @@ -13,7 +13,7 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; import type Performance from 'react-native/src/private/webapis/performance/Performance'; import type {PerformanceObserverEntryList} from 'react-native/src/private/webapis/performance/PerformanceObserver'; -import NativePerformance from '../specs/NativePerformance'; +import MaybeNativePerformance from '../specs/NativePerformance'; import * as Fantom from '@react-native/fantom'; import nullthrows from 'nullthrows'; import {useState} from 'react'; @@ -22,6 +22,8 @@ import setUpPerformanceObserver from 'react-native/src/private/setup/setUpPerfor import {PerformanceEventTiming} from 'react-native/src/private/webapis/performance/EventTiming'; import {PerformanceObserver} from 'react-native/src/private/webapis/performance/PerformanceObserver'; +const NativePerformance = nullthrows(MaybeNativePerformance); + setUpPerformanceObserver(); declare var performance: Performance; @@ -193,7 +195,7 @@ describe('Event Timing API', () => { }); it('reports number of dispatched events via performance.eventCounts', () => { - NativePerformance?.clearEventCountsForTesting?.(); + NativePerformance.clearEventCountsForTesting?.(); const root = Fantom.createRoot(); Fantom.runTask(() => { diff --git a/packages/react-native/src/private/webapis/performance/__tests__/UserTiming-itest.js b/packages/react-native/src/private/webapis/performance/__tests__/UserTiming-itest.js index 85fa6443510613..e1a469740062f8 100644 --- a/packages/react-native/src/private/webapis/performance/__tests__/UserTiming-itest.js +++ b/packages/react-native/src/private/webapis/performance/__tests__/UserTiming-itest.js @@ -18,8 +18,11 @@ import type { import ensureInstance from '../../../__tests__/utilities/ensureInstance'; import DOMException from '../../errors/DOMException'; -import NativePerformance from '../specs/NativePerformance'; +import MaybeNativePerformance from '../specs/NativePerformance'; import {PerformanceMark, PerformanceMeasure} from '../UserTiming'; +import nullthrows from 'nullthrows'; + +const NativePerformance = nullthrows(MaybeNativePerformance); declare var performance: Performance; @@ -44,7 +47,7 @@ describe('User Timing', () => { describe('mark', () => { it('works with default timestamp', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); const mark = performance.mark('mark-now'); @@ -144,7 +147,7 @@ describe('User Timing', () => { describe('measure', () => { describe('with measureOptions', () => { it('uses 0 as default start and now as default end', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); const measure = performance.measure('measure-with-defaults', {}); @@ -157,7 +160,7 @@ describe('User Timing', () => { }); it('works with a start timestamp', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); const measure = performance.measure('measure-with-start-timestamp', { start: 10, @@ -172,7 +175,7 @@ describe('User Timing', () => { }); it('works with start mark', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { startTime: 10, @@ -191,7 +194,7 @@ describe('User Timing', () => { }); it('works with end mark', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); performance.mark('end-mark', { startTime: 50, @@ -210,7 +213,7 @@ describe('User Timing', () => { }); it('works with start mark and end mark', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { startTime: 10, @@ -375,7 +378,7 @@ describe('User Timing', () => { describe('with startMark / endMark', () => { it('uses 0 as default start and now as default end', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); const measure = performance.measure('measure-with-defaults'); @@ -388,7 +391,7 @@ describe('User Timing', () => { }); it('works with startMark', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { startTime: 10, @@ -408,7 +411,7 @@ describe('User Timing', () => { }); it('works with startMark and endMark', () => { - NativePerformance?.setCurrentTimeStampForTesting?.(25); + NativePerformance.setCurrentTimeStampForTesting?.(25); performance.mark('start-mark', { startTime: 10, From 532b41596050d2e49ca5621b4149744376d8f5c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Fri, 18 Jul 2025 04:19:28 -0700 Subject: [PATCH 0179/1383] Throw an error when using an unrecognized @fantom_ prefixed pragma (#52701) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52701 Changelog: [internal] This adds validation for Fantom test file pragmas to avoid ignoring configurations accidentally when introducing typos. Reviewed By: rshest Differential Revision: D78550866 fbshipit-source-id: 7123bfb39573adbb1adf417c232cf7d4cae4cd25 --- .../runner/getFantomTestConfigs.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/private/react-native-fantom/runner/getFantomTestConfigs.js b/private/react-native-fantom/runner/getFantomTestConfigs.js index 027074a7e42585..ba4e1a699a5c59 100644 --- a/private/react-native-fantom/runner/getFantomTestConfigs.js +++ b/private/react-native-fantom/runner/getFantomTestConfigs.js @@ -82,6 +82,13 @@ const FANTOM_BENCHMARK_DEFAULT_MODE: FantomTestConfigMode = const MAX_FANTOM_CONFIGURATION_VARIATIONS = 12; +const VALID_FANTOM_PRAGMAS = [ + 'fantom_mode', + 'fantom_flags', + 'fantom_hermes_variant', + 'fantom_react_fb_flags', +]; + /** * Extracts the Fantom configurations from the test file, specified as part of * the docblock comment. E.g.: @@ -118,6 +125,8 @@ export default function getFantomTestConfigs( const docblock = extract(testContents); const pragmas = parse(docblock) as DocblockPragmas; + verifyFantomPragmas(pragmas); + const config: FantomTestConfig = { mode: DEFAULT_MODE, hermesVariant: DEFAULT_HERMES_VARIANT, @@ -401,3 +410,19 @@ function parseFeatureFlagValue( throw new Error(`Unsupported feature flag type: ${typeof defaultValue}`); } } + +function verifyFantomPragmas(pragmas: DocblockPragmas): void { + for (const pragma of Object.keys(pragmas)) { + if ( + pragma.startsWith('fantom_') && + !VALID_FANTOM_PRAGMAS.includes(pragma) + ) { + const validFantomPragmas = VALID_FANTOM_PRAGMAS.map(p => `@${p}`).join( + ', ', + ); + throw new Error( + `Unrecognized Fantom pragma @${pragma}. Valid pragmas are ${validFantomPragmas}.`, + ); + } + } +} From 5cda3065ce635460a7458cbab5c10e24bea3bfe2 Mon Sep 17 00:00:00 2001 From: Jakub Piasecki Date: Fri, 18 Jul 2025 06:50:29 -0700 Subject: [PATCH 0180/1383] Update font scale on Android when recreating RootView (#52595) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52595 Changelog: [ANDROID][FIXED] Update font scale when recreating `RootView` At the moment `enableFontScaleChangesUpdatingLayout` flag only works when the activity is configured to handle font scale changes by itself (`configChanges="fontScale"` in the manifest). When that configuration is missing, the OS handles the font scale changes by recreating the activity, but in this case the path responsible for updating internally kept font size isn't executed. This diff updates the RootView, so that the display metrics are also updated when it's created. Alternative approach would be to do that on the Activity, but that assumes usage of `ReactActivity`. Reviewed By: NickGerleman Differential Revision: D78323174 fbshipit-source-id: e48583091767497b5dfd4f2d938329530de4068d --- .../src/main/java/com/facebook/react/ReactRootView.java | 4 ++++ 1 file changed, 4 insertions(+) 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 e421de963ef7c4..a807346d3f9dbb 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 @@ -135,6 +135,10 @@ public ReactRootView(Context context, AttributeSet attrs, int defStyle) { private void init() { setRootViewTag(ReactRootViewTagGenerator.getNextRootViewTag()); setClipChildren(false); + + if (ReactNativeFeatureFlags.enableFontScaleChangesUpdatingLayout()) { + DisplayMetricsHolder.initDisplayMetrics(getContext().getApplicationContext()); + } } @Override From 5e3edafec6c69558521061dced7a6bcd046576b0 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Fri, 18 Jul 2025 08:07:54 -0700 Subject: [PATCH 0181/1383] Migrate RNTester to use `{usesCleartextTraffic}` Manifest Placeholder (#52620) Summary: This creates a `debugOptimized` build type for React Native Android, meaning that we can run C++ optimization on the debug build, while still having the debugger enabled. This is aimed at improving the developer experience for folks developing on low-end devices or emulators. Users that intend to debug can still use the `debug` variant where the full debug symbols are shipped. ## Changelog: [ANDROID] [ADDED] - Create a debugOptimized buildType for Android Pull Request resolved: https://github.com/facebook/react-native/pull/52620 Test Plan: Tested locally with RNTester by doing: ``` ./gradlew installDebugOptimized ``` This is the output of the 3 generated .aar. The size difference is a proof that we're correctly stripping out the C++ debug symbols: Screenshot 2025-07-15 at 17 49 50 Screenshot 2025-07-15 at 17 49 39 Screenshot 2025-07-15 at 17 49 32 Rollback Plan: Reviewed By: cipolleschi Differential Revision: D78351347 Pulled By: cortinico fbshipit-source-id: 568a484ba8d2ee6e089cabc95451938e853fbc54 --- .../kotlin/com/facebook/react/ReactPlugin.kt | 2 ++ .../react/utils/AgpConfiguratorUtils.kt | 21 +++++++++++++++++++ .../android/app/src/debug/AndroidManifest.xml | 8 ------- .../android/app/src/main/AndroidManifest.xml | 1 + 4 files changed, 24 insertions(+), 8 deletions(-) delete mode 100644 packages/rn-tester/android/app/src/debug/AndroidManifest.xml diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt index 85f8ca32aaf142..3d40455a43a366 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt @@ -18,6 +18,7 @@ import com.facebook.react.tasks.GenerateEntryPointTask import com.facebook.react.tasks.GeneratePackageListTask import com.facebook.react.utils.AgpConfiguratorUtils.configureBuildConfigFieldsForApp import com.facebook.react.utils.AgpConfiguratorUtils.configureBuildConfigFieldsForLibraries +import com.facebook.react.utils.AgpConfiguratorUtils.configureBuildTypesForApp import com.facebook.react.utils.AgpConfiguratorUtils.configureDevServerLocation import com.facebook.react.utils.AgpConfiguratorUtils.configureNamespaceForLibraries import com.facebook.react.utils.BackwardCompatUtils.configureBackwardCompatibilityReactMap @@ -84,6 +85,7 @@ class ReactPlugin : Plugin { configureAutolinking(project, extension) configureCodegen(project, extension, rootExtension, isLibrary = false) configureResources(project, extension) + configureBuildTypesForApp(project) } // Library Only Configuration diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt index f8bee6923f901c..f33353349b2c85 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt @@ -19,6 +19,7 @@ import java.net.Inet4Address import java.net.NetworkInterface import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory +import kotlin.plus import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.plugins.AppliedPlugin @@ -27,6 +28,26 @@ import org.w3c.dom.Element @Suppress("UnstableApiUsage") internal object AgpConfiguratorUtils { + fun configureBuildTypesForApp(project: Project) { + val action = + Action { + project.extensions + .getByType(ApplicationAndroidComponentsExtension::class.java) + .finalizeDsl { ext -> + ext.buildTypes { + val debug = + getByName("debug").apply { + manifestPlaceholders["usesCleartextTraffic"] = "true" + } + getByName("release").apply { + manifestPlaceholders["usesCleartextTraffic"] = "false" + } + } + } + } + project.pluginManager.withPlugin("com.android.application", action) + } + fun configureBuildConfigFieldsForApp(project: Project, extension: ReactExtension) { val action = Action { diff --git a/packages/rn-tester/android/app/src/debug/AndroidManifest.xml b/packages/rn-tester/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index fa26aa56e1c144..00000000000000 --- a/packages/rn-tester/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - diff --git a/packages/rn-tester/android/app/src/main/AndroidManifest.xml b/packages/rn-tester/android/app/src/main/AndroidManifest.xml index bd35388167baa1..a842f3a0d29136 100644 --- a/packages/rn-tester/android/app/src/main/AndroidManifest.xml +++ b/packages/rn-tester/android/app/src/main/AndroidManifest.xml @@ -50,6 +50,7 @@ Date: Fri, 18 Jul 2025 08:07:54 -0700 Subject: [PATCH 0182/1383] Migrate helloworld to use `{usesCleartextTraffic}` manifest placeholder (#52647) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52647 This removes the need to specify 2 Manifests for apps and we can just use the `main` manifes to toggle if `usesCleartextTraffic` should be enabled or not. This will have to be replicated in the template repository. Changelog: [Android] [Added] - Add support to specify a single Manifest rather than 2 (main/debug) by using the `usesCleartextTraffic` manifest placeholder which is autoconfigured by RNGP. Reviewed By: cipolleschi Differential Revision: D78425139 fbshipit-source-id: 9173a014b387d5aed5f7087fa69b7bd49c220f2c --- .../helloworld/android/app/src/debug/AndroidManifest.xml | 9 --------- .../helloworld/android/app/src/main/AndroidManifest.xml | 1 + 2 files changed, 1 insertion(+), 9 deletions(-) delete mode 100644 private/helloworld/android/app/src/debug/AndroidManifest.xml diff --git a/private/helloworld/android/app/src/debug/AndroidManifest.xml b/private/helloworld/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index eb98c01afd79a6..00000000000000 --- a/private/helloworld/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/private/helloworld/android/app/src/main/AndroidManifest.xml b/private/helloworld/android/app/src/main/AndroidManifest.xml index 4122f36a590a44..fe3dfae11627d8 100644 --- a/private/helloworld/android/app/src/main/AndroidManifest.xml +++ b/private/helloworld/android/app/src/main/AndroidManifest.xml @@ -8,6 +8,7 @@ android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" + android:usesCleartextTraffic="${usesCleartextTraffic}" android:theme="@style/AppTheme"> Date: Fri, 18 Jul 2025 08:07:54 -0700 Subject: [PATCH 0183/1383] Create a debugOptimized buildType for Android (#52648) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52648 This creates a `debugOptimized` build type for React Native Android, meaning that we can run C++ optimization on the debug build, while still having the debugger enabled. This is aimed at improving the developer experience for folks developing on low-end devices or emulators. Users that intend to debug can still use the `debug` variant where the full debug symbols are shipped. Changelog: [ANDROID] [ADDED] - Create a debugOptimized buildType for Android Reviewed By: cipolleschi Differential Revision: D78425138 fbshipit-source-id: c1e9ea3608e7df10fb871a5584352f0747cf560b --- .../main/kotlin/com/facebook/react/ReactExtension.kt | 4 ++-- .../com/facebook/react/utils/AgpConfiguratorUtils.kt | 10 ++++++++++ packages/react-native/ReactAndroid/build.gradle.kts | 11 ++++++++++- .../ReactAndroid/hermes-engine/build.gradle.kts | 6 ++++++ .../jni/react/hermes/reactexecutor/CMakeLists.txt | 4 +++- .../main/jni/react/runtime/hermes/jni/CMakeLists.txt | 4 +++- .../src/main/jni/react/runtime/jni/CMakeLists.txt | 4 +++- .../ReactCommon/hermes/executor/CMakeLists.txt | 2 +- .../hermes/inspector-modern/CMakeLists.txt | 2 +- .../ReactCommon/jsinspector-modern/CMakeLists.txt | 10 ++++++---- .../ReactCommon/react/debug/CMakeLists.txt | 2 +- .../ReactCommon/react/runtime/CMakeLists.txt | 4 +++- .../ReactCommon/react/runtime/hermes/CMakeLists.txt | 2 +- 13 files changed, 50 insertions(+), 15 deletions(-) diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt index fa9c937361156b..2e89b8c281dd9c 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt @@ -100,10 +100,10 @@ abstract class ReactExtension @Inject constructor(val project: Project) { * Allows to specify the debuggable variants (by default just 'debug'). Variants in this list will * not be bundled (the bundle file will not be created and won't be copied over). * - * Default: ['debug'] + * Default: ['debug', 'debugOptimized'] */ val debuggableVariants: ListProperty = - objects.listProperty(String::class.java).convention(listOf("debug")) + objects.listProperty(String::class.java).convention(listOf("debug", "debugOptimized")) /** Hermes Config */ diff --git a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt index f33353349b2c85..c11d0ccf163224 100644 --- a/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt +++ b/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt @@ -42,6 +42,16 @@ internal object AgpConfiguratorUtils { getByName("release").apply { manifestPlaceholders["usesCleartextTraffic"] = "false" } + maybeCreate("debugOptimized").apply { + manifestPlaceholders["usesCleartextTraffic"] = "true" + initWith(debug) + externalNativeBuild { + cmake { + arguments("-DCMAKE_BUILD_TYPE=Release") + matchingFallbacks += listOf("release") + } + } + } } } } diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index 50d2d57927e8c7..ff2b486c4b98c3 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -599,7 +599,7 @@ android { publishing { multipleVariants { withSourcesJar() - includeBuildTypeValues("debug", "release") + includeBuildTypeValues("debug", "release", "debugOptimized") } } @@ -607,6 +607,15 @@ android { unitTests { isIncludeAndroidResources = true } targetSdk = libs.versions.targetSdk.get().toInt() } + + buildTypes { + create("debugOptimized") { + initWith(getByName("debug")) + externalNativeBuild { + cmake { arguments("-DCMAKE_BUILD_TYPE=Release", "-DREACT_NATIVE_DEBUG_OPTIMIZED=True") } + } + } + } } tasks.withType().configureEach { diff --git a/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts b/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts index d0228e0d4d910c..69814d86625727 100644 --- a/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts +++ b/packages/react-native/ReactAndroid/hermes-engine/build.gradle.kts @@ -306,6 +306,12 @@ android { } } } + buildTypes { + create("debugOptimized") { + initWith(getByName("debug")) + externalNativeBuild { cmake { arguments("-DCMAKE_BUILD_TYPE=Release") } } + } + } } sourceSets.getByName("main") { diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/CMakeLists.txt index d0d015ccc55d4c..aa973151b94921 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/CMakeLists.txt @@ -25,4 +25,6 @@ target_link_libraries( reactnative ) target_compile_reactnative_options(hermes_executor PRIVATE) -target_compile_options(hermes_executor PRIVATE $<$:-DHERMES_ENABLE_DEBUGGER=1>) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) + target_compile_options(hermes_executor PRIVATE -DHERMES_ENABLE_DEBUGGER=1) +endif() diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/CMakeLists.txt index 6b182daa3acb65..63c1a937341b3f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/CMakeLists.txt @@ -27,4 +27,6 @@ target_link_libraries(hermesinstancejni ) target_compile_reactnative_options(hermesinstancejni PRIVATE) -target_compile_options(hermesinstancejni PRIVATE $<$:-DHERMES_ENABLE_DEBUGGER=1>) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) + target_compile_options(hermesinstancejni PRIVATE -DHERMES_ENABLE_DEBUGGER=1) +endif () diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/CMakeLists.txt index 0633be11254ec2..8987aed037633a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/CMakeLists.txt @@ -17,7 +17,9 @@ add_library(rninstance ) target_compile_reactnative_options(rninstance PRIVATE) -target_compile_options(rninstance PRIVATE $<$:-DHERMES_ENABLE_DEBUGGER=1>) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) + target_compile_options(rninstance PRIVATE -DHERMES_ENABLE_DEBUGGER=1) +endif () target_merge_so(rninstance) target_include_directories(rninstance PUBLIC .) diff --git a/packages/react-native/ReactCommon/hermes/executor/CMakeLists.txt b/packages/react-native/ReactCommon/hermes/executor/CMakeLists.txt index b512daeafd8fcf..4c1d72be560bc2 100644 --- a/packages/react-native/ReactCommon/hermes/executor/CMakeLists.txt +++ b/packages/react-native/ReactCommon/hermes/executor/CMakeLists.txt @@ -26,7 +26,7 @@ target_link_libraries(hermes_executor_common ) target_compile_reactnative_options(hermes_executor_common PRIVATE) -if(${CMAKE_BUILD_TYPE} MATCHES Debug) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) target_compile_options( hermes_executor_common PRIVATE diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/CMakeLists.txt b/packages/react-native/ReactCommon/hermes/inspector-modern/CMakeLists.txt index 37dbf64c1876d9..3344bf7c4d8c1d 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/CMakeLists.txt +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/CMakeLists.txt @@ -17,7 +17,7 @@ add_library(hermes_inspector_modern target_compile_reactnative_options(hermes_inspector_modern PRIVATE) -if(${CMAKE_BUILD_TYPE} MATCHES Debug) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) target_compile_options( hermes_inspector_modern PRIVATE diff --git a/packages/react-native/ReactCommon/jsinspector-modern/CMakeLists.txt b/packages/react-native/ReactCommon/jsinspector-modern/CMakeLists.txt index 437f8c303cb92e..e06c951fd91fb1 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/CMakeLists.txt +++ b/packages/react-native/ReactCommon/jsinspector-modern/CMakeLists.txt @@ -28,7 +28,9 @@ target_link_libraries(jsinspector reactperflogger ) target_compile_reactnative_options(jsinspector PRIVATE) -target_compile_options(jsinspector PRIVATE - $<$:-DREACT_NATIVE_DEBUGGER_ENABLED=1> - $<$:-DREACT_NATIVE_DEBUGGER_ENABLED_DEVONLY=1> -) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) + target_compile_options(jsinspector PRIVATE + -DREACT_NATIVE_DEBUGGER_ENABLED=1 + -DREACT_NATIVE_DEBUGGER_ENABLED_DEVONLY=1 + ) +endif () diff --git a/packages/react-native/ReactCommon/react/debug/CMakeLists.txt b/packages/react-native/ReactCommon/react/debug/CMakeLists.txt index 35e81ec635034b..448f163308c616 100644 --- a/packages/react-native/ReactCommon/react/debug/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/debug/CMakeLists.txt @@ -21,6 +21,6 @@ endif() target_compile_reactnative_options(react_debug PRIVATE) target_compile_options(react_debug PRIVATE -Wpedantic) -if(NOT ${CMAKE_BUILD_TYPE} MATCHES Debug) +if(NOT ${CMAKE_BUILD_TYPE} MATCHES Debug AND NOT REACT_NATIVE_DEBUG_OPTIMIZED) target_compile_options(react_debug PUBLIC -DNDEBUG) endif() diff --git a/packages/react-native/ReactCommon/react/runtime/CMakeLists.txt b/packages/react-native/ReactCommon/react/runtime/CMakeLists.txt index 51ffc864b16fe2..0cf910be5bfda1 100644 --- a/packages/react-native/ReactCommon/react/runtime/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/runtime/CMakeLists.txt @@ -16,7 +16,9 @@ add_library(bridgeless ${bridgeless_SRC} ) target_compile_reactnative_options(bridgeless PRIVATE) -target_compile_options(bridgeless PRIVATE $<$:-DHERMES_ENABLE_DEBUGGER=1>) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) + target_compile_options(bridgeless PRIVATE -DHERMES_ENABLE_DEBUGGER=1) +endif () target_include_directories(bridgeless PUBLIC .) react_native_android_selector(fabricjni fabricjni "") diff --git a/packages/react-native/ReactCommon/react/runtime/hermes/CMakeLists.txt b/packages/react-native/ReactCommon/react/runtime/hermes/CMakeLists.txt index d531e870b851b1..dc1a5dd9cab836 100644 --- a/packages/react-native/ReactCommon/react/runtime/hermes/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/runtime/hermes/CMakeLists.txt @@ -29,7 +29,7 @@ target_link_libraries(bridgelesshermes ) target_compile_reactnative_options(bridgelesshermes PRIVATE) -if(${CMAKE_BUILD_TYPE} MATCHES Debug) +if(${CMAKE_BUILD_TYPE} MATCHES Debug OR REACT_NATIVE_DEBUG_OPTIMIZED) target_compile_options( bridgelesshermes PRIVATE From e186f1bf1725607d163a7acd29e0942673113fa1 Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Fri, 18 Jul 2025 08:28:34 -0700 Subject: [PATCH 0184/1383] Fix CQS signal modernize-use-using in xplat/js/react-native-github/packages [B] (#52693) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52693 Reviewed By: dtolnay Differential Revision: D78494711 fbshipit-source-id: 870e300b29e41aec488926cdf416f246de96514d --- packages/react-native/React/Views/RCTFont.mm | 4 ++-- packages/react-native/ReactCommon/cxxreact/CxxModule.h | 4 ++-- .../react-native/ReactCommon/cxxreact/JsArgumentHelpers.h | 4 ++-- packages/react-native/ReactCommon/logger/react_native_log.h | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/react-native/React/Views/RCTFont.mm b/packages/react-native/React/Views/RCTFont.mm index fe350138fd9590..ed6425e9cf2b2a 100644 --- a/packages/react-native/React/Views/RCTFont.mm +++ b/packages/react-native/React/Views/RCTFont.mm @@ -205,7 +205,7 @@ + (UIFont *)UIFont:(id)json UIFontWeightRegular, doubleValue) -typedef BOOL RCTFontStyle; +using RCTFontStyle = BOOL; RCT_ENUM_CONVERTER( RCTFontStyle, (@{ @@ -216,7 +216,7 @@ + (UIFont *)UIFont:(id)json NO, boolValue) -typedef NSDictionary RCTFontVariantDescriptor; +using RCTFontVariantDescriptor = NSDictionary; + (RCTFontVariantDescriptor *)RCTFontVariantDescriptor:(id)json { static NSDictionary *mapping; diff --git a/packages/react-native/ReactCommon/cxxreact/CxxModule.h b/packages/react-native/ReactCommon/cxxreact/CxxModule.h index fed1a7353a3b47..a825c401388abc 100644 --- a/packages/react-native/ReactCommon/cxxreact/CxxModule.h +++ b/packages/react-native/ReactCommon/cxxreact/CxxModule.h @@ -53,9 +53,9 @@ class CxxModule { class SyncTagType {}; public: - typedef std::function()> Provider; + using Provider = std::function()>; - typedef std::function)> Callback; + using Callback = std::function)>; constexpr static AsyncTagType AsyncTag = AsyncTagType(); constexpr static SyncTagType SyncTag = SyncTagType(); diff --git a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h index 9a907017985c05..cf5343cb3e7348 100644 --- a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h +++ b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h @@ -68,8 +68,8 @@ namespace detail { // only for types compatible with folly::dynamic. template struct is_dynamic { - typedef typename std:: - enable_if::value, T>::type type; + using type = typename std:: + enable_if::value, T>::type; }; } // end namespace detail diff --git a/packages/react-native/ReactCommon/logger/react_native_log.h b/packages/react-native/ReactCommon/logger/react_native_log.h index 5f585efa4287c0..a05b4c6e6a31a7 100644 --- a/packages/react-native/ReactCommon/logger/react_native_log.h +++ b/packages/react-native/ReactCommon/logger/react_native_log.h @@ -14,7 +14,7 @@ enum ReactNativeLogLevel { ReactNativeLogLevelFatal = 4 }; -typedef void (*reactnativelogfunctype)(ReactNativeLogLevel, const char*); +using reactnativelogfunctype = void (*)(ReactNativeLogLevel, const char*); #ifdef __cplusplus extern "C" { From 37a0517b3fbaa0fa01b662881661d3af54583cb2 Mon Sep 17 00:00:00 2001 From: generatedunixname1395667395051502 Date: Fri, 18 Jul 2025 08:54:36 -0700 Subject: [PATCH 0185/1383] Update React Native DevTools binaries Summary: Automated update of React Native DevTools binaries bypass-github-export-checks Changelog: [Internal] Reviewed By: robhogan Differential Revision: D78413554 fbshipit-source-id: 5b0d64f886db4cf121f4a6761e6a3e7fe1ccceec --- .../debugger-shell/bin/react-native-devtools | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100755 packages/debugger-shell/bin/react-native-devtools diff --git a/packages/debugger-shell/bin/react-native-devtools b/packages/debugger-shell/bin/react-native-devtools new file mode 100755 index 00000000000000..a1fc11d8581040 --- /dev/null +++ b/packages/debugger-shell/bin/react-native-devtools @@ -0,0 +1,62 @@ +#!/usr/bin/env dotslash + +// @generated SignedSource<<686df5695b32a90cd465412d979a1a3f>> + + +{ + "name": "React Native DevTools", + "platforms": { + "linux-aarch64": { + "size": 113511487, + "hash": "sha256", + "digest": "c22f7d5e029357f05055ce7c56cc284a0d441d558e103a7b7ebae118c67d0b95", + "providers": [ + { + "type": "http", + "url": "https://scontent.xx.fbcdn.net/mci_ab/uap/?ab_b=m&ab_page=react_native_devtools_binaries&ab_entry=AQPRilWDJV8xyKEv9lqYn7Hf2kyZg6nqW8KctGZCXsU95lS_MTFyAmEULrB3J6hGCjqBY2Zl-uq_FjERAIgzbZFWX2eceacTbutBSOKEj6QTZzkVN_L1zPh2lGh24x29MHpkwUzw4E-kAXV43f-11QxqD7orI1QicyOnsmUqeRNKE_QjM9rNRsw6iE8" + } + ], + "format": "tar.gz", + "path": "React Native DevTools-linux-arm64/React Native DevTools" + }, + "linux-x86_64": { + "size": 113244728, + "hash": "sha256", + "digest": "d749aee18d6c969f033511ed631b439c578068cc20786974bc0ee707c6c2f177", + "providers": [ + { + "type": "http", + "url": "https://scontent.xx.fbcdn.net/mci_ab/uap/?ab_b=m&ab_page=react_native_devtools_binaries&ab_entry=AQP8NAAXjHJ-9NJThip1nnmVim4yiS1tdYAXmWl2Remiluq5f13nXA8YEadsmGRLWxXz2WJouHXSK47ea4a30fxewyKeTt0niFn3T-lr_91m3Ve5ZS-FOZ_9CRVCkv5zC-Z1FlXJGOnphfWetIU10Pw9tho3IzjdSNlXle0XTrkJ2AyKSl4cKPaX" + } + ], + "format": "tar.gz", + "path": "React Native DevTools-linux-x64/React Native DevTools" + }, + "macos-aarch64": { + "size": 108805847, + "hash": "sha256", + "digest": "dc4a6cfa3d2d8646db8793ef497e43ad72be54bb14ed96345d059880ff72ce1e", + "providers": [ + { + "type": "http", + "url": "https://scontent.xx.fbcdn.net/mci_ab/uap/?ab_b=m&ab_page=react_native_devtools_binaries&ab_entry=AQPuZx9G4h30mUDM0hZ8y74LbzAi7-S6jnOqq8uyfDdIptLwIgpb8CKB8F2tduvaBFMGd7obwXd2NVy01r6XKVdgAK5-QTp8PYUPUE7VSCi6QAqobXcQ2uq_lY-jgyj8XkV4Ua4gA6KR609Bmh-beSTOrSqMymqVodaGqoGjB_9jVwfD99_PfFlex-Ta" + } + ], + "format": "tar.gz", + "path": "React Native DevTools.app/Contents/MacOS/React Native DevTools" + }, + "macos-x86_64": { + "size": 113766610, + "hash": "sha256", + "digest": "74178859ce6a1c26c32055e192b1b123822c76c827ea86a6dfdb5463b89b1ace", + "providers": [ + { + "type": "http", + "url": "https://scontent.xx.fbcdn.net/mci_ab/uap/?ab_b=m&ab_page=react_native_devtools_binaries&ab_entry=AQN6DjGhr8_L7N_cwrh8pi3cfNcbn9dot_QQpgwe3Vv-780FDgi6JUeMvbo_wbFoT2rogxfHZ0-NbXbKdWYwhGUoGeQuikT57QnVMOYuPUTjlQUgYy0Ng9XPhq3iSEYwlMV1XsUJuPFRUg-hIHcgaaA55JoTLXZ1fLYydhHnmgRxGHc4pxaHvSpTtQ" + } + ], + "format": "tar.gz", + "path": "React Native DevTools.app/Contents/MacOS/React Native DevTools" + } + } +} From ae3b793de61f7d2f1a42461d1e63d9167b72840c Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Fri, 18 Jul 2025 09:01:22 -0700 Subject: [PATCH 0186/1383] Fix CQS signal modernize-use-using in xplat/js/react-native-github/packages [A] [A] (#52708) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52708 Reviewed By: rshest Differential Revision: D78538428 fbshipit-source-id: 6195ead0fa36e5fc4632e9a57362508f55969380 --- packages/react-native/React/CxxBridge/RCTCxxBridge.mm | 2 +- .../React/DevSupport/RCTInspectorNetworkHelper.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm index bab39104d5234b..9ea645d4752688 100644 --- a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm +++ b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm @@ -66,7 +66,7 @@ static NSString *const RCTJSThreadName = @"com.facebook.react.JavaScript"; -typedef void (^RCTPendingCall)(); +using RCTPendingCall = void (^)(); using namespace facebook::jsi; using namespace facebook::react; diff --git a/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.h b/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.h index 3494b5b9135c07..db6091f62ffbfc 100644 --- a/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.h +++ b/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.h @@ -11,11 +11,11 @@ #import -typedef facebook::react::jsinspector_modern::NetworkRequestListener RCTInspectorNetworkListener; +using RCTInspectorNetworkListener = facebook::react::jsinspector_modern::NetworkRequestListener; -typedef facebook::react::jsinspector_modern::ScopedExecutor RCTInspectorNetworkExecutor; +using RCTInspectorNetworkExecutor = facebook::react::jsinspector_modern::ScopedExecutor; -typedef facebook::react::jsinspector_modern::LoadNetworkResourceRequest RCTInspectorLoadNetworkResourceRequest; +using RCTInspectorLoadNetworkResourceRequest = facebook::react::jsinspector_modern::LoadNetworkResourceRequest; /** * A helper class that wraps around NSURLSession to make network requests. From 9f0903780b9041a78f005e0bbc0046b1eb592dde Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Fri, 18 Jul 2025 09:23:10 -0700 Subject: [PATCH 0187/1383] Bump monorepo packages to 0.82.0-main (#52706) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52706 This just prepares the repo for the next branch cut. Changelog: [Internal] [Changed] - Reviewed By: cipolleschi Differential Revision: D78558445 fbshipit-source-id: 2132d560dad447b3685874438387a519587f8554 --- package.json | 4 ++-- packages/assets/package.json | 2 +- packages/babel-plugin-codegen/package.json | 4 ++-- packages/community-cli-plugin/package.json | 4 ++-- packages/core-cli-utils/package.json | 2 +- packages/debugger-frontend/package.json | 2 +- packages/debugger-shell/package.json | 2 +- packages/dev-middleware/package.json | 4 ++-- packages/eslint-config-react-native/package.json | 4 ++-- packages/eslint-plugin-react-native/package.json | 2 +- packages/eslint-plugin-specs/package.json | 4 ++-- packages/gradle-plugin/package.json | 2 +- packages/metro-config/package.json | 6 +++--- packages/new-app-screen/package.json | 2 +- packages/normalize-color/package.json | 2 +- packages/polyfills/package.json | 2 +- packages/react-native-babel-preset/package.json | 4 ++-- .../react-native-babel-transformer/package.json | 4 ++-- packages/react-native-codegen/package.json | 2 +- .../react-native-compatibility-check/package.json | 4 ++-- .../react-native-popup-menu-android/package.json | 4 ++-- packages/react-native-test-library/package.json | 4 ++-- packages/react-native/package.json | 14 +++++++------- packages/rn-tester/package.json | 8 ++++---- packages/typescript-config/package.json | 2 +- packages/virtualized-lists/package.json | 2 +- private/helloworld/package.json | 10 +++++----- .../package.json | 2 +- 28 files changed, 54 insertions(+), 54 deletions(-) diff --git a/package.json b/package.json index 37d71aa2d9cca4..43852e6b301e5c 100644 --- a/package.json +++ b/package.json @@ -56,8 +56,8 @@ "@electron/packager": "^18.3.6", "@jest/create-cache-key-function": "^29.7.0", "@microsoft/api-extractor": "^7.52.2", - "@react-native/metro-babel-transformer": "0.81.0-main", - "@react-native/metro-config": "0.81.0-main", + "@react-native/metro-babel-transformer": "0.82.0-main", + "@react-native/metro-config": "0.82.0-main", "@tsconfig/node22": "22.0.2", "@types/react": "^19.1.0", "@typescript-eslint/parser": "^8.36.0", diff --git a/packages/assets/package.json b/packages/assets/package.json index b36696ca1298b6..aff74ac9732b96 100644 --- a/packages/assets/package.json +++ b/packages/assets/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/assets-registry", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Asset support code for React Native.", "license": "MIT", "repository": { diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json index 366fabe53ba341..6af39526dbed5f 100644 --- a/packages/babel-plugin-codegen/package.json +++ b/packages/babel-plugin-codegen/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/babel-plugin-codegen", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Babel plugin to generate native module and view manager code for React Native.", "license": "MIT", "repository": { @@ -26,7 +26,7 @@ ], "dependencies": { "@babel/traverse": "^7.25.3", - "@react-native/codegen": "0.81.0-main" + "@react-native/codegen": "0.82.0-main" }, "devDependencies": { "@babel/core": "^7.25.2" diff --git a/packages/community-cli-plugin/package.json b/packages/community-cli-plugin/package.json index 1bbb6171da1c6f..d69f5cf5eb24a5 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.81.0-main", + "version": "0.82.0-main", "description": "Core CLI commands for React Native", "keywords": [ "react-native", @@ -22,7 +22,7 @@ "dist" ], "dependencies": { - "@react-native/dev-middleware": "0.81.0-main", + "@react-native/dev-middleware": "0.82.0-main", "debug": "^4.4.0", "invariant": "^2.2.4", "metro": "^0.83.0", diff --git a/packages/core-cli-utils/package.json b/packages/core-cli-utils/package.json index 78e68ece88b820..601eb124a5da8a 100644 --- a/packages/core-cli-utils/package.json +++ b/packages/core-cli-utils/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/core-cli-utils", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "React Native CLI library for Frameworks to build on", "license": "MIT", "main": "./src/index.flow.js", diff --git a/packages/debugger-frontend/package.json b/packages/debugger-frontend/package.json index 70ba87b219703c..1475dd77753fc3 100644 --- a/packages/debugger-frontend/package.json +++ b/packages/debugger-frontend/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/debugger-frontend", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Debugger frontend for React Native based on Chrome DevTools", "keywords": [ "react-native", diff --git a/packages/debugger-shell/package.json b/packages/debugger-shell/package.json index 44e6389f0ec52c..d95afdeeebdd03 100644 --- a/packages/debugger-shell/package.json +++ b/packages/debugger-shell/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/debugger-shell", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Experimental debugger shell for React Native for use with @react-native/debugger-frontend", "keywords": [ "react-native", diff --git a/packages/dev-middleware/package.json b/packages/dev-middleware/package.json index ad0b5f327bfd7d..e95686aa32398a 100644 --- a/packages/dev-middleware/package.json +++ b/packages/dev-middleware/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/dev-middleware", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Dev server middleware for React Native", "keywords": [ "react-native", @@ -23,7 +23,7 @@ ], "dependencies": { "@isaacs/ttlcache": "^1.4.1", - "@react-native/debugger-frontend": "0.81.0-main", + "@react-native/debugger-frontend": "0.82.0-main", "chrome-launcher": "^0.15.2", "chromium-edge-launcher": "^0.2.0", "connect": "^3.6.5", diff --git a/packages/eslint-config-react-native/package.json b/packages/eslint-config-react-native/package.json index a7e7481edc5e48..b22a235c64f9ff 100644 --- a/packages/eslint-config-react-native/package.json +++ b/packages/eslint-config-react-native/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/eslint-config", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "ESLint config for React Native", "license": "MIT", "repository": { @@ -22,7 +22,7 @@ "dependencies": { "@babel/core": "^7.25.2", "@babel/eslint-parser": "^7.25.1", - "@react-native/eslint-plugin": "0.81.0-main", + "@react-native/eslint-plugin": "0.82.0-main", "@typescript-eslint/eslint-plugin": "^8.36.0", "@typescript-eslint/parser": "^8.36.0", "eslint-config-prettier": "^8.5.0", diff --git a/packages/eslint-plugin-react-native/package.json b/packages/eslint-plugin-react-native/package.json index d7db05218a633b..e6819df62c14aa 100644 --- a/packages/eslint-plugin-react-native/package.json +++ b/packages/eslint-plugin-react-native/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/eslint-plugin", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "ESLint rules for @react-native/eslint-config", "license": "MIT", "repository": { diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json index 1c8fe173a38fa4..05897815ae55f4 100644 --- a/packages/eslint-plugin-specs/package.json +++ b/packages/eslint-plugin-specs/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/eslint-plugin-specs", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "ESLint rules to validate NativeModule and Component Specs", "license": "MIT", "repository": { @@ -26,7 +26,7 @@ "dependencies": { "@babel/core": "^7.25.2", "@babel/plugin-transform-flow-strip-types": "^7.25.2", - "@react-native/codegen": "0.81.0-main", + "@react-native/codegen": "0.82.0-main", "make-dir": "^2.1.0", "pirates": "^4.0.1", "source-map-support": "0.5.0" diff --git a/packages/gradle-plugin/package.json b/packages/gradle-plugin/package.json index 9675ec0401c9c9..bb4d12c2f2572c 100644 --- a/packages/gradle-plugin/package.json +++ b/packages/gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/gradle-plugin", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Gradle Plugin for React Native", "license": "MIT", "repository": { diff --git a/packages/metro-config/package.json b/packages/metro-config/package.json index a649cbe470754f..d8ee6a472e15e7 100644 --- a/packages/metro-config/package.json +++ b/packages/metro-config/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/metro-config", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Metro configuration for React Native.", "license": "MIT", "repository": { @@ -26,8 +26,8 @@ "dist" ], "dependencies": { - "@react-native/js-polyfills": "0.81.0-main", - "@react-native/metro-babel-transformer": "0.81.0-main", + "@react-native/js-polyfills": "0.82.0-main", + "@react-native/metro-babel-transformer": "0.82.0-main", "metro-config": "^0.83.0", "metro-runtime": "^0.83.0" } diff --git a/packages/new-app-screen/package.json b/packages/new-app-screen/package.json index 915753cfa157c9..d1926d11577487 100644 --- a/packages/new-app-screen/package.json +++ b/packages/new-app-screen/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/new-app-screen", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "NewAppScreen component for React Native", "keywords": [ "react-native" diff --git a/packages/normalize-color/package.json b/packages/normalize-color/package.json index 48b016fcb2b8c6..d6a7de133ca6df 100644 --- a/packages/normalize-color/package.json +++ b/packages/normalize-color/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/normalize-colors", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Color normalization for React Native.", "license": "MIT", "repository": { diff --git a/packages/polyfills/package.json b/packages/polyfills/package.json index 647594e12ec283..355da1286ac651 100644 --- a/packages/polyfills/package.json +++ b/packages/polyfills/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/js-polyfills", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Polyfills for React Native.", "license": "MIT", "repository": { diff --git a/packages/react-native-babel-preset/package.json b/packages/react-native-babel-preset/package.json index 1fc6149ea3475c..82a4c85f85047d 100644 --- a/packages/react-native-babel-preset/package.json +++ b/packages/react-native-babel-preset/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/babel-preset", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Babel preset for React Native applications", "repository": { "type": "git", @@ -66,7 +66,7 @@ "@babel/plugin-transform-typescript": "^7.25.2", "@babel/plugin-transform-unicode-regex": "^7.24.7", "@babel/template": "^7.25.0", - "@react-native/babel-plugin-codegen": "0.81.0-main", + "@react-native/babel-plugin-codegen": "0.82.0-main", "babel-plugin-syntax-hermes-parser": "0.29.1", "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 e41576ee44e8d8..e9d1d3d94a8529 100644 --- a/packages/react-native-babel-transformer/package.json +++ b/packages/react-native-babel-transformer/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/metro-babel-transformer", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Babel transformer for React Native applications.", "repository": { "type": "git", @@ -27,7 +27,7 @@ ], "dependencies": { "@babel/core": "^7.25.2", - "@react-native/babel-preset": "0.81.0-main", + "@react-native/babel-preset": "0.82.0-main", "hermes-parser": "0.29.1", "nullthrows": "^1.1.1" }, diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 7c727645e3a705..e48f0538e5937f 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/codegen", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Code generation tools for React Native", "license": "MIT", "repository": { diff --git a/packages/react-native-compatibility-check/package.json b/packages/react-native-compatibility-check/package.json index 258ac6d0729f1e..6d8f07fa1c625d 100644 --- a/packages/react-native-compatibility-check/package.json +++ b/packages/react-native-compatibility-check/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/compatibility-check", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Check a React Native app's boundary between JS and Native for incompatibilities", "license": "MIT", "repository": { @@ -29,7 +29,7 @@ "dist" ], "dependencies": { - "@react-native/codegen": "0.81.0-main" + "@react-native/codegen": "0.82.0-main" }, "devDependencies": { "flow-remove-types": "^2.237.2", diff --git a/packages/react-native-popup-menu-android/package.json b/packages/react-native-popup-menu-android/package.json index 38344be5bf0d8e..e34b574f4cac96 100644 --- a/packages/react-native-popup-menu-android/package.json +++ b/packages/react-native-popup-menu-android/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/popup-menu-android", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "PopupMenu for the Android platform", "main": "index.js", "files": [ @@ -21,7 +21,7 @@ }, "license": "MIT", "devDependencies": { - "@react-native/codegen": "0.81.0-main" + "@react-native/codegen": "0.82.0-main" }, "peerDependencies": { "@types/react": "^19.1.0", diff --git a/packages/react-native-test-library/package.json b/packages/react-native-test-library/package.json index 96311c75092f8d..e3cc74d743aa6c 100644 --- a/packages/react-native-test-library/package.json +++ b/packages/react-native-test-library/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/oss-library-example", - "version": "0.81.0-main", + "version": "0.82.0-main", "private": true, "description": "Package that includes native module exapmle, native component example, targets both the old and the new architecture. It should serve as an example of a real-world OSS library.", "license": "MIT", @@ -26,7 +26,7 @@ ], "devDependencies": { "@babel/core": "^7.25.2", - "@react-native/babel-preset": "0.81.0-main", + "@react-native/babel-preset": "0.82.0-main", "react-native": "1000.0.0" }, "peerDependencies": { diff --git a/packages/react-native/package.json b/packages/react-native/package.json index a3e2f40b0f907c..32bf6e367866ea 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -161,13 +161,13 @@ }, "dependencies": { "@jest/create-cache-key-function": "^29.7.0", - "@react-native/assets-registry": "0.81.0-main", - "@react-native/codegen": "0.81.0-main", - "@react-native/community-cli-plugin": "0.81.0-main", - "@react-native/gradle-plugin": "0.81.0-main", - "@react-native/js-polyfills": "0.81.0-main", - "@react-native/normalize-colors": "0.81.0-main", - "@react-native/virtualized-lists": "0.81.0-main", + "@react-native/assets-registry": "0.82.0-main", + "@react-native/codegen": "0.82.0-main", + "@react-native/community-cli-plugin": "0.82.0-main", + "@react-native/gradle-plugin": "0.82.0-main", + "@react-native/js-polyfills": "0.82.0-main", + "@react-native/normalize-colors": "0.82.0-main", + "@react-native/virtualized-lists": "0.82.0-main", "abort-controller": "^3.0.0", "anser": "^1.4.9", "ansi-regex": "^5.0.0", diff --git a/packages/rn-tester/package.json b/packages/rn-tester/package.json index cfde9ad7b0c4fa..57d48a4ab294d0 100644 --- a/packages/rn-tester/package.json +++ b/packages/rn-tester/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/tester", - "version": "0.81.0-main", + "version": "0.82.0-main", "private": true, "description": "React Native tester app.", "license": "MIT", @@ -26,9 +26,9 @@ "e2e-test-ios": "./scripts/maestro-test-ios.sh" }, "dependencies": { - "@react-native/oss-library-example": "0.81.0-main", - "@react-native/new-app-screen": "0.81.0-main", - "@react-native/popup-menu-android": "0.81.0-main", + "@react-native/oss-library-example": "0.82.0-main", + "@react-native/new-app-screen": "0.82.0-main", + "@react-native/popup-menu-android": "0.82.0-main", "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", "nullthrows": "^1.1.1" diff --git a/packages/typescript-config/package.json b/packages/typescript-config/package.json index 3a706f61b2889f..a00cd1a2fe912e 100644 --- a/packages/typescript-config/package.json +++ b/packages/typescript-config/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/typescript-config", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Default TypeScript configuration for React Native apps", "license": "MIT", "repository": { diff --git a/packages/virtualized-lists/package.json b/packages/virtualized-lists/package.json index f208d9d8cb05a7..b0d3d93b892101 100644 --- a/packages/virtualized-lists/package.json +++ b/packages/virtualized-lists/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/virtualized-lists", - "version": "0.81.0-main", + "version": "0.82.0-main", "description": "Virtualized lists for React Native.", "license": "MIT", "repository": { diff --git a/private/helloworld/package.json b/private/helloworld/package.json index 3a59bcbb34ce90..f53c401157f552 100644 --- a/private/helloworld/package.json +++ b/private/helloworld/package.json @@ -19,11 +19,11 @@ "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.25.0", - "@react-native/babel-preset": "0.81.0-main", - "@react-native/core-cli-utils": "0.81.0-main", - "@react-native/eslint-config": "0.81.0-main", - "@react-native/metro-config": "0.81.0-main", - "@react-native/typescript-config": "0.81.0-main", + "@react-native/babel-preset": "0.82.0-main", + "@react-native/core-cli-utils": "0.82.0-main", + "@react-native/eslint-config": "0.82.0-main", + "@react-native/metro-config": "0.82.0-main", + "@react-native/typescript-config": "0.82.0-main", "@types/jest": "^29.5.14", "commander": "^12.0.0", "eslint": "^8.19.0", diff --git a/private/react-native-codegen-typescript-test/package.json b/private/react-native-codegen-typescript-test/package.json index 9e68a255d084a0..1270bd5aafd136 100644 --- a/private/react-native-codegen-typescript-test/package.json +++ b/private/react-native-codegen-typescript-test/package.json @@ -13,7 +13,7 @@ "prepare": "yarn run build" }, "dependencies": { - "@react-native/codegen": "0.81.0-main" + "@react-native/codegen": "0.82.0-main" }, "devDependencies": { "@babel/core": "^7.25.2", From 81c2e798d7ad92c43bd7321918e56307d5458407 Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Fri, 18 Jul 2025 09:30:15 -0700 Subject: [PATCH 0188/1383] Fix CQS signal readability-braces-around-statements in xplat/js/react-native-github/packages (#52700) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52700 Pull Request resolved: https://github.com/facebook/react-native/pull/52699 Reviewed By: cipolleschi Differential Revision: D78549834 fbshipit-source-id: a15a9faed579a1e650eabb6e028a48f9307ad22b --- .../Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h | 3 ++- .../Libraries/Image/RCTUIImageViewAnimated.mm | 9 ++++++--- .../React/Views/RefreshControl/RCTRefreshControl.m | 6 ++++-- .../ReactCommon/cxxreact/tests/jsbigstring.cpp | 3 ++- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h index 481398ee14ef57..46c2782bf9bd4f 100644 --- a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h +++ b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h @@ -50,8 +50,9 @@ class LazyVector { const_reference at(size_type pos) const { #ifndef _LIBCPP_NO_EXCEPTIONS - if (!(pos < _size)) + if (!(pos < _size)) { throw std::out_of_range("out of range"); + } #else assert(pos < _size || !"out of range"); #endif diff --git a/packages/react-native/Libraries/Image/RCTUIImageViewAnimated.mm b/packages/react-native/Libraries/Image/RCTUIImageViewAnimated.mm index 670493e83a9211..5478e5753d4b17 100644 --- a/packages/react-native/Libraries/Image/RCTUIImageViewAnimated.mm +++ b/packages/react-native/Libraries/Image/RCTUIImageViewAnimated.mm @@ -25,11 +25,13 @@ static NSUInteger RCTDeviceFreeMemory(void) kern_return_t kern; kern = host_page_size(host_port, &page_size); - if (kern != KERN_SUCCESS) + if (kern != KERN_SUCCESS) { return 0; + } kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size); - if (kern != KERN_SUCCESS) + if (kern != KERN_SUCCESS) { return 0; + } return (vm_stat.free_count - vm_stat.speculative_count) * page_size; } @@ -278,8 +280,9 @@ - (void)displayDidRefresh:(CADisplayLink *)displayLink - (void)calculateMaxBufferCount { NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage); - if (bytes == 0) + if (bytes == 0) { bytes = 1024; + } NSUInteger max = 0; if (self.maxBufferSize > 0) { diff --git a/packages/react-native/React/Views/RefreshControl/RCTRefreshControl.m b/packages/react-native/React/Views/RefreshControl/RCTRefreshControl.m index 53bfd04703502d..7f7e5471ec6e44 100644 --- a/packages/react-native/React/Views/RefreshControl/RCTRefreshControl.m +++ b/packages/react-native/React/Views/RefreshControl/RCTRefreshControl.m @@ -71,8 +71,9 @@ - (void)didMoveToWindow - (void)beginRefreshingProgrammatically { - if (!_hasMovedToWindow) + if (!_hasMovedToWindow) { return; + } UInt64 beginRefreshingTimestamp = _currentRefreshingStateTimestamp; _refreshingProgrammatically = YES; @@ -108,8 +109,9 @@ - (void)beginRefreshingProgrammatically - (void)endRefreshingProgrammatically { - if (!_hasMovedToWindow) + if (!_hasMovedToWindow) { return; + } // The contentOffset of the scrollview MUST be greater than the contentInset before calling // endRefreshing otherwise the next pull to refresh will not work properly. UIScrollView *scrollView = self.scrollView; diff --git a/packages/react-native/ReactCommon/cxxreact/tests/jsbigstring.cpp b/packages/react-native/ReactCommon/cxxreact/tests/jsbigstring.cpp index 6bb9dda3b46311..02890b11190489 100644 --- a/packages/react-native/ReactCommon/cxxreact/tests/jsbigstring.cpp +++ b/packages/react-native/ReactCommon/cxxreact/tests/jsbigstring.cpp @@ -16,8 +16,9 @@ using namespace facebook::react; namespace { int tempFileFromString(std::string contents) { const char* tmpDir = getenv("TMPDIR"); - if (tmpDir == nullptr) + if (tmpDir == nullptr) { tmpDir = "/tmp"; + } std::string tmp{tmpDir}; tmp += "/temp.XXXXXX"; From 391a6b87a0df490207dacd1b08ee7f5b82a8bc68 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Fri, 18 Jul 2025 10:20:19 -0700 Subject: [PATCH 0189/1383] Rollout `preventShadowTreeCommitExhaustionWithLocking` in experimental (#52709) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52709 We want to make user for folks in OSS to try `preventShadowTreeCommitExhaustionWithLocking`. Therefore I'm updating the OSS release channel for this flag to experimental. Changelog: [Internal] [Changed] - Rollout `preventShadowTreeCommitExhaustionWithLocking` in experimental Reviewed By: rubennorte Differential Revision: D78558655 fbshipit-source-id: 02a9d216c7b2f8f7bdc1340213f82b70c5692dc7 --- ...ativeFeatureFlagsOverrides_RNOSS_Experimental_Android.kt | 4 ++-- .../ReactNativeFeatureFlagsOverridesOSSExperimental.h | 6 ++++-- .../scripts/featureflags/ReactNativeFeatureFlags.config.js | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsOverrides_RNOSS_Experimental_Android.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsOverrides_RNOSS_Experimental_Android.kt index 32dc0a1e2d0d41..ecacb9c45ef16c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsOverrides_RNOSS_Experimental_Android.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsOverrides_RNOSS_Experimental_Android.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<<93aab733661b558c1701b728c18b3d00>> */ /** @@ -23,5 +23,5 @@ public open class ReactNativeFeatureFlagsOverrides_RNOSS_Experimental_Android : // We could use JNI to get the defaults from C++, // but that is more expensive than just duplicating the defaults here. - + override fun preventShadowTreeCommitExhaustionWithLocking(): Boolean = true } diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h index 765468e4ee8977..a9e9a58c8005fb 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.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<<1de02178e1be302bb4b19501950b260a>> + * @generated SignedSource<<16c5fdf431579bbfd454a28c06f28c41>> */ /** @@ -27,7 +27,9 @@ class ReactNativeFeatureFlagsOverridesOSSExperimental : public ReactNativeFeatur public: ReactNativeFeatureFlagsOverridesOSSExperimental() = default; - + bool preventShadowTreeCommitExhaustionWithLocking() override { + return true; + } }; } // namespace facebook::react diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index 96c351da54fbf5..e23dafa744f392 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -545,7 +545,7 @@ const definitions: FeatureFlagDefinitions = { expectedReleaseValue: true, purpose: 'experimentation', }, - ossReleaseStage: 'none', + ossReleaseStage: 'experimental', }, releaseImageDataWhenConsumed: { defaultValue: false, From 36fed563c4ec0f73e681d1b5176aa580cd3df4c7 Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Fri, 18 Jul 2025 14:16:22 -0700 Subject: [PATCH 0190/1383] Use experimental VirtualView in FlatListVirtualColumn (#52689) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52689 Changelog: [Internal] - Add support for experimental VirtualView in polyfill Reviewed By: mdvacca Differential Revision: D78450011 fbshipit-source-id: cc30394eb1a008cc8c023db2aaf0a6a6ffcd16df --- .../com/facebook/react/views/scroll/VirtualViewContainer.kt | 2 +- .../virtual/viewexperimental/ReactVirtualViewExperimental.kt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt index fa12bc6c85e224..66bd3d167dfe1b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt @@ -115,7 +115,7 @@ private val IS_DEBUG_BUILD = ReactBuildConfig.DEBUG || ReactBuildConfig.IS_INTERNAL_BUILD || ReactBuildConfig.ENABLE_PERFETTO internal inline fun debugLog(subtag: String, block: () -> String = { "" }) { - if (IS_DEBUG_BUILD) { + if (IS_DEBUG_BUILD && ReactNativeFeatureFlags.enableVirtualViewDebugFeatures()) { FLog.d("$DEBUG_TAG:$subtag", block()) } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/viewexperimental/ReactVirtualViewExperimental.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/viewexperimental/ReactVirtualViewExperimental.kt index 42cca02c780c5f..0b819e4e47b902 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/viewexperimental/ReactVirtualViewExperimental.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/virtual/viewexperimental/ReactVirtualViewExperimental.kt @@ -15,6 +15,7 @@ import androidx.annotation.VisibleForTesting import com.facebook.common.logging.FLog import com.facebook.react.R import com.facebook.react.common.build.ReactBuildConfig +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags import com.facebook.react.uimanager.ReactRoot import com.facebook.react.views.scroll.VirtualView import com.facebook.react.views.scroll.VirtualViewContainer @@ -202,7 +203,7 @@ public class ReactVirtualViewExperimental(context: Context) : } internal inline fun debugLog(subtag: String, block: () -> String = { "" }) { - if (IS_DEBUG_BUILD) { + if (IS_DEBUG_BUILD && ReactNativeFeatureFlags.enableVirtualViewDebugFeatures()) { FLog.d("$DEBUG_TAG:$subtag", "${block()} [$id][$nativeId]") } } From 7ea0ef7a90e18f33cb4e15f673168cee1ab0b64b Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Fri, 18 Jul 2025 14:16:22 -0700 Subject: [PATCH 0191/1383] Implement windowFocus on ReactVirtualViewExperiment (#52690) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52690 Changelog: [Internal] - Add the window focus experiment to ReactVirtualViewExperimental Reviewed By: yungsters Differential Revision: D78502991 fbshipit-source-id: 3e72561835925040e5b240e71734a088908957ed --- .../react/views/scroll/ReactScrollView.java | 3 ++ .../views/scroll/VirtualViewContainer.kt | 36 +++++++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) 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 a0a906f6c10493..fd5ec0e73dbd85 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 @@ -407,6 +407,9 @@ protected void onDetachedFromWindow() { if (mMaintainVisibleContentPositionHelper != null) { mMaintainVisibleContentPositionHelper.stop(); } + if (mVirtualViewContainerState != null) { + mVirtualViewContainerState.cleanup(); + } } @Override diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt index 66bd3d167dfe1b..0dae4459618458 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VirtualViewContainer.kt @@ -9,6 +9,7 @@ package com.facebook.react.views.scroll import android.graphics.Rect import android.view.ViewGroup +import android.view.ViewTreeObserver import com.facebook.common.logging.FLog import com.facebook.react.common.build.ReactBuildConfig import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags @@ -46,13 +47,34 @@ private fun rectsOverlap(rect1: Rect, rect2: Rect): Boolean { return true } -internal class VirtualViewContainerState(private val scrollView: ViewGroup) { +internal class VirtualViewContainerState { private val prerenderRatio: Double = ReactNativeFeatureFlags.virtualViewPrerenderRatio() + private val detectWindowFocus = ReactNativeFeatureFlags.enableVirtualViewWindowFocusDetection() + private val virtualViews: MutableSet = mutableSetOf() private val emptyRect: Rect = Rect() private val visibleRect: Rect = Rect() private val prerenderRect: Rect = Rect() + private val onWindowFocusChangeListener = + ViewTreeObserver.OnWindowFocusChangeListener { + debugLog("onWindowFocusChanged") + updateModes() + } + private val scrollView: ViewGroup + + constructor(scrollView: ViewGroup) { + this.scrollView = scrollView + if (detectWindowFocus) { + scrollView.viewTreeObserver.addOnWindowFocusChangeListener(onWindowFocusChangeListener) + } + } + + public fun cleanup() { + if (detectWindowFocus) { + scrollView.viewTreeObserver.removeOnWindowFocusChangeListener(onWindowFocusChangeListener) + } + } public fun onChange(virtualView: VirtualView) { if (virtualViews.add(virtualView)) { @@ -72,7 +94,7 @@ internal class VirtualViewContainerState(private val scrollView: ViewGroup) { // Called on ScrollView onLayout or onScroll public fun updateState() { - debugLog("VirtualViewContainer.updateState") + debugLog("updateState") updateModes() } @@ -92,8 +114,16 @@ internal class VirtualViewContainerState(private val scrollView: ViewGroup) { when { rect.isEmpty -> {} rectsOverlap(rect, visibleRect) -> { - mode = VirtualViewMode.Visible thresholdRect = visibleRect + if (detectWindowFocus) { + if (scrollView.hasWindowFocus()) { + mode = VirtualViewMode.Visible + } else { + mode = VirtualViewMode.Prerender + } + } else { + mode = VirtualViewMode.Visible + } } rectsOverlap(rect, prerenderRect) -> { mode = VirtualViewMode.Prerender From ea394f6229e77f88efef88d3e94f9a16cf0f161f Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Fri, 18 Jul 2025 15:19:58 -0700 Subject: [PATCH 0192/1383] Fix incorrect hit testing on text when layout reused (#52692) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52692 D77341994 added a global cache for Facsimile layouts, where we will reuse an existing `android.text.Layout`, and `Spannable`, if one already existed for a same AttributedString, under same layout constraints. An error here, is that we consider a layout reusable, even when shadow views are different, which means there may be different react tags in the underlying AttributedString. This leaks into the layout itself, and means that if a layout is reused, we can hit test against a stale/incorrect react tag. The solution to allow reuse here, is to avoid embedding react tag directly into the `android.text.Layout` structure. Instead, we replace references to react tags, with a fragment index, and embed the list of fragment indices in each PreparedLayout. We can hide this "cleverness" within the boundary of `TextLayoutManager`, such that an invalid `PreparedLayout` is never allowed to escape. Changelog: [Internal] Reviewed By: joevilches Differential Revision: D78516079 fbshipit-source-id: 2d9fe9d80f60e6d7e7e40080a0817a08b51c3153 --- .../react/fabric/FabricUIManager.java | 12 ++++ .../react/views/text/PreparedLayout.kt | 3 +- .../views/text/PreparedLayoutTextView.kt | 7 +- .../react/views/text/TextLayoutManager.kt | 64 ++++++++++++++----- .../internal/span/ReactFragmentIndexSpan.kt | 14 ++++ .../views/text/internal/span/ReactLinkSpan.kt | 47 ++++++++++++++ .../textlayoutmanager/TextLayoutManager.cpp | 44 ++++++++++++- .../react/utils/SimpleThreadSafeCache.h | 53 ++++++++++----- 8 files changed, 204 insertions(+), 40 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactFragmentIndexSpan.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactLinkSpan.kt 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 6199a2ca654586..7c12222230feb6 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 @@ -675,6 +675,18 @@ public PreparedLayout prepareTextLayout( : null); } + @AnyThread + @ThreadConfined(ANY) + @UnstableReactNativeAPI + public PreparedLayout reusePreparedLayoutWithNewReactTags( + PreparedLayout preparedLayout, int[] reactTags) { + return new PreparedLayout( + preparedLayout.getLayout(), + preparedLayout.getMaximumNumberOfLines(), + preparedLayout.getVerticalOffset(), + reactTags); + } + @AnyThread @ThreadConfined(ANY) @UnstableReactNativeAPI diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayout.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayout.kt index 1f76f2e7d36fdf..19195d96dcd1db 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayout.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayout.kt @@ -18,5 +18,6 @@ import com.facebook.proguard.annotations.DoNotStrip internal class PreparedLayout( val layout: Layout, val maximumNumberOfLines: Int, - val verticalOffset: Float + val verticalOffset: Float, + val reactTags: IntArray, ) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt index b3c5aeacad4e40..d7b496ba997b46 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt @@ -27,7 +27,7 @@ import com.facebook.proguard.annotations.DoNotStrip import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.ReactCompoundView import com.facebook.react.uimanager.style.Overflow -import com.facebook.react.views.text.internal.span.ReactTagSpan +import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan import kotlin.collections.ArrayList import kotlin.math.roundToInt @@ -310,8 +310,9 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re override fun hasOverlappingRendering(): Boolean = false override fun reactTagForTouch(touchX: Float, touchY: Float): Int = - getSpanInCoords(touchX.roundToInt(), touchY.roundToInt(), ReactTagSpan::class.java)?.reactTag - ?: id + getSpanInCoords(touchX.roundToInt(), touchY.roundToInt(), ReactFragmentIndexSpan::class.java) + ?.fragmentIndex + ?.let { preparedLayout?.reactTags[it] } ?: id @RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) private object Api34Utils { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt index 5ed9b61154dc69..7f66d6b0123dac 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt @@ -42,6 +42,8 @@ import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan import com.facebook.react.views.text.internal.span.ReactBackgroundColorSpan import com.facebook.react.views.text.internal.span.ReactClickableSpan import com.facebook.react.views.text.internal.span.ReactForegroundColorSpan +import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan +import com.facebook.react.views.text.internal.span.ReactLinkSpan import com.facebook.react.views.text.internal.span.ReactOpacitySpan import com.facebook.react.views.text.internal.span.ReactStrikethroughSpan import com.facebook.react.views.text.internal.span.ReactTagSpan @@ -218,7 +220,8 @@ internal object TextLayoutManager { context: Context, fragments: MapBuffer, sb: SpannableStringBuilder, - ops: MutableList + ops: MutableList, + outputReactTags: IntArray? ) { for (i in 0 until fragments.count) { val fragment = fragments.getMapBuffer(i) @@ -249,7 +252,11 @@ internal object TextLayoutManager { (textAttributes.mAccessibilityRole == ReactAccessibilityDelegate.AccessibilityRole.LINK) if (roleIsLink) { - ops.add(SetSpanOperation(start, end, ReactClickableSpan(reactTag))) + if (ReactNativeFeatureFlags.enablePreparedTextLayout()) { + ops.add(SetSpanOperation(start, end, ReactLinkSpan(i))) + } else { + ops.add(SetSpanOperation(start, end, ReactClickableSpan(reactTag))) + } } if (textAttributes.mIsColorSet) { ops.add(SetSpanOperation(start, end, ReactForegroundColorSpan(textAttributes.mColor))) @@ -307,7 +314,14 @@ internal object TextLayoutManager { start, end, CustomLineHeightSpan(textAttributes.effectiveLineHeight))) } - ops.add(SetSpanOperation(start, end, ReactTagSpan(reactTag))) + if (ReactNativeFeatureFlags.enablePreparedTextLayout()) { + ops.add(SetSpanOperation(start, end, ReactFragmentIndexSpan(i))) + if (outputReactTags != null) { + outputReactTags[i] = reactTag + } + } else { + ops.add(SetSpanOperation(start, end, ReactTagSpan(reactTag))) + } } } } @@ -323,7 +337,8 @@ internal object TextLayoutManager { private fun buildSpannableFromFragmentsOptimized( context: Context, - fragments: MapBuffer + fragments: MapBuffer, + outputReactTags: IntArray? ): Spannable { val text = StringBuilder() val parsedFragments = ArrayList(fragments.count) @@ -363,7 +378,7 @@ internal object TextLayoutManager { val spannable = SpannableString(text) var start = 0 - for (fragment in parsedFragments) { + for ((i, fragment) in parsedFragments.withIndex()) { val end = start + fragment.length val spanFlags = if (start == 0) Spannable.SPAN_INCLUSIVE_INCLUSIVE else Spannable.SPAN_EXCLUSIVE_INCLUSIVE @@ -386,7 +401,11 @@ internal object TextLayoutManager { ReactAccessibilityDelegate.AccessibilityRole.LINK) if (roleIsLink) { - spannable.setSpan(ReactClickableSpan(fragment.reactTag), start, end, spanFlags) + if (ReactNativeFeatureFlags.enablePreparedTextLayout()) { + spannable.setSpan(ReactLinkSpan(i), start, end, spanFlags) + } else { + spannable.setSpan(ReactClickableSpan(fragment.reactTag), start, end, spanFlags) + } } if (fragment.props.isColorSet) { @@ -453,7 +472,14 @@ internal object TextLayoutManager { CustomLineHeightSpan(fragment.props.effectiveLineHeight), start, end, spanFlags) } - spannable.setSpan(ReactTagSpan(fragment.reactTag), start, end, spanFlags) + if (ReactNativeFeatureFlags.enablePreparedTextLayout()) { + spannable.setSpan(ReactFragmentIndexSpan(i), start, end, spanFlags) + if (outputReactTags != null) { + outputReactTags[i] = fragment.reactTag + } + } else { + spannable.setSpan(ReactTagSpan(fragment.reactTag), start, end, spanFlags) + } } start = end @@ -474,7 +500,10 @@ internal object TextLayoutManager { } else { text = createSpannableFromAttributedString( - context, attributedString, reactTextViewManagerCallback) + context, + attributedString.getMapBuffer(AS_KEY_FRAGMENTS), + reactTextViewManagerCallback, + null) } return text @@ -482,13 +511,12 @@ internal object TextLayoutManager { private fun createSpannableFromAttributedString( context: Context, - attributedString: MapBuffer, - reactTextViewManagerCallback: ReactTextViewManagerCallback? + fragments: MapBuffer, + reactTextViewManagerCallback: ReactTextViewManagerCallback?, + outputReactTags: IntArray? ): Spannable { if (ReactNativeFeatureFlags.enableAndroidTextMeasurementOptimizations()) { - val spannable = - buildSpannableFromFragmentsOptimized( - context, attributedString.getMapBuffer(AS_KEY_FRAGMENTS)) + val spannable = buildSpannableFromFragmentsOptimized(context, fragments, outputReactTags) reactTextViewManagerCallback?.onPostProcessSpannable(spannable) return spannable @@ -500,7 +528,7 @@ internal object TextLayoutManager { // a new spannable will be wiped out val ops: MutableList = ArrayList() - buildSpannableFromFragments(context, attributedString.getMapBuffer(AS_KEY_FRAGMENTS), sb, ops) + buildSpannableFromFragments(context, fragments, sb, ops, outputReactTags) // TODO T31905686: add support for inline Images // While setting the Spans on the final text, we also check whether any of them are images. @@ -756,7 +784,11 @@ internal object TextLayoutManager { heightYogaMeasureMode: YogaMeasureMode, reactTextViewManagerCallback: ReactTextViewManagerCallback? ): PreparedLayout { - val text = getOrCreateSpannableForText(context, attributedString, reactTextViewManagerCallback) + val fragments = attributedString.getMapBuffer(AS_KEY_FRAGMENTS) + val reactTags = IntArray(fragments.count) + val text = + createSpannableFromAttributedString( + context, fragments, reactTextViewManagerCallback, reactTags) val baseTextAttributes = TextAttributeProps.fromMapBuffer(attributedString.getMapBuffer(AS_KEY_BASE_ATTRIBUTES)) val layout = @@ -779,7 +811,7 @@ internal object TextLayoutManager { getVerticalOffset( layout, paragraphAttributes, height, heightYogaMeasureMode, maximumNumberOfLines) - return PreparedLayout(layout, maximumNumberOfLines, verticalOffset) + return PreparedLayout(layout, maximumNumberOfLines, verticalOffset, reactTags) } @JvmStatic diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactFragmentIndexSpan.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactFragmentIndexSpan.kt new file mode 100644 index 00000000000000..203a4d9867076e --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactFragmentIndexSpan.kt @@ -0,0 +1,14 @@ +/* + * 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.views.text.internal.span + +/** + * Maps a section of the text to the index of the AttributedString fragment originally used to + * create it. + */ +internal class ReactFragmentIndexSpan(val fragmentIndex: Int) : ReactSpan diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactLinkSpan.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactLinkSpan.kt new file mode 100644 index 00000000000000..e25d48f8a975b4 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactLinkSpan.kt @@ -0,0 +1,47 @@ +/* + * 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.views.text.internal.span + +import android.text.TextPaint +import android.text.style.ClickableSpan +import android.view.View +import com.facebook.react.bridge.ReactContext +import com.facebook.react.uimanager.UIManagerHelper +import com.facebook.react.views.text.PreparedLayoutTextView +import com.facebook.react.views.text.TextLayoutManager +import com.facebook.react.views.view.ViewGroupClickEvent + +/** + * This class is used in [TextLayoutManager] to linkify and style a span of text with + * accessibilityRole="link". This is needed to make nested Text components accessible. + * + * For example, if your React component looks like this: + * ```js + * + * Some text with + * a link + * in the middle. + * + * ``` + */ +internal class ReactLinkSpan(val fragmentIndex: Int) : ClickableSpan(), ReactSpan { + override fun onClick(view: View) { + val context = view.context as ReactContext + val textView = view as? PreparedLayoutTextView ?: return + val preparedLayout = textView.preparedLayout ?: return + val reactTag = preparedLayout.reactTags[fragmentIndex] + val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(context, reactTag) + eventDispatcher?.dispatchEvent( + ViewGroupClickEvent(UIManagerHelper.getSurfaceId(context), reactTag)) + } + + override fun updateDrawState(ds: TextPaint) { + // no super call so we don't change the link color or add an underline by default, as the + // superclass does. + } +} diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp index 9525394f99346b..dc618063babb6e 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp @@ -310,14 +310,19 @@ TextLayoutManager::PreparedLayout TextLayoutManager::prepareLayout( jfloat, jfloat)>("prepareTextLayout"); - return preparedTextCache_.get( + static auto reusePreparedLayoutWithNewReactTags = + jni::findClassStatic("com/facebook/react/fabric/FabricUIManager") + ->getMethod( + "reusePreparedLayoutWithNewReactTags"); + + const auto [key, preparedText] = preparedTextCache_.getWithKey( {.attributedString = attributedString, .paragraphAttributes = paragraphAttributes, .layoutConstraints = layoutConstraints}, - [&] { + [&]() { const auto& fabricUIManager = contextContainer_->at>("FabricUIManager"); - auto attributedStringMB = JReadableMapBuffer::createWithContents( toMapBuffer(attributedString)); auto paragraphAttributesMB = JReadableMapBuffer::createWithContents( @@ -336,6 +341,39 @@ TextLayoutManager::PreparedLayout TextLayoutManager::prepareLayout( minimumSize.height, maximumSize.height))}; }); + + // PreparedTextCacheKey allows equality of layouts which are the same + // display-wise, but ShadowView fragments (and thus react tags) may have + // changed. + const auto& fragments = attributedString.getFragments(); + const auto& cacheKeyFragments = key->attributedString.getFragments(); + bool needsNewReactTags = [&] { + for (size_t i = 0; i < fragments.size(); i++) { + if (fragments[i].parentShadowView.tag != + cacheKeyFragments[i].parentShadowView.tag) { + return true; + } + } + return false; + }(); + + if (needsNewReactTags) { + std::vector reactTags(fragments.size()); + for (size_t i = 0; i < reactTags.size(); i++) { + reactTags[i] = fragments[i].parentShadowView.tag; + } + + auto javaReactTags = jni::JArrayInt::newArray(fragments.size()); + javaReactTags->setRegion( + 0, static_cast(reactTags.size()), reactTags.data()); + + const auto& fabricUIManager = + contextContainer_->at>("FabricUIManager"); + return PreparedLayout{jni::make_global(reusePreparedLayoutWithNewReactTags( + fabricUIManager, preparedText->get(), javaReactTags.get()))}; + } else { + return PreparedLayout{*preparedText}; + } } TextMeasurement TextLayoutManager::measurePreparedLayout( diff --git a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h index 3dc71ac281071c..0ed2f8589ab540 100644 --- a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h +++ b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h @@ -38,24 +38,20 @@ class SimpleThreadSafeCache { */ ValueT get(const KeyT& key, CacheGeneratorFunction auto generator) const { - std::lock_guard lock(mutex_); - - if (auto it = map_.find(key); it != map_.end()) { - // Move accessed item to front of list - list_.splice(list_.begin(), list_, it->second); - return it->second->second; - } + return getMapIterator(key, std::move(generator))->second->second; + } - auto value = generator(); - // Add new value to front of list and map - list_.emplace_front(key, value); - map_[key] = list_.begin(); - if (list_.size() > maxSize_) { - // Evict least recently used item (back of list) - map_.erase(list_.back().first); - list_.pop_back(); - } - return value; + /* + * Returns pointers to both the key and value from the map with a given key. + * If the value wasn't found in the cache, constructs the value using given + * generator function, stores it inside a cache and returns it. + * Can be called from any thread. + */ + std::pair getWithKey( + const KeyT& key, + CacheGeneratorFunction auto generator) const { + auto it = getMapIterator(key, std::move(generator)); + return std::make_pair(&it->first, &it->second->second); } /* @@ -79,6 +75,29 @@ class SimpleThreadSafeCache { using EntryT = std::pair; using iterator = typename std::list::iterator; + auto getMapIterator( + const KeyT& key, + CacheGeneratorFunction auto generator) const { + std::lock_guard lock(mutex_); + + if (auto it = map_.find(key); it != map_.end()) { + // Move accessed item to front of list + list_.splice(list_.begin(), list_, it->second); + return it; + } + + auto value = generator(); + // Add new value to front of list and map + list_.emplace_front(key, value); + auto [it, _] = map_.insert_or_assign(key, list_.begin()); + if (list_.size() > maxSize_) { + // Evict least recently used item (back of list) + map_.erase(list_.back().first); + list_.pop_back(); + } + return it; + } + size_t maxSize_; mutable std::mutex mutex_; mutable std::list list_; From b3d1d2a0a5915f740a7a26069d046f6a02dd0d88 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Fri, 18 Jul 2025 15:19:58 -0700 Subject: [PATCH 0193/1383] Disable Measure Cache When Also Using Prepared Text Layout (#52714) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52714 If we also have prepared text layout enabled, this cache will fill up with the last 1000 TextInput AttributedString, which isn't very useful. Let's assume we want to get rid of this cache, when we have the prepared layout cache as well. Changelog: [Internal] Reviewed By: rshest Differential Revision: D78534088 fbshipit-source-id: e9020ebfb7e1210f19e0b31f7423e7a9a90a89d1 --- .../react/renderer/textlayoutmanager/TextLayoutManager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp index dc618063babb6e..e89c19f93213c8 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp @@ -190,7 +190,8 @@ TextMeasurement TextLayoutManager::measure( }; auto measurement = - ReactNativeFeatureFlags::disableTextLayoutManagerCacheAndroid() + (ReactNativeFeatureFlags::disableTextLayoutManagerCacheAndroid() || + ReactNativeFeatureFlags::enablePreparedTextLayout()) ? measureText() : textMeasureCache_.get( {.attributedString = attributedString, From 1ceba3b470b8968b4ab0f31f6bbe0ab53db6d740 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Fri, 18 Jul 2025 17:51:14 -0700 Subject: [PATCH 0194/1383] Prepare react-native for prettier v3 (#52717) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52717 Prettier v3 no longer loads plugin implicitly. This diff first configures the hermes-parser plugin explicitly to prepare for v3 rollout. Changelog: [Internal] Reviewed By: pieterv Differential Revision: D78590158 fbshipit-source-id: dba06f5a823488b72a30ae5b58e37e172f4e736f --- .prettierrc | 36 ------------------------------------ .prettierrc.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 36 deletions(-) delete mode 100644 .prettierrc create mode 100644 .prettierrc.js diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index a3f4c89ec6a21b..00000000000000 --- a/.prettierrc +++ /dev/null @@ -1,36 +0,0 @@ -{ - "arrowParens": "avoid", - "bracketSameLine": true, - "bracketSpacing": false, - "requirePragma": true, - "singleQuote": true, - "trailingComma": "all", - "endOfLine": "lf", - "overrides": [ - { - "files": ["*.code-workspace"], - "options": { - "parser": "json" - } - }, - { - "files": [ - "*.js", - "*.js.flow" - ], - "options": { - "parser": "hermes" - } - }, - { - "files": [ - "**/__docs__/*.md" - ], - "options": { - "parser": "markdown", - "proseWrap": "always", - "requirePragma": false - } - } - ] -} diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000000000..0709f7c2ed1b7e --- /dev/null +++ b/.prettierrc.js @@ -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. + * + * @format + */ + +module.exports = { + arrowParens: 'avoid', + bracketSameLine: true, + bracketSpacing: false, + requirePragma: true, + singleQuote: true, + trailingComma: 'all', + endOfLine: 'lf', + plugins: [ + // Using module.parent and createRequire hack to simulate prettier v2 plugin resolution behavior. + // The hack allows us to resolve the plugin from the install location of prettier. + (module.parent + ? require('module').createRequire(module.parent.id) + : require + ).resolve('prettier-plugin-hermes-parser'), + ], + overrides: [ + { + files: ['*.code-workspace'], + options: { + parser: 'json', + }, + }, + { + files: ['*.js', '*.js.flow'], + options: { + parser: 'hermes', + }, + }, + { + files: ['**/__docs__/*.md'], + options: { + parser: 'markdown', + proseWrap: 'always', + requirePragma: false, + }, + }, + ], +}; From 34fb932f974b803f9f40431c73b88f7c33e0514e Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Fri, 18 Jul 2025 20:09:48 -0700 Subject: [PATCH 0195/1383] Use `allVariants()` when publishing ReactAndroid (#52719) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52719 This is really a nit. We don't need to list all the variants here, we can instead use `allVariants()` which we also use for hermes-engine, to publish every buildVariant from React Android. Changelog: [Internal] [Changed] - Reviewed By: alanleedev Differential Revision: D78561729 fbshipit-source-id: 35989051ce966ea07caf26a218eb43c1a2bcac2d --- packages/react-native/ReactAndroid/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index ff2b486c4b98c3..faa0d8816a1d4e 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -599,7 +599,7 @@ android { publishing { multipleVariants { withSourcesJar() - includeBuildTypeValues("debug", "release", "debugOptimized") + allVariants() } } From 087da29604717abbe622e0991c00fb1c73d415cd Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Fri, 18 Jul 2025 22:01:36 -0700 Subject: [PATCH 0196/1383] Add a TestCallInvoker (#52652) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52652 Changelog: [Internal] This adds a TestCallInvoker, suitable for unit testing Reviewed By: alanleedev Differential Revision: D78453676 fbshipit-source-id: d35e604fedc8656a0430956a811b4a7a07c8ee16 --- .../ReactCommon/tests/TestCallInvoker.h | 47 +++++++++++++++++++ .../react/bridging/tests/BridgingTest.h | 39 +++++---------- .../react/io/tests/NetworkingModuleTests.cpp | 20 ++------ 3 files changed, 63 insertions(+), 43 deletions(-) create mode 100644 packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h diff --git a/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h b/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h new file mode 100644 index 00000000000000..1c48519631b23d --- /dev/null +++ b/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h @@ -0,0 +1,47 @@ +/* + * 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 { + +class TestCallInvoker : public CallInvoker { + public: + explicit TestCallInvoker(std::shared_ptr runtime) + : runtime_(runtime) {} + + void invokeAsync(CallFunc&& func) noexcept override { + queue_.push_back(std::move(func)); + } + + void invokeSync(CallFunc&& func) override { + if (auto runtime = runtime_.lock()) { + func(*runtime); + } + } + + void flushQueue() { + if (auto runtime = runtime_.lock()) { + while (!queue_.empty()) { + queue_.front()(*runtime); + queue_.pop_front(); + runtime->drainMicrotasks(); // Run microtasks every cycle. + } + } + } + + private: + std::list queue_{}; + std::weak_ptr runtime_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h index 7fef3c9726a258..973fcad5b127ef 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h @@ -7,6 +7,7 @@ #pragma once +#include #include #include #include @@ -15,34 +16,24 @@ namespace facebook::react { -class TestCallInvoker : public CallInvoker { +class BridgingTest : public ::testing::Test { public: - void invokeAsync(CallFunc&& fn) noexcept override { - queue_.push_back(std::move(fn)); - } - - void invokeSync(CallFunc&&) override { - FAIL() << "JSCallInvoker does not support invokeSync()"; - } - - private: - friend class BridgingTest; + BridgingTest(BridgingTest& other) = delete; + BridgingTest& operator=(BridgingTest& other) = delete; + BridgingTest(BridgingTest&& other) = delete; + BridgingTest& operator=(BridgingTest&& other) = delete; - std::list queue_; -}; - -class BridgingTest : public ::testing::Test { protected: BridgingTest() - : invoker(std::make_shared()), - runtime(hermes::makeHermesRuntime( + : runtime(hermes::makeHermesRuntime( ::hermes::vm::RuntimeConfig::Builder() // Make promises work with Hermes microtasks. .withMicrotaskQueue(true) .build())), - rt(*runtime) {} + rt(*runtime), + invoker(std::make_shared(runtime)) {} - ~BridgingTest() { + ~BridgingTest() override { LongLivedObjectCollection::get(rt).clear(); } @@ -62,16 +53,12 @@ class BridgingTest : public ::testing::Test { } void flushQueue() { - while (!invoker->queue_.empty()) { - invoker->queue_.front()(*runtime); - invoker->queue_.pop_front(); - rt.drainMicrotasks(); // Run microtasks every cycle. - } + invoker->flushQueue(); } - std::shared_ptr invoker; - std::unique_ptr runtime; + std::shared_ptr runtime; jsi::Runtime& rt; + std::shared_ptr invoker; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp b/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp index 62b113d0989333..1ff920cb37f607 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp +++ b/packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp @@ -10,7 +10,7 @@ #include #endif -#include +#include #include #include #include @@ -21,25 +21,11 @@ namespace facebook::react { -class TestCallInvoker : public CallInvoker { - public: - void invokeAsync(CallFunc&& fn) noexcept override { - queue_.push_back(std::move(fn)); - } - - void invokeSync(CallFunc&& /*func*/) override { - FAIL() << "JSCallInvoker does not support invokeSync()"; - } - - private: - std::list queue_; -}; - class NetworkingModuleTests : public testing::Test { protected: void SetUp() override { rt_ = facebook::hermes::makeHermesRuntime(); - jsInvoker_ = std::make_shared(); + jsInvoker_ = std::make_shared(rt_); } static void verifyFormData( @@ -55,7 +41,7 @@ class NetworkingModuleTests : public testing::Test { } } - std::unique_ptr rt_; + std::shared_ptr rt_; std::shared_ptr jsInvoker_; }; From cb94e71845259ae7fa823eb4d21cde74fccd7435 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Fri, 18 Jul 2025 22:01:44 -0700 Subject: [PATCH 0197/1383] Delete old location of CallbackWrapper / LongLivedObject (#52649) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52649 Changelog: [Internal] RN-Windows has been updated > https://github.com/microsoft/react-native-windows/pull/14839 Reviewed By: rshest Differential Revision: D78312252 fbshipit-source-id: 8e5bd561c4624064cef72395c1179cbe28c247f6 --- .../nativemodule/core/ReactCommon/CallbackWrapper.h | 11 ----------- .../nativemodule/core/ReactCommon/LongLivedObject.h | 11 ----------- 2 files changed, 22 deletions(-) delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CallbackWrapper.h delete mode 100644 packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.h diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CallbackWrapper.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CallbackWrapper.h deleted file mode 100644 index 2c105d9c3f7238..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CallbackWrapper.h +++ /dev/null @@ -1,11 +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 - -// This header is left here for compatibility reasons. -#include diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.h deleted file mode 100644 index 1e1fa0cdb5d7c3..00000000000000 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.h +++ /dev/null @@ -1,11 +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 - -// This header is left here for compatibility reasons. -#include From ff85e2f6dd1949095fe20fa8e3100e5d6b685f44 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Fri, 18 Jul 2025 22:46:21 -0700 Subject: [PATCH 0198/1383] Add NativeCxxModuleExampleTests (#52653) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52653 Changelog: [Internal] This adds an example of Unit Testing a C++ Turbo Module with Google GTest and also adds necessary and useful utility classes for testings This is GTEST / C++ version of the same tests added in https://github.com/facebook/react-native/pull/52477 Reviewed By: alanleedev Differential Revision: D78250302 fbshipit-source-id: 278655779dd17550be9c579d84cc1f7b6e45230d --- .../core/tests/TurboModuleTestFixture.h | 31 ++++ .../NativeCxxModuleExample.podspec | 2 +- .../tests/NativeCxxModuleExampleTests.cpp | 166 ++++++++++++++++++ 3 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h create mode 100644 packages/rn-tester/NativeCxxModuleExample/tests/NativeCxxModuleExampleTests.cpp diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h new file mode 100644 index 00000000000000..c0039e3405906f --- /dev/null +++ b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h @@ -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. + */ + +#pragma once + +#include +#include +#include +#include + +namespace facebook::react { + +template +class TurboModuleTestFixture : public ::testing::Test { + public: + explicit TurboModuleTestFixture(Args... args) + : runtime_(facebook::hermes::makeHermesRuntime()), + jsInvoker_(std::make_shared(runtime_)), + module_(std::make_shared(jsInvoker_, std::forward(args)...)) {} + + protected: + std::shared_ptr runtime_{}; + std::shared_ptr jsInvoker_{}; + std::shared_ptr module_; +}; + +} // namespace facebook::react diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.podspec b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.podspec index 73162939e40daf..f8957da75cb570 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.podspec +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.compiler_flags = '-Wno-nullability-completeness' s.author = "Meta Platforms, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/react-native.git", :tag => "#{s.version}" } - s.source_files = "**/*.{h,cpp}" + s.source_files = "*.{h,cpp}" s.requires_arc = true s.pod_target_xcconfig = { "USE_HEADERMAP" => "YES", diff --git a/packages/rn-tester/NativeCxxModuleExample/tests/NativeCxxModuleExampleTests.cpp b/packages/rn-tester/NativeCxxModuleExample/tests/NativeCxxModuleExampleTests.cpp new file mode 100644 index 00000000000000..b182b529151c32 --- /dev/null +++ b/packages/rn-tester/NativeCxxModuleExample/tests/NativeCxxModuleExampleTests.cpp @@ -0,0 +1,166 @@ +/* + * 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 +#include +#include +#include +#include +#include + +namespace facebook::react { + +class NativeCxxModuleExampleTests + : public TurboModuleTestFixture {}; + +TEST_F(NativeCxxModuleExampleTests, GetArrayReturnsCorrectValues) { + std::vector> empty; + EXPECT_EQ(module_->getArray(*runtime_, empty), empty); + + std::vector> withNull = {std::nullopt}; + EXPECT_EQ(module_->getArray(*runtime_, withNull), withNull); + + std::vector> withObj = {ObjectStruct{1, "2"}}; + auto result = module_->getArray(*runtime_, withObj); + ASSERT_EQ(result.size(), 1); + EXPECT_EQ(result[0]->a, 1); + EXPECT_EQ(result[0]->b, "2"); +} + +TEST_F(NativeCxxModuleExampleTests, GetBoolReturnsCorrectValues) { + EXPECT_FALSE(module_->getBool(*runtime_, false)); + EXPECT_TRUE(module_->getBool(*runtime_, true)); +} + +TEST_F(NativeCxxModuleExampleTests, GetConstantsReturnsCorrectValues) { + auto constants = module_->getConstants(*runtime_); + EXPECT_TRUE(constants.const1); + EXPECT_EQ(constants.const2, 69); + EXPECT_EQ(constants.const3, "react-native"); +} + +TEST_F(NativeCxxModuleExampleTests, GetCustomEnumReturnsCorrectValue) { + EXPECT_EQ( + module_->getCustomEnum(*runtime_, CustomEnumInt::A), CustomEnumInt::A); +} + +TEST_F(NativeCxxModuleExampleTests, GetAndConsumeCustomHostObject) { + auto hostObj = module_->getCustomHostObject(*runtime_); + ASSERT_NE(hostObj, nullptr); + EXPECT_EQ(module_->consumeCustomHostObject(*runtime_, hostObj), "answer42"); +} + +TEST_F(NativeCxxModuleExampleTests, GetBinaryTreeNodeReturnsCorrectValues) { + auto result = module_->getBinaryTreeNode( + *runtime_, + BinaryTreeNode{ + .left = std::make_unique( + BinaryTreeNode{nullptr, 2, nullptr}), + .value = 4, + .right = std::make_unique( + BinaryTreeNode{nullptr, 6, nullptr})}); + ASSERT_NE(result.left, nullptr); + EXPECT_EQ(result.left->value, 2); + EXPECT_EQ(result.value, 4); + ASSERT_NE(result.right, nullptr); + EXPECT_EQ(result.right->value, 6); +} + +TEST_F(NativeCxxModuleExampleTests, GetGraphNodeReturnsCorrectValues) { + GraphNode input{ + .label = "root", + .neighbors = std::vector{ + GraphNode{.label = "child1"}, GraphNode{.label = "child2"}}}; + auto result = module_->getGraphNode(*runtime_, input); + EXPECT_EQ(result.label, "root"); + ASSERT_EQ(result.neighbors.value().size(), 4); + EXPECT_EQ(result.neighbors.value()[0].label, "child1"); + EXPECT_EQ(result.neighbors.value()[1].label, "child2"); + EXPECT_EQ(result.neighbors.value()[2].label, "top"); + EXPECT_EQ(result.neighbors.value()[3].label, "down"); +} + +TEST_F(NativeCxxModuleExampleTests, GetNumEnumReturnsCorrectValues) { + EXPECT_EQ( + module_->getNumEnum(*runtime_, NativeCxxModuleExampleEnumInt::IA), + NativeCxxModuleExampleEnumInt::IA); + EXPECT_EQ( + module_->getNumEnum(*runtime_, NativeCxxModuleExampleEnumInt::IB), + NativeCxxModuleExampleEnumInt::IB); +} + +TEST_F(NativeCxxModuleExampleTests, GetStrEnumReturnsCorrectValues) { + EXPECT_EQ( + module_->getStrEnum(*runtime_, NativeCxxModuleExampleEnumNone::NA), + NativeCxxModuleExampleEnumStr::SB); + EXPECT_EQ( + module_->getStrEnum(*runtime_, NativeCxxModuleExampleEnumNone::NB), + NativeCxxModuleExampleEnumStr::SB); +} + +TEST_F(NativeCxxModuleExampleTests, GetMapReturnsCorrectValues) { + std::map> input = { + {"a", 0}, {"b", std::nullopt}, {"c", 3}}; + auto result = module_->getMap(*runtime_, input); + EXPECT_EQ(result["a"], 0); + EXPECT_EQ(result["b"], std::nullopt); + EXPECT_EQ(result["c"], 3); +} + +TEST_F(NativeCxxModuleExampleTests, GetNumberReturnsCorrectValues) { + EXPECT_EQ(module_->getNumber(*runtime_, 0), 0); + EXPECT_EQ(module_->getNumber(*runtime_, pow(2, 53)), pow(2, 53)); +} + +TEST_F(NativeCxxModuleExampleTests, GetObjectReturnsCorrectValues) { + ObjectStruct input1{2, "two"}; + auto result1 = module_->getObject(*runtime_, input1); + EXPECT_EQ(result1.a, 2); + EXPECT_EQ(result1.b, "two"); + ObjectStruct input2{4, "four", "seven"}; + auto result2 = module_->getObject(*runtime_, input2); + EXPECT_EQ(result2.a, 4); + EXPECT_EQ(result2.b, "four"); + EXPECT_EQ(result2.c, "seven"); +} + +TEST_F(NativeCxxModuleExampleTests, GetSetReturnsCorrectValues) { + std::set input = {1, 2, 3, 3, 3}; + auto result = module_->getSet(*runtime_, input); + EXPECT_EQ(result.size(), 3); + EXPECT_TRUE(result.count(1)); + EXPECT_TRUE(result.count(2)); + EXPECT_TRUE(result.count(3)); +} + +TEST_F(NativeCxxModuleExampleTests, GetStringReturnsCorrectValues) { + EXPECT_EQ(module_->getString(*runtime_, ""), ""); + EXPECT_EQ(module_->getString(*runtime_, "string"), "string"); +} + +TEST_F(NativeCxxModuleExampleTests, GetValueReturnsCorrectValues) { + ObjectStruct z{4, "four", "seven"}; + auto result = module_->getValue(*runtime_, 23, "forty-two", z); + EXPECT_EQ(result.x, 23); + EXPECT_EQ(result.y, "forty-two"); + EXPECT_EQ(result.z.a, 4); + EXPECT_EQ(result.z.b, "four"); + EXPECT_EQ(result.z.c, "seven"); +} + +TEST_F( + NativeCxxModuleExampleTests, + GetWithWithOptionalArgsReturnsCorrectValues) { + EXPECT_EQ( + module_->getWithWithOptionalArgs(*runtime_, std::nullopt), std::nullopt); + EXPECT_EQ(module_->getWithWithOptionalArgs(*runtime_, true), true); + EXPECT_EQ(module_->getWithWithOptionalArgs(*runtime_, false), false); +} + +} // namespace facebook::react From 2534aeaddb0490b69dfaba6b8d316616c7e10a9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateo=20Guzm=C3=A1n?= Date: Sat, 19 Jul 2025 06:22:25 -0700 Subject: [PATCH 0199/1383] Migrate `Arguments` to Kotlin (#52457) Summary: Migrate com.facebook.react.bridge.Arguments to Kotlin. ## Changelog: [Android][Changed] - Migrated com.facebook.react.bridge.Arguments to Kotlin. Pull Request resolved: https://github.com/facebook/react-native/pull/52457 Test Plan: ```bash yarn test-android yarn android ``` Reviewed By: javache Differential Revision: D78353290 Pulled By: cortinico fbshipit-source-id: 3d42b44c00a60d34264cb1093991315f5e3c444e --- .../ReactAndroid/api/ReactAndroid.api | 29 +- .../com/facebook/react/bridge/Arguments.java | 423 ------------------ .../com/facebook/react/bridge/Arguments.kt | 356 +++++++++++++++ .../com/facebook/react/bridge/CallbackImpl.kt | 3 +- .../facebook/react/bridge/CxxCallbackImpl.kt | 2 +- .../react/runtime/BridgelessReactContext.kt | 6 +- .../virtual/view/ReactVirtualViewTest.kt | 9 +- .../testutils/shadows/ShadowArguments.kt | 21 +- 8 files changed, 391 insertions(+), 458 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index e6b3b5c3e9822b..12c6f291ff3ac6 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -531,20 +531,21 @@ public abstract interface class com/facebook/react/bridge/ActivityEventListener public fun onUserLeaveHint (Landroid/app/Activity;)V } -public class com/facebook/react/bridge/Arguments { - public fun ()V - public static fun createArray ()Lcom/facebook/react/bridge/WritableArray; - public static fun createMap ()Lcom/facebook/react/bridge/WritableMap; - public static fun fromArray (Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableArray; - public static fun fromBundle (Landroid/os/Bundle;)Lcom/facebook/react/bridge/WritableMap; - public static fun fromJavaArgs ([Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableNativeArray; - public static fun fromList (Ljava/util/List;)Lcom/facebook/react/bridge/WritableArray; - public static fun makeNativeArray (Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableNativeArray; - public static fun makeNativeArray (Ljava/util/List;)Lcom/facebook/react/bridge/WritableNativeArray; - public static fun makeNativeMap (Landroid/os/Bundle;)Lcom/facebook/react/bridge/WritableNativeMap; - public static fun makeNativeMap (Ljava/util/Map;)Lcom/facebook/react/bridge/WritableNativeMap; - public static fun toBundle (Lcom/facebook/react/bridge/ReadableMap;)Landroid/os/Bundle; - public static fun toList (Lcom/facebook/react/bridge/ReadableArray;)Ljava/util/ArrayList; +public final class com/facebook/react/bridge/Arguments { + public static final field INSTANCE Lcom/facebook/react/bridge/Arguments; + public static final fun createArray ()Lcom/facebook/react/bridge/WritableArray; + public static final fun createMap ()Lcom/facebook/react/bridge/WritableMap; + public static final fun fromArray (Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableArray; + public static final fun fromBundle (Landroid/os/Bundle;)Lcom/facebook/react/bridge/WritableMap; + public static final fun fromJavaArgs (Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableNativeArray; + public static final fun fromJavaArgs ([Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableNativeArray; + public static final fun fromList (Ljava/util/List;)Lcom/facebook/react/bridge/WritableArray; + public static final fun makeNativeArray (Ljava/lang/Object;)Lcom/facebook/react/bridge/WritableNativeArray; + public static final fun makeNativeArray (Ljava/util/List;)Lcom/facebook/react/bridge/WritableNativeArray; + public static final fun makeNativeMap (Landroid/os/Bundle;)Lcom/facebook/react/bridge/WritableNativeMap; + public static final fun makeNativeMap (Ljava/util/Map;)Lcom/facebook/react/bridge/WritableNativeMap; + public static final fun toBundle (Lcom/facebook/react/bridge/ReadableMap;)Landroid/os/Bundle; + public static final fun toList (Lcom/facebook/react/bridge/ReadableArray;)Ljava/util/ArrayList; } public final class com/facebook/react/bridge/AssertionException : java/lang/RuntimeException { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java deleted file mode 100644 index 58ee1ed91c85a5..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java +++ /dev/null @@ -1,423 +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.bridge; - -import android.os.Bundle; -import android.os.Parcelable; -import androidx.annotation.Nullable; -import com.facebook.infer.annotation.Nullsafe; -import com.facebook.proguard.annotations.DoNotStrip; -import java.lang.reflect.Array; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -@Nullsafe(Nullsafe.Mode.LOCAL) -@DoNotStrip -public class Arguments { - private static @Nullable Object makeNativeObject(@Nullable Object object) { - if (object == null) { - return null; - } else if (object instanceof Float - || object instanceof Long - || object instanceof Byte - || object instanceof Short) { - return ((Number) object).doubleValue(); - } else if (object.getClass().isArray()) { - return makeNativeArray(object); - } else if (object instanceof List) { - return makeNativeArray((List) object); - } else if (object instanceof Map) { - return makeNativeMap((Map) object); - } else if (object instanceof Bundle) { - return makeNativeMap((Bundle) object); - } else if (object instanceof JavaOnlyMap) { - return makeNativeMap(((JavaOnlyMap) object).toHashMap()); - } else if (object instanceof JavaOnlyArray) { - return makeNativeArray(((JavaOnlyArray) object).toArrayList()); - } else { - // Boolean, Integer, Double, String, WritableNativeArray, WritableNativeMap - return object; - } - } - - /** - * This method converts a List into a NativeArray. The data types supported are boolean, int, - * float, double, and String. List, Map, and Bundle objects, as well as arrays, containing values - * of the above types and/or null, or any recursive arrangement of these, are also supported. The - * best way to think of this is a way to generate a Java representation of a json list, from Java - * types which have a natural representation in json. - */ - public static WritableNativeArray makeNativeArray(@Nullable List objects) { - WritableNativeArray nativeArray = new WritableNativeArray(); - if (objects == null) { - return nativeArray; - } - for (Object elem : objects) { - elem = makeNativeObject(elem); - if (elem == null) { - nativeArray.pushNull(); - } else if (elem instanceof Boolean) { - nativeArray.pushBoolean((Boolean) elem); - } else if (elem instanceof Integer) { - nativeArray.pushInt((Integer) elem); - } else if (elem instanceof Double) { - nativeArray.pushDouble((Double) elem); - } else if (elem instanceof String) { - nativeArray.pushString((String) elem); - } else if (elem instanceof WritableNativeArray) { - nativeArray.pushArray((WritableNativeArray) elem); - } else if (elem instanceof WritableNativeMap) { - nativeArray.pushMap((WritableNativeMap) elem); - } else { - throw new IllegalArgumentException("Could not convert " + elem.getClass()); - } - } - return nativeArray; - } - - /** - * This overload is like the above, but uses reflection to operate on any primitive or object - * type. - */ - public static WritableNativeArray makeNativeArray(final @Nullable Object objects) { - if (objects == null) { - return new WritableNativeArray(); - } - // No explicit check for objects's type here. If it's not an array, the - // Array methods will throw IllegalArgumentException. - return makeNativeArray( - new AbstractList() { - public int size() { - return Array.getLength(objects); - } - - public @Nullable Object get(int index) { - return Array.get(objects, index); - } - }); - } - - private static void addEntry(WritableNativeMap nativeMap, String key, @Nullable Object value) { - value = makeNativeObject(value); - if (value == null) { - nativeMap.putNull(key); - } else if (value instanceof Boolean) { - nativeMap.putBoolean(key, (Boolean) value); - } else if (value instanceof Integer) { - nativeMap.putInt(key, (Integer) value); - } else if (value instanceof Number) { - nativeMap.putDouble(key, ((Number) value).doubleValue()); - } else if (value instanceof String) { - nativeMap.putString(key, (String) value); - } else if (value instanceof WritableNativeArray) { - nativeMap.putArray(key, (WritableNativeArray) value); - } else if (value instanceof WritableNativeMap) { - nativeMap.putMap(key, (WritableNativeMap) value); - } else { - throw new IllegalArgumentException("Could not convert " + value.getClass()); - } - } - - /** - * This method converts a Map into a NativeMap. Value types are supported as with makeNativeArray. - * The best way to think of this is a way to generate a Java representation of a json object, from - * Java types which have a natural representation in json. - */ - @DoNotStrip - public static WritableNativeMap makeNativeMap(@Nullable Map objects) { - WritableNativeMap nativeMap = new WritableNativeMap(); - if (objects == null) { - return nativeMap; - } - for (Map.Entry entry : objects.entrySet()) { - addEntry(nativeMap, entry.getKey(), entry.getValue()); - } - return nativeMap; - } - - /** Like the above, but takes a Bundle instead of a Map. */ - @DoNotStrip - public static WritableNativeMap makeNativeMap(@Nullable Bundle bundle) { - WritableNativeMap nativeMap = new WritableNativeMap(); - if (bundle == null) { - return nativeMap; - } - for (String key : bundle.keySet()) { - addEntry(nativeMap, key, bundle.get(key)); - } - return nativeMap; - } - - /** This method should be used when you need to stub out creating NativeArrays in unit tests. */ - public static WritableArray createArray() { - return new WritableNativeArray(); - } - - /** This method should be used when you need to stub out creating NativeMaps in unit tests. */ - public static WritableMap createMap() { - return new WritableNativeMap(); - } - - public static WritableNativeArray fromJavaArgs(Object[] args) { - WritableNativeArray arguments = new WritableNativeArray(); - for (int i = 0; i < args.length; i++) { - Object argument = args[i]; - if (argument == null) { - arguments.pushNull(); - continue; - } - - Class argumentClass = argument.getClass(); - if (argumentClass == Boolean.class) { - arguments.pushBoolean(((Boolean) argument).booleanValue()); - } else if (argumentClass == Integer.class) { - arguments.pushDouble(((Integer) argument).doubleValue()); - } else if (argumentClass == Double.class) { - arguments.pushDouble(((Double) argument).doubleValue()); - } else if (argumentClass == Float.class) { - arguments.pushDouble(((Float) argument).doubleValue()); - } else if (argumentClass == String.class) { - arguments.pushString(argument.toString()); - } else if (argumentClass == WritableNativeMap.class) { - arguments.pushMap((WritableNativeMap) argument); - } else if (argumentClass == WritableNativeArray.class) { - arguments.pushArray((WritableNativeArray) argument); - } else { - throw new RuntimeException("Cannot convert argument of type " + argumentClass); - } - } - return arguments; - } - - /** - * Convert an array to a {@link WritableArray}. - * - * @param array the array to convert. Supported types are: {@code String[]}, {@code Bundle[]}, - * {@code int[]}, {@code float[]}, {@code double[]}, {@code boolean[]}. - * @return the converted {@link WritableArray} - * @throws IllegalArgumentException if the passed object is none of the above types - */ - public static WritableArray fromArray(Object array) { - WritableArray catalystArray = createArray(); - if (array instanceof String[]) { - for (String v : (String[]) array) { - catalystArray.pushString(v); - } - } else if (array instanceof Bundle[]) { - for (Bundle v : (Bundle[]) array) { - catalystArray.pushMap(fromBundle(v)); - } - } else if (array instanceof int[]) { - for (int v : (int[]) array) { - catalystArray.pushInt(v); - } - } else if (array instanceof float[]) { - for (float v : (float[]) array) { - catalystArray.pushDouble(v); - } - } else if (array instanceof double[]) { - for (double v : (double[]) array) { - catalystArray.pushDouble(v); - } - } else if (array instanceof boolean[]) { - for (boolean v : (boolean[]) array) { - catalystArray.pushBoolean(v); - } - } else if (array instanceof Parcelable[]) { - for (Parcelable v : (Parcelable[]) array) { - if (v instanceof Bundle) { - catalystArray.pushMap(fromBundle((Bundle) v)); - } else { - throw new IllegalArgumentException("Unexpected array member type " + v.getClass()); - } - } - } else { - throw new IllegalArgumentException("Unknown array type " + array.getClass()); - } - return catalystArray; - } - - /** - * Convert a {@link List} to a {@link WritableArray}. - * - * @param list the list to convert. Supported value types are: {@code null}, {@code String}, - * {@code Bundle}, {@code List}, {@code Number}, {@code Boolean}, and all array types - * supported in {@link #fromArray(Object)}. - * @return the converted {@link WritableArray} - * @throws IllegalArgumentException if one of the values from the passed list is none of the above - * types - */ - public static WritableArray fromList(List list) { - WritableArray catalystArray = createArray(); - for (Object obj : list) { - if (obj == null) { - catalystArray.pushNull(); - } else if (obj.getClass().isArray()) { - catalystArray.pushArray(fromArray(obj)); - } else if (obj instanceof Bundle) { - catalystArray.pushMap(fromBundle((Bundle) obj)); - } else if (obj instanceof List) { - catalystArray.pushArray(fromList((List) obj)); - } else if (obj instanceof String) { - catalystArray.pushString((String) obj); - } else if (obj instanceof Integer) { - catalystArray.pushInt((Integer) obj); - } else if (obj instanceof Number) { - catalystArray.pushDouble(((Number) obj).doubleValue()); - } else if (obj instanceof Boolean) { - catalystArray.pushBoolean((Boolean) obj); - } else { - throw new IllegalArgumentException("Unknown value type " + obj.getClass()); - } - } - return catalystArray; - } - - /** - * Convert a {@link Bundle} to a {@link WritableMap}. Supported key types in the bundle are: - * - *

- * - *

    - *
  • primitive types: int, float, double, boolean - *
  • arrays supported by {@link #fromArray(Object)} - *
  • lists supported by {@link #fromList(List)} - *
  • {@link Bundle} objects that are recursively converted to maps - *
- * - * @param bundle the {@link Bundle} to convert - * @return the converted {@link WritableMap} - * @throws IllegalArgumentException if there are keys of unsupported types - */ - public static WritableMap fromBundle(Bundle bundle) { - WritableMap map = createMap(); - for (String key : bundle.keySet()) { - Object value = bundle.get(key); - if (value == null) { - map.putNull(key); - } else if (value.getClass().isArray()) { - map.putArray(key, fromArray(value)); - } else if (value instanceof String) { - map.putString(key, (String) value); - } else if (value instanceof Number) { - if (value instanceof Integer) { - map.putInt(key, (Integer) value); - } else { - map.putDouble(key, ((Number) value).doubleValue()); - } - } else if (value instanceof Boolean) { - map.putBoolean(key, (Boolean) value); - } else if (value instanceof Bundle) { - map.putMap(key, fromBundle((Bundle) value)); - } else if (value instanceof List) { - map.putArray(key, fromList((List) value)); - } else { - throw new IllegalArgumentException("Could not convert " + value.getClass()); - } - } - return map; - } - - /** - * Convert a {@link WritableArray} to a {@link ArrayList}. - * - * @param readableArray the {@link WritableArray} to convert. - * @return the converted {@link ArrayList}. - */ - @Nullable - public static ArrayList toList(@Nullable ReadableArray readableArray) { - if (readableArray == null) { - return null; - } - - ArrayList list = new ArrayList(); - - for (int i = 0; i < readableArray.size(); i++) { - switch (readableArray.getType(i)) { - case Null: - list.add(null); - break; - case Boolean: - list.add(readableArray.getBoolean(i)); - break; - case Number: - double number = readableArray.getDouble(i); - if (number == Math.rint(number)) { - // Add as an integer - list.add((int) number); - } else { - // Add as a double - list.add(number); - } - break; - case String: - list.add(readableArray.getString(i)); - break; - case Map: - list.add(toBundle(readableArray.getMap(i))); - break; - case Array: - list.add(toList(readableArray.getArray(i))); - break; - default: - throw new IllegalArgumentException("Could not convert object in array."); - } - } - - return list; - } - - /** - * Convert a {@link WritableMap} to a {@link Bundle}. Note: Each array is converted to an {@link - * ArrayList}. - * - * @param readableMap the {@link WritableMap} to convert. - * @return the converted {@link Bundle}. - */ - @Nullable - public static Bundle toBundle(@Nullable ReadableMap readableMap) { - if (readableMap == null) { - return null; - } - - ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); - - Bundle bundle = new Bundle(); - while (iterator.hasNextKey()) { - String key = iterator.nextKey(); - ReadableType readableType = readableMap.getType(key); - switch (readableType) { - case Null: - bundle.putString(key, null); - break; - case Boolean: - bundle.putBoolean(key, readableMap.getBoolean(key)); - break; - case Number: - // Can be int or double. - bundle.putDouble(key, readableMap.getDouble(key)); - break; - case String: - bundle.putString(key, readableMap.getString(key)); - break; - case Map: - bundle.putBundle(key, toBundle(readableMap.getMap(key))); - break; - case Array: - bundle.putSerializable(key, toList(readableMap.getArray(key))); - break; - default: - throw new IllegalArgumentException("Could not convert object with key: " + key + "."); - } - } - - return bundle; - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.kt new file mode 100644 index 00000000000000..9dfdc6eac8e69b --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.kt @@ -0,0 +1,356 @@ +/* + * 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 android.os.Bundle +import android.os.Parcelable +import com.facebook.proguard.annotations.DoNotStrip +import java.util.AbstractList +import kotlin.math.round + +@DoNotStrip +public object Arguments { + @Suppress("UNCHECKED_CAST") + private fun makeNativeObject(value: Any?): Any? = + when { + value == null -> null + value is Float || value is Long || value is Byte || value is Short -> + (value as Number).toDouble() + value.javaClass.isArray -> makeNativeArray(value) + value is List<*> -> makeNativeArray(value) + value is Map<*, *> -> makeNativeMap(value as Map) + value is Bundle -> makeNativeMap(value) + value is JavaOnlyMap -> makeNativeMap(value.toHashMap()) + value is JavaOnlyArray -> makeNativeArray(value.toArrayList()) + else -> value // Boolean, Integer, Double, String, WritableNativeArray, WritableNativeMap + } + + /** + * This method converts a List into a NativeArray. The data types supported are boolean, int, + * float, double, and String. List, Map, and Bundle objects, as well as arrays, containing values + * of the above types and/or null, or any recursive arrangement of these, are also supported. The + * best way to think of this is a way to generate a Java representation of a json list, from Java + * types which have a natural representation in json. + */ + @JvmStatic + public fun makeNativeArray(objects: List<*>?): WritableNativeArray { + val nativeArray = WritableNativeArray() + if (objects == null) { + return nativeArray + } + for (elem in objects) { + when (val value = makeNativeObject(elem)) { + null -> nativeArray.pushNull() + is Boolean -> nativeArray.pushBoolean(value) + is Int -> nativeArray.pushInt(value) + is Double -> nativeArray.pushDouble(value) + is String -> nativeArray.pushString(value) + is WritableNativeArray -> nativeArray.pushArray(value) + is WritableNativeMap -> nativeArray.pushMap(value) + else -> throw IllegalArgumentException("Could not convert ${value.javaClass}") + } + } + return nativeArray + } + + /** + * This overload is like the above, but uses reflection to operate on any primitive or object + * type. + */ + @JvmStatic + public fun makeNativeArray(objects: Any?): WritableNativeArray { + if (objects == null) { + return WritableNativeArray() + } + // No explicit check for objects's type here. If it's not an array, the + // Array methods will throw IllegalArgumentException. + return makeNativeArray( + object : AbstractList() { + override val size: Int + get() = java.lang.reflect.Array.getLength(objects) + + override fun get(index: Int): Any? = java.lang.reflect.Array.get(objects, index) + }) + } + + private fun addEntry(nativeMap: WritableNativeMap, key: String, value: Any?) { + when (val nativeObjectValue = makeNativeObject(value)) { + null -> nativeMap.putNull(key) + is Boolean -> nativeMap.putBoolean(key, nativeObjectValue) + is Int -> nativeMap.putInt(key, nativeObjectValue) + is Number -> nativeMap.putDouble(key, nativeObjectValue.toDouble()) + is String -> nativeMap.putString(key, nativeObjectValue) + is WritableNativeArray -> nativeMap.putArray(key, nativeObjectValue) + is WritableNativeMap -> nativeMap.putMap(key, nativeObjectValue) + else -> throw IllegalArgumentException("Could not convert ${nativeObjectValue.javaClass}") + } + } + + /** + * This method converts a Map into a NativeMap. Value types are supported as with makeNativeArray. + * The best way to think of this is a way to generate a Java representation of a json object, from + * Java types which have a natural representation in json. + */ + @DoNotStrip + @JvmStatic + public fun makeNativeMap(objects: Map?): WritableNativeMap { + val nativeMap = WritableNativeMap() + if (objects == null) { + return nativeMap + } + for ((key, value) in objects) { + addEntry(nativeMap, key, value) + } + return nativeMap + } + + /** Like the above, but takes a Bundle instead of a Map. */ + @DoNotStrip + @JvmStatic + @Suppress("DEPRECATION") + public fun makeNativeMap(bundle: Bundle?): WritableNativeMap { + val nativeMap = WritableNativeMap() + if (bundle == null) { + return nativeMap + } + for (key in bundle.keySet()) { + addEntry(nativeMap, key, bundle[key]) + } + return nativeMap + } + + /** This method should be used when you need to stub out creating NativeArrays in unit tests. */ + @JvmStatic public fun createArray(): WritableArray = WritableNativeArray() + + /** This method should be used when you need to stub out creating NativeMaps in unit tests. */ + @JvmStatic public fun createMap(): WritableMap = WritableNativeMap() + + @Suppress("UNCHECKED_CAST") + @JvmStatic + @Deprecated( + "Use fromJavaArgs(Array) instead. This method is added only to retain compatibility with Java consumers.") + public fun fromJavaArgs(args: Any?): WritableNativeArray = fromJavaArgs(args as Array) + + @JvmStatic + public fun fromJavaArgs(args: Array): WritableNativeArray { + val arguments = WritableNativeArray() + for (i in args.indices) { + val argument = args[i] + when (val argumentClass = argument?.javaClass) { + null -> arguments.pushNull() + Boolean::class.java, + java.lang.Boolean::class.java -> arguments.pushBoolean(argument as Boolean) + Int::class.java, + java.lang.Integer::class.java -> arguments.pushDouble((argument as Number).toDouble()) + Double::class.java, + java.lang.Double::class.java -> arguments.pushDouble((argument as Double)) + Float::class.java -> arguments.pushDouble((argument as Float).toDouble()) + java.lang.Float::class.java -> arguments.pushDouble((argument as Float).toDouble()) + String::class.java -> arguments.pushString(argument.toString()) + WritableNativeMap::class.java -> arguments.pushMap(argument as WritableNativeMap) + WritableNativeArray::class.java -> arguments.pushArray(argument as WritableNativeArray) + else -> throw RuntimeException("Cannot convert argument of type $argumentClass") + } + } + return arguments + } + + /** + * Convert an array to a [WritableArray]. + * + * @param array the array to convert. Supported types are: `String[]`, `Bundle[]`, `int[]`, + * `float[]`, `double[]`, `boolean[]`. + * @return the converted [WritableArray] + * @throws IllegalArgumentException if the passed object is none of the above types + */ + @JvmStatic + @Suppress("UNCHECKED_CAST") + public fun fromArray(array: Any): WritableArray { + val catalystArray = createArray() + when { + array is Array<*> && array.isArrayOf() -> { + for (v in array as Array) { + catalystArray.pushString(v) + } + } + array is Array<*> && array.isArrayOf() -> { + for (v in array as Array) { + catalystArray.pushMap(fromBundle(v)) + } + } + array is IntArray -> { + for (v in array) { + catalystArray.pushInt(v) + } + } + array is FloatArray -> { + for (v in array) { + catalystArray.pushDouble(v.toDouble()) + } + } + array is DoubleArray -> { + for (v in array) { + catalystArray.pushDouble(v) + } + } + array is BooleanArray -> { + for (v in array) { + catalystArray.pushBoolean(v) + } + } + array is Array<*> && array.isArrayOf() -> { + for (v in array as Array) { + if (v is Bundle) { + catalystArray.pushMap(fromBundle(v)) + } else { + throw IllegalArgumentException("Unexpected array member type ${v.javaClass}") + } + } + } + else -> throw IllegalArgumentException("Unknown array type ${array.javaClass}") + } + return catalystArray + } + + /** + * Convert a [List] to a [WritableArray]. + * + * @param list the list to convert. Supported value types are: `null`, `String`, `Bundle`, `List`, + * `Number`, `Boolean`, and all array types supported in [.fromArray]. + * @return the converted [WritableArray] + * @throws IllegalArgumentException if one of the values from the passed list is none of the above + * types + */ + @JvmStatic + public fun fromList(list: List<*>): WritableArray { + val catalystArray = createArray() + for (obj in list) { + when { + obj == null -> catalystArray.pushNull() + obj.javaClass.isArray -> catalystArray.pushArray(fromArray(obj)) + obj is Bundle -> catalystArray.pushMap(fromBundle(obj)) + obj is List<*> -> catalystArray.pushArray(fromList(obj)) + obj is String -> catalystArray.pushString(obj) + obj is Int -> catalystArray.pushInt(obj) + obj is Number -> catalystArray.pushDouble(obj.toDouble()) + obj is Boolean -> catalystArray.pushBoolean(obj) + else -> throw IllegalArgumentException("Unknown value type ${obj.javaClass}") + } + } + return catalystArray + } + + /** + * Convert a [Bundle] to a [WritableMap]. Supported key types in the bundle are: + * * primitive types: int, float, double, boolean + * * arrays supported by [.fromArray] + * * lists supported by [.fromList] + * * [Bundle] objects that are recursively converted to maps + * + * @param bundle the [Bundle] to convert + * @return the converted [WritableMap] + * @throws IllegalArgumentException if there are keys of unsupported types + */ + @JvmStatic + @Suppress("DEPRECATION") + public fun fromBundle(bundle: Bundle): WritableMap { + val map = createMap() + for (key in bundle.keySet()) { + val value = bundle[key] + when { + value == null -> map.putNull(key) + value.javaClass.isArray -> map.putArray(key, fromArray(value)) + value is String -> map.putString(key, value) + value is Number -> { + if (value is Int) { + map.putInt(key, value) + } else { + map.putDouble(key, value.toDouble()) + } + } + value is Boolean -> map.putBoolean(key, value) + value is Bundle -> map.putMap(key, fromBundle(value)) + value is List<*> -> map.putArray(key, fromList(value)) + else -> throw IllegalArgumentException("Could not convert ${value.javaClass}") + } + } + return map + } + + /** + * Convert a [WritableArray] to a [ArrayList]. + * + * @param readableArray the [WritableArray] to convert. + * @return the converted [ArrayList]. + */ + @JvmStatic + @Suppress("REDUNDANT_ELSE_IN_WHEN") + public fun toList(readableArray: ReadableArray?): ArrayList? { + if (readableArray == null) { + return null + } + + val list: ArrayList = ArrayList() + + for (i in 0.. list.add(null) + ReadableType.Boolean -> list.add(readableArray.getBoolean(i)) + ReadableType.Number -> { + val number = readableArray.getDouble(i) + if (number == round(number)) { + // Add as an integer + list.add(number.toInt()) + } else { + // Add as a double + list.add(number) + } + } + ReadableType.String -> list.add(readableArray.getString(i)) + ReadableType.Map -> list.add(toBundle(readableArray.getMap(i))) + ReadableType.Array -> list.add(toList(readableArray.getArray(i))) + else -> throw IllegalArgumentException("Could not convert object in array.") + } + } + + return list + } + + /** + * Convert a [WritableMap] to a [Bundle]. Note: Each array is converted to an [ArrayList]. + * + * @param readableMap the [WritableMap] to convert. + * @return the converted [Bundle]. + */ + @JvmStatic + @Suppress("REDUNDANT_ELSE_IN_WHEN") + public fun toBundle(readableMap: ReadableMap?): Bundle? { + if (readableMap == null) { + return null + } + + val iterator = readableMap.keySetIterator() + val bundle = Bundle() + + while (iterator.hasNextKey()) { + val key = iterator.nextKey() + when (readableMap.getType(key)) { + ReadableType.Null -> bundle.putString(key, null) + ReadableType.Boolean -> bundle.putBoolean(key, readableMap.getBoolean(key)) + ReadableType.Number -> + bundle.putDouble(key, readableMap.getDouble(key)) // Can be int or double. + ReadableType.String -> bundle.putString(key, readableMap.getString(key)) + ReadableType.Map -> bundle.putBundle(key, toBundle(readableMap.getMap(key))) + ReadableType.Array -> bundle.putSerializable(key, toList(readableMap.getArray(key))) + else -> throw IllegalArgumentException("Could not convert object with key: $key.") + } + } + + return bundle + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.kt index e0641596d16ff9..ef1b67592d6fc5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.kt @@ -22,7 +22,8 @@ internal class CallbackImpl(private val jsInstance: JSInstance, private val call throw RuntimeException( "Illegal callback invocation from native module. This callback type only permits a single invocation from native code.") } - jsInstance.invokeCallback(callbackId, Arguments.fromJavaArgs(args)) + @Suppress("UNCHECKED_CAST") + jsInstance.invokeCallback(callbackId, Arguments.fromJavaArgs(args as Array)) invoked = true } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.kt index dbd8c004bc507d..8554580f1cb4f1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.kt @@ -15,7 +15,7 @@ import com.facebook.proguard.annotations.DoNotStrip public class CxxCallbackImpl @DoNotStrip private constructor() : HybridClassBase(), Callback { override fun invoke(vararg args: Any?) { - nativeInvoke(Arguments.fromJavaArgs(args)) + @Suppress("UNCHECKED_CAST") nativeInvoke(Arguments.fromJavaArgs(args as Array)) } private external fun nativeInvoke(arguments: NativeArray) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.kt index 70dc70a1563705..ad2caa13642174 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/BridgelessReactContext.kt @@ -21,7 +21,6 @@ import com.facebook.react.bridge.NativeArray import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.UIManager -import com.facebook.react.bridge.WritableNativeArray import com.facebook.react.common.annotations.FrameworkAPI import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.common.build.ReactBuildConfig @@ -105,9 +104,8 @@ internal class BridgelessReactContext(context: Context, private val reactHost: R private val reactHost: ReactHostImpl, private val jsModuleInterface: Class ) : InvocationHandler { - override fun invoke(proxy: Any, method: Method, args: Array?): Any? { - val jsArgs: NativeArray = - if (args != null) Arguments.fromJavaArgs(args) else WritableNativeArray() + override fun invoke(proxy: Any, method: Method, args: Array): Any? { + val jsArgs: NativeArray = Arguments.fromJavaArgs(args) reactHost.callFunctionOnModule( JavaScriptModuleRegistry.getJSModuleName(jsModuleInterface), method.name, jsArgs) return null diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt index 34f39ee251a766..75c6821e3aed1a 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/virtual/view/ReactVirtualViewTest.kt @@ -11,9 +11,6 @@ import android.app.Activity import android.content.Context import android.graphics.Rect import android.util.DisplayMetrics -import com.facebook.react.bridge.Arguments -import com.facebook.react.bridge.JavaOnlyMap -import com.facebook.react.bridge.WritableMap import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests import com.facebook.react.uimanager.DisplayMetricsHolder import com.facebook.react.uimanager.events.Event @@ -21,6 +18,7 @@ import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.views.scroll.ReactScrollView import com.facebook.react.views.virtual.VirtualViewMode import com.facebook.react.views.virtual.VirtualViewModeChangeEvent +import com.facebook.testutils.shadows.ShadowArguments import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test @@ -32,8 +30,10 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** Tests [ReactVirtualView] */ +@Config(shadows = [ShadowArguments::class]) @RunWith(RobolectricTestRunner::class) class ReactVirtualViewTest { @@ -45,9 +45,6 @@ class ReactVirtualViewTest { context = Robolectric.buildActivity(Activity::class.java).create().get() - val arguments = mockStatic(Arguments::class.java) - arguments.`when` { Arguments.createMap() }.thenAnswer { JavaOnlyMap() } - val displayMetricsHolder = mockStatic(DisplayMetricsHolder::class.java) displayMetricsHolder .`when` { DisplayMetricsHolder.getWindowDisplayMetrics() } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt index 7987af9ac76f30..6f6d1070651f7b 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArguments.kt @@ -18,15 +18,18 @@ import org.robolectric.annotation.Implements import org.robolectric.shadow.api.Shadow @Implements(Arguments::class) -object ShadowArguments { - @JvmStatic @Implementation fun createArray(): WritableArray = JavaOnlyArray() +class ShadowArguments { - @JvmStatic @Implementation fun createMap(): WritableMap = JavaOnlyMap() + companion object { + @JvmStatic @Implementation fun createArray(): WritableArray = JavaOnlyArray() - @JvmStatic - @Implementation - fun fromJavaArgs(args: Array): WritableNativeArray = - WritableNativeArray().apply { - (Shadow.extract(this) as ShadowNativeArray).backingArray = JavaOnlyArray.of(*args) - } + @JvmStatic @Implementation fun createMap(): WritableMap = JavaOnlyMap() + + @JvmStatic + @Implementation + fun fromJavaArgs(args: Array): WritableNativeArray = + WritableNativeArray().apply { + (Shadow.extract(this) as ShadowNativeArray).backingArray = JavaOnlyArray.of(*args) + } + } } From 690cb003539b1d854cd1171bfcea4e07cf8f7d81 Mon Sep 17 00:00:00 2001 From: Marco Wang Date: Sat, 19 Jul 2025 11:08:41 -0700 Subject: [PATCH 0200/1383] Deploy 0.276.0 to xplat (#52720) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52720 Changelog: [Internal] Reviewed By: SamChou19815 Differential Revision: D78605229 fbshipit-source-id: 59ae4a2f316cee8415f6ef2984ca74f906ae0377 --- .flowconfig | 2 +- package.json | 2 +- .../react-native/Libraries/Core/Timers/queueMicrotask.js | 1 + yarn.lock | 8 ++++---- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.flowconfig b/.flowconfig index 1faa6debeb1931..ef32dd1bf9e696 100644 --- a/.flowconfig +++ b/.flowconfig @@ -104,4 +104,4 @@ untyped-import untyped-type-import [version] -^0.275.0 +^0.276.0 diff --git a/package.json b/package.json index 43852e6b301e5c..f295639b20b9f3 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,7 @@ "eslint-plugin-redundant-undefined": "^0.4.0", "eslint-plugin-relay": "^1.8.3", "flow-api-translator": "0.29.1", - "flow-bin": "^0.275.0", + "flow-bin": "^0.276.0", "glob": "^7.1.1", "hermes-eslint": "0.29.1", "hermes-transform": "0.29.1", diff --git a/packages/react-native/Libraries/Core/Timers/queueMicrotask.js b/packages/react-native/Libraries/Core/Timers/queueMicrotask.js index 83621536ecf423..34741aa1f838b5 100644 --- a/packages/react-native/Libraries/Core/Timers/queueMicrotask.js +++ b/packages/react-native/Libraries/Core/Timers/queueMicrotask.js @@ -30,6 +30,7 @@ export default function queueMicrotask(callback: Function) { } // Try to reuse a lazily allocated resolved promise from closure. + // $FlowFixMe[constant-condition] (resolvedPromise || (resolvedPromise = Promise.resolve())) .then(callback) .catch(error => diff --git a/yarn.lock b/yarn.lock index 77b4343fdc5fed..9204f9675e166b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4880,10 +4880,10 @@ flow-api-translator@0.29.1: hermes-transform "0.29.1" typescript "5.3.2" -flow-bin@^0.275.0: - version "0.275.0" - resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.275.0.tgz#3da676f7c3d3ef8fc0c63a6cab8c4915206ec225" - integrity sha512-pKMBgZ4hZ3y45UWhJc2isG9lgFY8ARE7SuHlfUjcbpGRFQxryxJlXI9y4YZnIWgbhrVAzmUb931P0VJT4yrWjw== +flow-bin@^0.276.0: + version "0.276.0" + resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.276.0.tgz#0c4f4de9d3eed254e5f6d86b0c02df58a4354588" + integrity sha512-qcxqq2ZtUS7KqwRiGa3w/N/YppQuWj5vaKMH9KgLDv0QaxrUskv6iCNoTfpFg/crT0YjQk5hJ8ALdk8YVqnO0g== flow-enums-runtime@^0.0.6: version "0.0.6" From 8488eaecea85f170378b67aa92c3dbff11781ec7 Mon Sep 17 00:00:00 2001 From: generatedunixname89002005287564 Date: Sat, 19 Jul 2025 12:46:58 -0700 Subject: [PATCH 0201/1383] Fix CQS signal modernize-use-using in xplat/js/react-native-github/packages [A] [B] [A] (#52718) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52718 Reviewed By: dtolnay Differential Revision: D78562730 fbshipit-source-id: 24576557eb7a6ba8e655a92f1e7cfe027f99dac0 --- .../react-native/React/DevSupport/RCTInspectorNetworkHelper.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.mm b/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.mm index 538d9767e1d2f4..53e8fde774ecbe 100644 --- a/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.mm +++ b/packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.mm @@ -8,7 +8,7 @@ #import "RCTInspectorNetworkHelper.h" #import -typedef void (^ListenerBlock)(RCTInspectorNetworkListener *); +using ListenerBlock = void (^)(RCTInspectorNetworkListener *); @interface RCTInspectorNetworkHelper () @property (nonatomic, strong) NSURLSession *session; From 6d4ea946f848d65375845d4d7dd272b73ab392f0 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Sun, 20 Jul 2025 06:12:31 -0700 Subject: [PATCH 0202/1383] Address lint warnings (#52702) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52702 Quick pass over some of the main files in `jsinspector-modern` now that C++ lint warnings have become more prevalent / auto-fixable. Changelog: [Internal] Reviewed By: motiz88 Differential Revision: D78490415 fbshipit-source-id: 32debcf5f217e847d326498709d50f695902bb5c --- .../jsinspector-modern/ExecutionContext.h | 3 +-- .../ReactCommon/jsinspector-modern/HostAgent.cpp | 11 ++++++----- .../ReactCommon/jsinspector-modern/HostTarget.cpp | 15 ++++++--------- .../jsinspector-modern/InspectorInterfaces.cpp | 11 +++++------ .../jsinspector-modern/InspectorInterfaces.h | 2 +- .../jsinspector-modern/InstanceAgent.cpp | 4 ++-- .../jsinspector-modern/InstanceTarget.cpp | 2 +- .../jsinspector-modern/InstanceTarget.h | 2 -- 8 files changed, 22 insertions(+), 28 deletions(-) diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h index 2e23fba10e4dab..b8c099a9c3c989 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h @@ -9,7 +9,6 @@ #include "UniqueMonostate.h" -#include #include #include #include @@ -19,7 +18,7 @@ namespace facebook::react::jsinspector_modern { struct ExecutionContextDescription { int32_t id{}; - std::string origin{""}; + std::string origin; std::string name{""}; std::optional uniqueId; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp index eb6e490cccee80..1d9e5f70f63a62 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp @@ -36,8 +36,8 @@ namespace facebook::react::jsinspector_modern { class HostAgent::Impl final { public: explicit Impl( - HostAgent& hostAgent, - FrontendChannel frontendChannel, + HostAgent& /*hostAgent*/, + const FrontendChannel& frontendChannel, HostTargetController& targetController, HostTargetMetadata hostMetadata, SessionState& sessionState, @@ -126,11 +126,11 @@ class HostAgent::Impl final { else if (req.method == "Page.reload") { targetController_.getDelegate().onReload({ .ignoreCache = - req.params.isObject() && req.params.count("ignoreCache") + req.params.isObject() && (req.params.count("ignoreCache") != 0u) ? std::optional(req.params.at("ignoreCache").asBool()) : std::nullopt, .scriptToEvaluateOnLoad = req.params.isObject() && - req.params.count("scriptToEvaluateOnLoad") + (req.params.count("scriptToEvaluateOnLoad") != 0u) ? std::optional( req.params.at("scriptToEvaluateOnLoad").asString()) : std::nullopt, @@ -139,7 +139,8 @@ class HostAgent::Impl final { shouldSendOKResponse = true; isFinishedHandlingRequest = true; } else if (req.method == "Overlay.setPausedInDebuggerMessage") { - auto message = req.params.isObject() && req.params.count("message") + auto message = + req.params.isObject() && (req.params.count("message") != 0u) ? std::optional(req.params.at("message").asString()) : std::nullopt; if (!isPausedInDebuggerOverlayVisible_ && message.has_value()) { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp index 245a4742b15bbc..29b2a7608a4b16 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp @@ -45,13 +45,13 @@ class HostTargetSession { targetController, std::move(hostMetadata), state_, - executor) {} + std::move(executor)) {} /** * Called by CallbackLocalConnection to send a message to this Session's * Agent. */ - void operator()(std::string message) { + void operator()(const std::string& message) { cdp::PreparsedRequest request; // Messages may be invalid JSON, or have unexpected types. try { @@ -91,7 +91,7 @@ class HostTargetSession { * there's no current instance. */ void setCurrentInstance(InstanceTarget* instance) { - if (instance) { + if (instance != nullptr) { hostAgent_.setCurrentInstanceAgent( instance->createAgent(frontendChannel_, state_)); } else { @@ -148,7 +148,7 @@ std::shared_ptr HostTarget::create( HostTargetDelegate& delegate, VoidExecutor executor) { std::shared_ptr hostTarget{new HostTarget(delegate)}; - hostTarget->setExecutor(executor); + hostTarget->setExecutor(std::move(executor)); return hostTarget; } @@ -166,7 +166,7 @@ std::unique_ptr HostTarget::connect( session->setCurrentInstance(currentInstance_.get()); sessions_.insert(std::weak_ptr(session)); return std::make_unique( - [session](std::string message) { (*session)(message); }); + [session](const std::string& message) { (*session)(message); }); } HostTarget::~HostTarget() { @@ -228,10 +228,7 @@ void HostTargetController::incrementPauseOverlayCounter() { bool HostTargetController::decrementPauseOverlayCounter() { assert(pauseOverlayCounter_ > 0 && "Pause overlay counter underflow"); - if (--pauseOverlayCounter_ == 0) { - return false; - } - return true; + return --pauseOverlayCounter_ != 0; } namespace { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.cpp index 0c6ad1dd999f39..a2da293e112132 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.cpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include namespace facebook::react::jsinspector_modern { @@ -24,7 +22,7 @@ IRemoteConnection::~IRemoteConnection() {} IInspector::~IInspector() {} IPageStatusListener::~IPageStatusListener() {} -const folly::dynamic targetCapabilitiesToDynamic( +folly::dynamic targetCapabilitiesToDynamic( const InspectorTargetCapabilities& capabilities) { return folly::dynamic::object( "nativePageReloads", capabilities.nativePageReloads)( @@ -56,7 +54,7 @@ class InspectorImpl : public IInspector { public: Page( int id, - const std::string& title, + const std::string& description, const std::string& vm, ConnectFunc connectFunc, InspectorTargetCapabilities capabilities); @@ -87,7 +85,7 @@ InspectorImpl::Page::Page( description_(description), vm_(vm), connectFunc_(std::move(connectFunc)), - capabilities_(std::move(capabilities)) {} + capabilities_(capabilities) {} InspectorImpl::Page::operator InspectorPageDescription() const { return InspectorPageDescription{ @@ -124,7 +122,7 @@ void InspectorImpl::removePage(int pageId) { std::scoped_lock lock(mutex_); if (pages_.erase(pageId) != 0) { - for (auto listenerWeak : listeners_) { + for (auto& listenerWeak : listeners_) { if (auto listener = listenerWeak.lock()) { listener->onPageRemoved(pageId); } @@ -138,6 +136,7 @@ std::vector InspectorImpl::getPages() const { std::vector inspectorPages; // pages_ is a std::map keyed on an incremental id, so this is insertion // ordered. + inspectorPages.reserve(pages_.size()); for (auto& it : pages_) { inspectorPages.push_back(InspectorPageDescription(it.second)); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h index bebc76a50a8863..fb38b0acdf8eb8 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h @@ -39,7 +39,7 @@ struct InspectorTargetCapabilities { bool prefersFuseboxFrontend = false; }; -const folly::dynamic targetCapabilitiesToDynamic( +folly::dynamic targetCapabilitiesToDynamic( const InspectorTargetCapabilities& capabilities); struct InspectorPageDescription { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp index 7b2cd6c77345b7..493980ea874555 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp @@ -16,7 +16,7 @@ InstanceAgent::InstanceAgent( FrontendChannel frontendChannel, InstanceTarget& target, SessionState& sessionState) - : frontendChannel_(frontendChannel), + : frontendChannel_(std::move(frontendChannel)), target_(target), sessionState_(sessionState) { (void)target_; @@ -36,7 +36,7 @@ bool InstanceAgent::handleRequest(const cdp::PreparsedRequest& req) { void InstanceAgent::setCurrentRuntime(RuntimeTarget* runtimeTarget) { auto previousRuntimeAgent = std::move(runtimeAgent_); - if (runtimeTarget) { + if (runtimeTarget != nullptr) { runtimeAgent_ = runtimeTarget->createAgent(frontendChannel_, sessionState_); } else { runtimeAgent_.reset(); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp index c8df28bce10b60..53d898d4681706 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.cpp @@ -18,7 +18,7 @@ std::shared_ptr InstanceTarget::create( VoidExecutor executor) { std::shared_ptr instanceTarget{ new InstanceTarget(executionContextManager, delegate)}; - instanceTarget->setExecutor(executor); + instanceTarget->setExecutor(std::move(executor)); return instanceTarget; } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h index e9ec51b12db339..c1cdeb96f67105 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h @@ -16,9 +16,7 @@ #include #include -#include #include -#include namespace facebook::react::jsinspector_modern { From 794df48ad6a259022e66de1a38ff54b5ec67c3e4 Mon Sep 17 00:00:00 2001 From: Vitali Zaidman Date: Sun, 20 Jul 2025 22:39:52 -0700 Subject: [PATCH 0203/1383] re-write console stack trace frame urls to be relative to debugger (#52704) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52704 Stack traces for console calls are passed to the debugger when they are relative to device. (e.g. 10.0.2.2 for Android emulator) Changelog: [android][fixed] fix stack trace linkifying failing when using Android emulator and other situations where the device and debugger have different bundle urls Reviewed By: motiz88 Differential Revision: D78553183 fbshipit-source-id: 91d7e7ccc99d12ec7d06f4201237ecf557a46c4f --- .../InspectorProxyCdpRewritingHacks-test.js | 49 ++++++++++++++++++- .../src/inspector-proxy/Device.js | 17 +++++++ .../src/inspector-proxy/cdp-types/messages.js | 1 + .../src/inspector-proxy/cdp-types/protocol.js | 17 +++++++ 4 files changed, 83 insertions(+), 1 deletion(-) diff --git a/packages/dev-middleware/src/__tests__/InspectorProxyCdpRewritingHacks-test.js b/packages/dev-middleware/src/__tests__/InspectorProxyCdpRewritingHacks-test.js index d354d6117782d8..ff98117891c114 100644 --- a/packages/dev-middleware/src/__tests__/InspectorProxyCdpRewritingHacks-test.js +++ b/packages/dev-middleware/src/__tests__/InspectorProxyCdpRewritingHacks-test.js @@ -184,7 +184,7 @@ describe.each(['HTTP', 'HTTPS'])( describe.each(['10.0.2.2:8080', '[::1]', 'example.com:2000'])( '%s aliasing to and from localhost', sourceHost => { - test('in source map fetching during Debugger.scriptParsed', async () => { + test('Debugger.scriptParsed - in source map fetching', async () => { serverRef.app.use('/source-map', serveStaticJson({version: 3})); const {device, debugger_} = await createAndConnectTarget( serverRef, @@ -220,6 +220,53 @@ describe.each(['HTTP', 'HTTPS'])( } }); + test('Runtime.consoleAPICalled - in location resolutions', async () => { + const {device, debugger_} = await createAndConnectTarget( + serverRef, + autoCleanup.signal, + { + app: 'bar-app', + id: 'page1', + title: 'bar-title', + vm: 'bar-vm', + }, + { + deviceHostHeader: sourceHost, + }, + ); + try { + const consoleMessage = await sendFromTargetToDebugger( + device, + debugger_, + 'page1', + { + method: 'Runtime.consoleAPICalled', + params: { + stackTrace: { + callFrames: [ + { + url: `${protocol.toLowerCase()}://${sourceHost}/bundleFile:1:2`, + field2: 'aaa', + }, + { + url: `${protocol.toLowerCase()}://${sourceHost}/bundleFile:5:4`, + field3: 'bbb', + }, + ], + }, + }, + }, + ); + expect(consoleMessage.params.stackTrace.callFrames).toEqual([ + {url: `${serverRef.serverBaseUrl}/bundleFile:1:2`, field2: 'aaa'}, + {url: `${serverRef.serverBaseUrl}/bundleFile:5:4`, field3: 'bbb'}, + ]); + } finally { + device.close(); + debugger_.close(); + } + }); + test('in Debugger.setBreakpointByUrl', async () => { const {device, debugger_} = await createAndConnectTarget( serverRef, diff --git a/packages/dev-middleware/src/inspector-proxy/Device.js b/packages/dev-middleware/src/inspector-proxy/Device.js index 94dd6b69caafb4..2db127aefc2a16 100644 --- a/packages/dev-middleware/src/inspector-proxy/Device.js +++ b/packages/dev-middleware/src/inspector-proxy/Device.js @@ -844,6 +844,23 @@ export default class Device { this.#isLegacyPageReloading = false; } + + if (payload.method === 'Runtime.consoleAPICalled') { + const callFrames = payload.params?.stackTrace?.callFrames ?? []; + for (const callFrame of callFrames) { + if (callFrame.url) { + const parsedUrl = this.#tryParseHTTPURL(callFrame.url); + if (parsedUrl) { + // Rewrite device-relative URLs pointing to the server so that they're + // reachable from the frontend. + callFrame.url = this.#deviceRelativeUrlToDebuggerRelativeUrl( + parsedUrl, + debuggerInfo, + ).href; + } + } + } + } } /** diff --git a/packages/dev-middleware/src/inspector-proxy/cdp-types/messages.js b/packages/dev-middleware/src/inspector-proxy/cdp-types/messages.js index 5010668a09e5b9..b06c447b3b375c 100644 --- a/packages/dev-middleware/src/inspector-proxy/cdp-types/messages.js +++ b/packages/dev-middleware/src/inspector-proxy/cdp-types/messages.js @@ -48,6 +48,7 @@ export type CDPClientMessage = export type CDPServerMessage = | CDPEvent<'Debugger.scriptParsed'> + | CDPEvent<'Runtime.consoleAPICalled'> | CDPEvent<> | CDPResponse<'Debugger.getScriptSource'> | CDPResponse<>; diff --git a/packages/dev-middleware/src/inspector-proxy/cdp-types/protocol.js b/packages/dev-middleware/src/inspector-proxy/cdp-types/protocol.js index 7cb4e814459334..f16540f0879718 100644 --- a/packages/dev-middleware/src/inspector-proxy/cdp-types/protocol.js +++ b/packages/dev-middleware/src/inspector-proxy/cdp-types/protocol.js @@ -84,10 +84,27 @@ export interface Debugger { */ sourceMapURL: string, }; + + ConsoleAPICalled: { + args: Array<{type: string, value: string}>, + executionContextId: number, + stackTrace: { + timestamp: number, + type: string, + callFrames: Array<{ + columnNumber: number, + lineNumber: number, + functionName: string, + scriptId: string, + url: string, + }>, + }, + }; } export type Events = { 'Debugger.scriptParsed': Debugger['ScriptParsedEvent'], + 'Runtime.consoleAPICalled': Debugger['ConsoleAPICalled'], [method: string]: JSONSerializable, }; From a0a77f7476ed2bf4220d8ee0ff4e88f88b0b764f Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Sun, 20 Jul 2025 23:08:03 -0700 Subject: [PATCH 0204/1383] Make it explicit to specify HttpClientFactoryKey and WebSocketClientFactoryKey values (#52715) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52715 Changelog: [Internal] Right now we rely on compile / link time magic to detect the implementation of ``` WebSocketClientFactory getWebSocketClientFactory(); HttpClientFactory getHttpClientFactory(); ``` this actually works until it does not work anymore, see .e.g.: ``` ld.lld: error: undefined symbol: facebook::react::getHttpClientFactory() >>> referenced by ReactHost.cpp:111 (xplat/js/react-native-github/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp:111) >>> xplat/js/react-native-github/packages/react-native/ReactCxxPlatform/react/runtime/__runtimeAndroid__/__objects__/ReactHost.cpp.pic.o:(facebook::react::ReactHost::ReactHost(facebook::react::ReactInstanceConfig, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::function, std::__ndk1::function, std::__ndk1::allocator> const&, unsigned int)>, std::__ndk1::shared_ptr, std::__ndk1::vector (std::__ndk1::basic_string, std::__ndk1::allocator> const&, std::__ndk1::shared_ptr const&)>, std::__ndk1::allocator (std::__ndk1::basic_string, std::__ndk1::allocator> const&, std::__ndk1::shared_ptr const&)>>>, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::function)) ld.lld: error: undefined symbol: facebook::react::getWebSocketClientFactory() >>> referenced by ReactHost.cpp:117 (xplat/js/react-native-github/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp:117) >>> xplat/js/react-native-github/packages/react-native/ReactCxxPlatform/react/runtime/__runtimeAndroid__/__objects__/ReactHost.cpp.pic.o:(facebook::react::ReactHost::ReactHost(facebook::react::ReactInstanceConfig, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::function, std::__ndk1::function, std::__ndk1::allocator> const&, unsigned int)>, std::__ndk1::shared_ptr, std::__ndk1::vector (std::__ndk1::basic_string, std::__ndk1::allocator> const&, std::__ndk1::shared_ptr const&)>, std::__ndk1::allocator (std::__ndk1::basic_string, std::__ndk1::allocator> const&, std::__ndk1::shared_ptr const&)>>>, std::__ndk1::shared_ptr, std::__ndk1::shared_ptr, std::__ndk1::function)) clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` The change here makes it explicit and mandatory to set the specific implementations of these interfaces Reviewed By: lenaic Differential Revision: D78529932 fbshipit-source-id: f26876683433a58e078d6720f169702c563ed92b --- .../ReactCxxPlatform/react/http/IWebSocketClient.h | 1 - .../ReactCxxPlatform/react/runtime/ReactHost.cpp | 8 +++----- .../ReactCxxPlatform/react/runtime/ReactHost.h | 3 +-- .../tester/src/TesterAppDelegate.cpp | 12 ++++++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h b/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h index a2ec1b0859bb47..6af9b1efbefad5 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h @@ -10,7 +10,6 @@ #include #include #include -#include namespace facebook::react { diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp index 9b7003eca6a576..bcd8d15f8aedd5 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp @@ -79,7 +79,7 @@ ReactHost::ReactHost( std::shared_ptr logBoxSurfaceDelegate, std::shared_ptr animatedNodesManagerProvider, - ReactInstance::BindingsInstallFunc bindingsInstallFunc) noexcept + ReactInstance::BindingsInstallFunc bindingsInstallFunc) : reactInstanceConfig_(std::move(reactInstanceConfig)) { auto componentRegistryFactory = mountingManager->getComponentRegistryFactory(); @@ -107,14 +107,12 @@ ReactHost::ReactHost( if (!reactInstanceData_->contextContainer ->find(HttpClientFactoryKey) .has_value()) { - reactInstanceData_->contextContainer->insert( - HttpClientFactoryKey, getHttpClientFactory()); + throw std::runtime_error("No HttpClientFactory provided"); } if (!reactInstanceData_->contextContainer ->find(WebSocketClientFactoryKey) .has_value()) { - reactInstanceData_->contextContainer->insert( - WebSocketClientFactoryKey, getWebSocketClientFactory()); + throw std::runtime_error("No WebSocketClientFactory provided"); } createReactInstance(); } diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h index dcbc07a3947929..7ddf2f4f130635 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h @@ -52,8 +52,7 @@ class ReactHost { std::shared_ptr logBoxSurfaceDelegate = nullptr, std::shared_ptr animatedNodesManagerProvider = nullptr, - ReactInstance::BindingsInstallFunc bindingsInstallFunc = - nullptr) noexcept; + ReactInstance::BindingsInstallFunc bindingsInstallFunc = nullptr); ReactHost(const ReactHost&) = delete; ReactHost& operator=(const ReactHost&) = delete; ReactHost(ReactHost&&) noexcept = delete; diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp index a2610b4a38022f..00790ae98c289a 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp @@ -6,7 +6,12 @@ */ #include "TesterAppDelegate.h" +#include "NativeFantom.h" #include "platform/TesterTurboModuleManagerDelegate.h" +#include "stubs/StubClock.h" +#include "stubs/StubHttpClient.h" +#include "stubs/StubQueue.h" +#include "stubs/StubWebSocketClient.h" #include #include @@ -26,10 +31,6 @@ #include #include -#include "NativeFantom.h" -#include "stubs/StubClock.h" -#include "stubs/StubQueue.h" - namespace facebook::react { namespace { @@ -75,6 +76,9 @@ TesterAppDelegate::TesterAppDelegate( queue_ = queue; return queue; })); + contextContainer->insert(HttpClientFactoryKey, getHttpClientFactory()); + contextContainer->insert( + WebSocketClientFactoryKey, getWebSocketClientFactory()); runLoopObserverManager_ = std::make_shared(); From 1f6eb884bf6a67f9535d2bb5a7a5c279f34a32a5 Mon Sep 17 00:00:00 2001 From: Nick Lefever Date: Mon, 21 Jul 2025 05:02:18 -0700 Subject: [PATCH 0205/1383] Fix modal crash on create with initial props (#52729) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52729 The Modal view creation contains initial properties when using Props 2.0. This diff adds support for Modal view creations having initial properties by allowing the `updateProperties` fast path only if the dialog is already initialized. Without the change, the fast path gets called before the dialog could be initialized which leads to throwing an exception when the dialog is being checked to see if it is initialized. Changelog: [Internal] Reviewed By: sammy-SC Differential Revision: D78638902 fbshipit-source-id: 61ad007b82867fa8b35648e3d8c930ee0e86c80d --- .../com/facebook/react/views/modal/ReactModalHostView.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt index c711027d172bc2..1126b992da0dba 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt @@ -256,8 +256,13 @@ public class ReactModalHostView(context: ThemedReactContext) : if (createNewDialog) { dismiss() } else { - updateProperties() - return + // With Props 2.0 the view creation could include initial props. This means the dialog might + // still have to be created before the properties can be set. We only update properties if the + // dialog was already initialized. + dialog?.let { + updateProperties() + return + } } // Reset the flag since we are going to create a new dialog From 57b5d7bf6f69b112c1d64d365815f1edd666450b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateo=20Guzm=C3=A1n?= Date: Mon, 21 Jul 2025 05:12:22 -0700 Subject: [PATCH 0206/1383] Make `UIManagerModuleListener` internal (#52727) Summary: This class can be internalized. I've checked there are [no relevant OSS usages](https://github.com/search?type=code&q=NOT+is%3Afork+NOT+org%3Afacebook+NOT+repo%3Areact-native-tvos%2Freact-native-tvos+NOT+repo%3Anuagoz%2Freact-native+NOT+repo%3A2lambda123%2Freact-native+NOT+repo%3Abeanchips%2Ffacebookreactnative+NOT+repo%3AfabOnReact%2Freact-native-notes+NOT+user%3Ahuntie+NOT+user%3Acortinico+NOT+repo%3AMaxdev18%2Fpowersync_app+NOT+repo%3Acarter-0%2Finstagram-decompiled+NOT+repo%3Am0mosenpai%2Finstadamn+NOT+repo%3AA-Star100%2FA-Star100-AUG2-2024+NOT+repo%3Alclnrd%2Fdetox-scrollview-reproductible+NOT+repo%3ADionisisChytiris%2FWorldWiseTrivia_Main+NOT+repo%3Apast3l%2Fhi2+NOT+repo%3AoneDotpy%2FCaribouQuest+NOT+repo%3Abejayoharen%2Fdailytodo+NOT+repo%3Amolangning%2Freversing-discord+NOT+repo%3AScottPrzy%2Freact-native+NOT+repo%3Agabrieldonadel%2Freact-native-visionos+NOT+repo%3AGabriel2308%2FTestes-Soft+NOT+repo%3Adawnzs03%2FflakyBuild+NOT+repo%3Acga2351%2Fcode+NOT+repo%3Astreeg%2Ftcc+NOT+repo%3Asoftware-mansion-labs%2Freact-native-swiftui+NOT+repo%3Apkcsecurity%2Fdecompiled-lightbulb+com.facebook.react.uimanager.UIManagerModuleListener). ## Changelog: [INTERNAL] - Make com.facebook.react.uimanager.UIManagerModuleListener internal Pull Request resolved: https://github.com/facebook/react-native/pull/52727 Test Plan: ```bash yarn test-android yarn android ``` Reviewed By: cortinico Differential Revision: D78656919 Pulled By: rshest fbshipit-source-id: cc9756bdd1c9e702f26cd87493c6f291792b7526 --- packages/react-native/ReactAndroid/api/ReactAndroid.api | 4 ---- .../com/facebook/react/uimanager/UIManagerModuleListener.kt | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 12c6f291ff3ac6..9332a05ac231d2 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -4404,10 +4404,6 @@ public abstract interface class com/facebook/react/uimanager/UIManagerModule$Cus public abstract fun resolveCustomEventName (Ljava/lang/String;)Ljava/lang/String; } -public abstract interface class com/facebook/react/uimanager/UIManagerModuleListener { - public abstract fun willDispatchViewUpdates (Lcom/facebook/react/uimanager/UIManagerModule;)V -} - public class com/facebook/react/uimanager/UIViewOperationQueue { public static final field DEFAULT_MIN_TIME_LEFT_IN_FRAME_FOR_NONBATCHED_OPERATION_MS I public fun (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/react/uimanager/NativeViewHierarchyManager;I)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.kt index e94f7cb6bae520..7b8106235e34ca 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.kt @@ -13,10 +13,10 @@ import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel /** Listener used to hook into the UIManager update process. */ @Deprecated("Use UIManagerListener instead. This will be deleted in some future release.") @LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR) -public interface UIManagerModuleListener { +internal interface UIManagerModuleListener { /** * Called right before view updates are dispatched at the end of a batch. This is useful if a * module needs to add UIBlocks to the queue before it is flushed. */ - public fun willDispatchViewUpdates(uiManager: UIManagerModule) + fun willDispatchViewUpdates(uiManager: UIManagerModule) } From aa27cdba9b135cdcca7370abd25af316a22368b4 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 21 Jul 2025 05:31:43 -0700 Subject: [PATCH 0207/1383] Revert "Fix Dimensions window values on Android < 15 (#52481)" (#52732) Summary: Commit 86994a6e22415dbb5c5348c3cede1f9942a894ea breaks Android for API level 24. Since it has landed last week, we had CI red. reverting this change while we found a valid fix forward. ## Changelog: [Android][Changed] - Reverted fix `Dimensions` `window` values on Android < 15 when edge-to-edge is enabled Pull Request resolved: https://github.com/facebook/react-native/pull/52732 Test Plan: GHA is green.: https://github.com/facebook/react-native/actions/runs/16414048087/job/46377878366?pr=52732 https://github.com/facebook/react-native/actions/runs/16414048087/job/46377878383?pr=52732 Reviewed By: cortinico, rshest Differential Revision: D78657920 Pulled By: cipolleschi fbshipit-source-id: 396a48c9aa7bde3109e25200fe2decc9977efda4 --- .../react-native/ReactAndroid/build.gradle.kts | 1 - .../java/com/facebook/react/ReactRootView.java | 4 ++-- .../react/uimanager/DisplayMetricsHolder.kt | 16 +--------------- packages/react-native/gradle/libs.versions.toml | 2 -- 4 files changed, 3 insertions(+), 20 deletions(-) diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index faa0d8816a1d4e..98ab7976caf9b0 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -630,7 +630,6 @@ dependencies { api(libs.androidx.autofill) api(libs.androidx.swiperefreshlayout) api(libs.androidx.tracing) - api(libs.androidx.window) api(libs.fbjni) api(libs.fresco) 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 a807346d3f9dbb..2f47dfdaa69dcb 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 @@ -869,7 +869,7 @@ private class CustomGlobalLayoutListener implements ViewTreeObserver.OnGlobalLay private int mDeviceRotation = 0; /* package */ CustomGlobalLayoutListener() { - DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(getContext()); + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(getContext().getApplicationContext()); mVisibleViewArea = new Rect(); mMinKeyboardHeightDetected = (int) PixelUtil.toPixelFromDIP(60); } @@ -992,7 +992,7 @@ private void checkForDeviceOrientationChanges() { return; } mDeviceRotation = rotation; - DisplayMetricsHolder.initDisplayMetrics(getContext()); + DisplayMetricsHolder.initDisplayMetrics(getContext().getApplicationContext()); emitOrientationChanged(rotation); } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/DisplayMetricsHolder.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/DisplayMetricsHolder.kt index 994990b83c4acf..9f6c9310a690c4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/DisplayMetricsHolder.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/DisplayMetricsHolder.kt @@ -13,10 +13,8 @@ import android.util.DisplayMetrics import android.view.WindowManager import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat -import androidx.window.layout.WindowMetricsCalculator import com.facebook.react.bridge.WritableMap import com.facebook.react.bridge.WritableNativeMap -import com.facebook.react.views.view.isEdgeToEdgeFeatureFlagOn /** * Holds an instance of the current DisplayMetrics so we don't have to thread it through all the @@ -64,19 +62,9 @@ public object DisplayMetricsHolder { @JvmStatic public fun initDisplayMetrics(context: Context) { val displayMetrics = context.resources.displayMetrics - val windowDisplayMetrics = DisplayMetrics() + windowDisplayMetrics = displayMetrics val screenDisplayMetrics = DisplayMetrics() - - windowDisplayMetrics.setTo(displayMetrics) screenDisplayMetrics.setTo(displayMetrics) - - if (isEdgeToEdgeFeatureFlagOn) { - WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(context).let { - windowDisplayMetrics.widthPixels = it.bounds.width() - windowDisplayMetrics.heightPixels = it.bounds.height() - } - } - val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager // Get the real display metrics if we are using API level 17 or higher. // The real metrics include system decor elements (e.g. soft menu bar). @@ -84,8 +72,6 @@ public object DisplayMetricsHolder { // See: // http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics) @Suppress("DEPRECATION") wm.defaultDisplay.getRealMetrics(screenDisplayMetrics) - - DisplayMetricsHolder.windowDisplayMetrics = windowDisplayMetrics DisplayMetricsHolder.screenDisplayMetrics = screenDisplayMetrics } diff --git a/packages/react-native/gradle/libs.versions.toml b/packages/react-native/gradle/libs.versions.toml index 7bbcf3cc4c6e7a..3a0e09083b3714 100644 --- a/packages/react-native/gradle/libs.versions.toml +++ b/packages/react-native/gradle/libs.versions.toml @@ -16,7 +16,6 @@ androidx-swiperefreshlayout = "1.1.0" androidx-test = "1.5.0" androidx-test-junit = "1.2.1" androidx-tracing = "1.1.0" -androidx-window = "1.4.0" assertj = "3.21.0" binary-compatibility-validator = "0.13.2" download = "5.4.0" @@ -65,7 +64,6 @@ androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx- androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test" } androidx-tracing = { module = "androidx.tracing:tracing", version.ref = "androidx-tracing" } androidx-uiautomator = { group = "androidx.test.uiautomator", name = "uiautomator", version.ref = "uiautomator" } -androidx-window = { module = "androidx.window:window", version.ref = "androidx-window" } fbjni = { module = "com.facebook.fbjni:fbjni", version.ref = "fbjni" } fresco = { module = "com.facebook.fresco:fresco", version.ref = "fresco" } From 0068b9ee90b7fa6da230cdc82d7675dc1b0df239 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Mon, 21 Jul 2025 08:35:59 -0700 Subject: [PATCH 0208/1383] Restore flow dir in react-native package files (#52735) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52735 Changelog: [Internal] (Follow up to keep #50784 non-breaking) Reviewed By: cortinico Differential Revision: D78662770 fbshipit-source-id: 03d931c904c0092481dbd03e8420244639305610 --- packages/react-native/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 32bf6e367866ea..aa53da493b9e14 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -78,6 +78,7 @@ "files": [ "build.gradle.kts", "cli.js", + "flow", "gradle.properties", "gradle/libs.versions.toml", "index.js", From 5c869fd0a56efb923d1314ba4db88b5d9cb526c5 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 21 Jul 2025 08:42:23 -0700 Subject: [PATCH 0209/1383] Run E2E tests on each PR (#52197) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52197 This Diff enables E2E tests to run on every PR. We estimated that, now that we removed JSC and the legacy arch, the cost of running E2E tests on each PR should not be that high. ## Changelog: [Internal] - Run E2E tests on each PR Reviewed By: cortinico Differential Revision: D77148473 fbshipit-source-id: 68191ff81c197d4c4ff9d6e71a41b7253971ddfb --- .github/actions/build-android/action.yml | 9 +-------- .github/workflows/test-all.yml | 12 +----------- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/.github/actions/build-android/action.yml b/.github/actions/build-android/action.yml index 91f8e25bf1d0ae..2eab76601569b0 100644 --- a/.github/actions/build-android/action.yml +++ b/.github/actions/build-android/action.yml @@ -4,9 +4,6 @@ inputs: release-type: required: true description: The type of release we are building. It could be nightly, release or dry-run - run-e2e-tests: - default: 'false' - description: If we need to build to run E2E tests. If yes, we need to build also x86. gradle-cache-encryption-key: description: "The encryption key needed to store the Gradle Configuration cache" runs: @@ -43,11 +40,7 @@ runs: run: | if [[ "${{ inputs.release-type }}" == "dry-run" ]]; then # dry-run: we only build ARM64 to save time/resources. For release/nightlies the default is to build all archs. - if [[ "${{ inputs.run-e2e-tests }}" == 'true' ]]; then - export ORG_GRADLE_PROJECT_reactNativeArchitectures="arm64-v8a,x86" # x86 is required for E2E testing - else - export ORG_GRADLE_PROJECT_reactNativeArchitectures="arm64-v8a" - fi + export ORG_GRADLE_PROJECT_reactNativeArchitectures="arm64-v8a,x86" # x86 is required for E2E testing TASKS="publishAllToMavenTempLocal build" elif [[ "${{ inputs.release-type }}" == "nightly" ]]; then # nightly: we set isSnapshot to true so artifacts are sent to the right repository on Maven Central. diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml index 2a57995aea90b5..741a4a7d967efd 100644 --- a/.github/workflows/test-all.yml +++ b/.github/workflows/test-all.yml @@ -2,11 +2,6 @@ name: Test All on: workflow_dispatch: - inputs: - run-e2e-tests: - description: Whether to run E2E tests or not - type: boolean - default: false pull_request: push: branches: @@ -168,7 +163,6 @@ jobs: flavor: ${{ matrix.flavor }} test_e2e_ios_rntester: - if: ${{ github.ref == 'refs/heads/main' || contains(github.ref, 'stable') || inputs.run-e2e-tests }} runs-on: macos-14-large needs: [test_ios_rntester] @@ -202,7 +196,6 @@ jobs: flavor: ${{ matrix.flavor }} test_e2e_ios_templateapp: - if: ${{ github.ref == 'refs/heads/main' || contains(github.ref, 'stable') || inputs.run-e2e-tests }} runs-on: macos-14-large needs: [build_npm_package, prebuild_apple_dependencies] env: @@ -295,7 +288,6 @@ jobs: working-directory: /tmp/RNTestProject test_e2e_android_templateapp: - if: ${{ github.ref == 'refs/heads/main' || contains(github.ref, 'stable') || inputs.run-e2e-tests }} runs-on: 4-core-ubuntu needs: build_npm_package strategy: @@ -414,11 +406,9 @@ jobs: uses: ./.github/actions/build-android with: release-type: ${{ needs.set_release_type.outputs.RELEASE_TYPE }} - run-e2e-tests: ${{ github.ref == 'refs/heads/main' || contains(github.ref, 'stable') || inputs.run-e2e-tests }} gradle-cache-encryption-key: ${{ secrets.GRADLE_CACHE_ENCRYPTION_KEY }} test_e2e_android_rntester: - if: ${{ github.ref == 'refs/heads/main' || contains(github.ref, 'stable') || inputs.run-e2e-tests }} runs-on: 4-core-ubuntu needs: [build_android] strategy: @@ -616,7 +606,7 @@ jobs: rerun-failed-jobs: runs-on: ubuntu-latest needs: [test_e2e_ios_rntester, test_e2e_android_rntester, test_e2e_ios_templateapp, test_e2e_android_templateapp] - if: always() + if: ${{ github.ref == 'refs/heads/main' && always() }} steps: - name: Checkout uses: actions/checkout@v4 From a7a51275b5d9a9fc1b3e4e7a7f4ce09a86cd4cd6 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 21 Jul 2025 08:51:05 -0700 Subject: [PATCH 0210/1383] Do not setup-node twice in test_js (#52737) Summary: I've noticed that test_js (20) and test_js (24) are actually running on Node 22. That's because the `yarn-install` action is invoking setup-node again with the default value (22). This changes it. Also I'm cleaning up the workflows so that every `yarn-install` invocation is happening just after the `setup-node` invocation. ## Changelog: [INTERNAL] - Pull Request resolved: https://github.com/facebook/react-native/pull/52737 Test Plan: CI which will most likely be red for test_js (20) so will need a follow-up Reviewed By: cipolleschi Differential Revision: D78664671 Pulled By: cortinico fbshipit-source-id: c73390930d1511d1bf0f2d4ea92e83f50b10247f --- .github/actions/build-hermes-macos/action.yml | 4 ++-- .github/actions/build-npm-package/action.yml | 4 ++-- .github/actions/create-release/action.yml | 2 ++ .github/actions/maestro-ios/action.yml | 2 ++ .github/actions/prepare-hermes-workspace/action.yml | 5 ++--- .github/actions/test-ios-helloworld/action.yml | 4 ++-- .github/actions/yarn-install/action.yml | 2 -- .github/workflows/test-all.yml | 3 ++- 8 files changed, 14 insertions(+), 12 deletions(-) diff --git a/.github/actions/build-hermes-macos/action.yml b/.github/actions/build-hermes-macos/action.yml index 41c7e6e869c8e2..d2c3eeed4e368e 100644 --- a/.github/actions/build-hermes-macos/action.yml +++ b/.github/actions/build-hermes-macos/action.yml @@ -15,8 +15,6 @@ runs: steps: - name: Setup xcode uses: ./.github/actions/setup-xcode - - name: Setup node.js - uses: ./.github/actions/setup-node - name: Restore Hermes workspace uses: ./.github/actions/restore-hermes-workspace - name: Restore Cached Artifacts @@ -45,6 +43,8 @@ runs: echo "ARTIFACTS_EXIST=true" >> $GITHUB_ENV echo "ARTIFACTS_EXIST=true" >> $GITHUB_OUTPUT fi + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Yarn- Install Dependencies if: ${{ steps.check_if_apple_artifacts_are_there.outputs.ARTIFACTS_EXIST != 'true' }} uses: ./.github/actions/yarn-install diff --git a/.github/actions/build-npm-package/action.yml b/.github/actions/build-npm-package/action.yml index 807e03a742cfae..4e4e0d6d6c68b9 100644 --- a/.github/actions/build-npm-package/action.yml +++ b/.github/actions/build-npm-package/action.yml @@ -116,12 +116,12 @@ runs: - name: Print Artifacts Directory shell: bash run: ls -lR ./packages/react-native/ReactAndroid/external-artifacts/artifacts/ - - name: Setup node.js - uses: ./.github/actions/setup-node - name: Setup gradle uses: ./.github/actions/setup-gradle with: cache-encryption-key: ${{ inputs.gradle-cache-encryption-key }} + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Install dependencies uses: ./.github/actions/yarn-install - name: Build packages diff --git a/.github/actions/create-release/action.yml b/.github/actions/create-release/action.yml index ff22a0cb3a0906..1d26e17e8fcc24 100644 --- a/.github/actions/create-release/action.yml +++ b/.github/actions/create-release/action.yml @@ -14,6 +14,8 @@ inputs: runs: using: composite steps: + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Yarn install uses: ./.github/actions/yarn-install - name: Configure Git diff --git a/.github/actions/maestro-ios/action.yml b/.github/actions/maestro-ios/action.yml index 5ba4f8dc2aaa66..50b21597c9ed9f 100644 --- a/.github/actions/maestro-ios/action.yml +++ b/.github/actions/maestro-ios/action.yml @@ -35,6 +35,8 @@ runs: with: java-version: '17' distribution: 'zulu' + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Run yarn install uses: ./.github/actions/yarn-install - name: Start Metro in Debug diff --git a/.github/actions/prepare-hermes-workspace/action.yml b/.github/actions/prepare-hermes-workspace/action.yml index 22dbe356ee581d..47953b6760074d 100644 --- a/.github/actions/prepare-hermes-workspace/action.yml +++ b/.github/actions/prepare-hermes-workspace/action.yml @@ -17,9 +17,6 @@ outputs: runs: using: composite steps: - - name: Setup node.js - uses: ./.github/actions/setup-node - - name: Setup hermes version shell: bash id: hermes-version @@ -67,6 +64,8 @@ runs: echo "HERMES_CACHED=true" >> "$GITHUB_OUTPUT" fi + - name: Setup node.js + uses: ./.github/actions/setup-node - name: Yarn- Install Dependencies if: ${{ steps.meaningful-cache.outputs.HERMES_CACHED != 'true' }} uses: ./.github/actions/yarn-install diff --git a/.github/actions/test-ios-helloworld/action.yml b/.github/actions/test-ios-helloworld/action.yml index 00f3edf02a28c1..0a9a6939bba25a 100644 --- a/.github/actions/test-ios-helloworld/action.yml +++ b/.github/actions/test-ios-helloworld/action.yml @@ -23,6 +23,8 @@ runs: uses: ./.github/actions/setup-xcode - name: Setup node.js uses: ./.github/actions/setup-node + - name: Run yarn install + uses: ./.github/actions/yarn-install - name: Create Hermes folder shell: bash run: mkdir -p "$HERMES_WS_DIR" @@ -34,8 +36,6 @@ runs: - name: Print Downloaded hermes shell: bash run: ls -lR "$HERMES_WS_DIR" - - name: Run yarn - uses: ./.github/actions/yarn-install - name: Setup ruby uses: ruby/setup-ruby@v1 with: diff --git a/.github/actions/yarn-install/action.yml b/.github/actions/yarn-install/action.yml index 7f7c7bd2bc9293..cdb4a85c899ec6 100644 --- a/.github/actions/yarn-install/action.yml +++ b/.github/actions/yarn-install/action.yml @@ -2,8 +2,6 @@ name: yarn-install runs: using: composite steps: - - name: Setup node.js - uses: ./.github/actions/setup-node - name: Install dependencies shell: bash run: | diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml index 741a4a7d967efd..7a13dedb7a3dc3 100644 --- a/.github/workflows/test-all.yml +++ b/.github/workflows/test-all.yml @@ -573,7 +573,8 @@ jobs: strategy: fail-fast: false matrix: - node-version: ["24", "22", "20"] + node-version: ["24", "22"] + # node-version: ["24", "22", "20.19.4"] steps: - name: Checkout uses: actions/checkout@v4 From 3ea2f62531b0a093950a2c7d91f829cd40f7633a Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 21 Jul 2025 09:02:04 -0700 Subject: [PATCH 0211/1383] Bump ccache cache key on GHA (#52711) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52711 The ccache cache is not really working. That's because we don't have a way to properly compute the cache. I'm adding has `hashFiles` to collect all the C++ and CMake files that are used by ccache to fix this. Changelog: [Internal] [Changed] - Reviewed By: cipolleschi Differential Revision: D78560946 fbshipit-source-id: 8d521d01386b62d3cfbd485f8e6fcf5f66eba71b --- .github/actions/build-android/action.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/actions/build-android/action.yml b/.github/actions/build-android/action.yml index 2eab76601569b0..ac769b62ce95d5 100644 --- a/.github/actions/build-android/action.yml +++ b/.github/actions/build-android/action.yml @@ -28,10 +28,11 @@ runs: uses: actions/cache/restore@v4 with: path: /github/home/.cache/ccache - key: v1-ccache-android-${{ github.job }}-${{ github.ref }} + key: v2-ccache-android-${{ github.job }}-${{ github.ref }}-${{ hashFiles('packages/react-native/ReactAndroid/**/*.cpp', 'packages/react-native/ReactAndroid/**/*.h', 'packages/react-native/ReactCommon/**/*.cpp', 'packages/react-native/ReactAndroid/**/CMakeLists.txt', 'packages/react-native/ReactCommon/**/CMakeLists.txt') }} restore-keys: | - v1-ccache-android-${{ github.job }}- - v1-ccache-android- + v2-ccache-android-${{ github.job }}-${{ github.ref }}- + v2-ccache-android-${{ github.job }}- + v2-ccache-android- - name: Show ccache stats shell: bash run: ccache -s -v @@ -56,7 +57,7 @@ runs: uses: actions/cache/save@v4 with: path: /github/home/.cache/ccache - key: v1-ccache-android-${{ github.job }}-${{ github.ref }} + key: v2-ccache-android-${{ github.job }}-${{ github.ref }}-${{ hashFiles('packages/react-native/ReactAndroid/**/*.cpp', 'packages/react-native/ReactAndroid/**/*.h', 'packages/react-native/ReactCommon/**/*.cpp', 'packages/react-native/ReactAndroid/**/CMakeLists.txt', 'packages/react-native/ReactCommon/**/CMakeLists.txt') }} - name: Show ccache stats shell: bash run: ccache -s -v From 2372c1c56a4c197cac357abbde1aa795dc0bc65b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateo=20Guzm=C3=A1n?= Date: Mon, 21 Jul 2025 09:11:29 -0700 Subject: [PATCH 0212/1383] Fix ktfmt symbolic links issues (#52721) Summary: There are symbolic link issues with ktfmt after building the rn-tester. Putting back this patch to address that issue. ## Changelog: [INTERNAL] - Fix ktfmt symbolic links issues Pull Request resolved: https://github.com/facebook/react-native/pull/52721 Test Plan: 1. Build the rn-tester: ```sh yarn android ``` 2. Unformat a file manually and then: ```sh yarn lint-kotlin-check yarn lint-kotlin ``` Reviewed By: cipolleschi Differential Revision: D78647797 Pulled By: cortinico fbshipit-source-id: b2f230741466be0a95c21a9b98f3d15b865c2b83 --- build.gradle.kts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/build.gradle.kts b/build.gradle.kts index 4fee398eaecb2a..90a4ab4199152a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -157,4 +157,11 @@ allprojects { com.ncorti.ktfmt.gradle.tasks.KtfmtCheckTask::class, com.ncorti.ktfmt.gradle.tasks.KtfmtFormatTask::class) .forEach { tasks.withType(it) { exclude(excludePatterns) } } + + // Disable the problematic ktfmt script tasks due to symbolic link issues in subprojects + afterEvaluate { + listOf("ktfmtCheckScripts", "ktfmtFormatScripts").forEach { + tasks.findByName(it)?.enabled = false + } + } } From 976055e52b4ca7af353e5de45fd4139cfcacd3d9 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Mon, 21 Jul 2025 15:13:17 -0700 Subject: [PATCH 0213/1383] Add annotations or make things readonly to prepare for array literal soundness fix Summary: Changelog: [Internal] Reviewed By: abhinayrathore, marcoww6 Differential Revision: D78689934 fbshipit-source-id: f749c4a0a6c34c80f09e4aaa05200ff282151838 --- .../components/GenerateViewConfigJs.js | 4 +++- .../Data/__tests__/parseLogBoxLog-test.js | 20 +++++++++---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js b/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js index 5a200a21da60ec..3d538f7d4d00c6 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js +++ b/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js @@ -317,7 +317,9 @@ function buildViewConfig( return directEvents; }, []); - const properties = [ + const properties: Array< + BabelNodeObjectMethod | BabelNodeObjectProperty | BabelNodeSpreadElement, + > = [ t.objectProperty( t.identifier('uiViewClassName'), t.stringLiteral(componentName), 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 74c456bb7a012a..5d83fd003b2084 100644 --- a/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js +++ b/packages/react-native/Libraries/LogBox/Data/__tests__/parseLogBoxLog-test.js @@ -559,7 +559,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with `error.componentStack`', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, @@ -614,7 +614,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with a component stack in the message', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, @@ -669,7 +669,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses a fatal exception', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: true, isComponentError: false, @@ -712,7 +712,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses a render error', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isComponentError: true, isFatal: true, @@ -754,7 +754,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('a malformed syntax error falls back to a syntax error', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: true, isComponentError: false, @@ -954,7 +954,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('detects a single component in a component stack', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: true, isComponentError: true, @@ -1004,7 +1004,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with `error.componentStack`', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, @@ -1225,7 +1225,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with `error.componentStack`', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, @@ -1534,7 +1534,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with `error.componentStack`', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, @@ -1596,7 +1596,7 @@ Please follow the instructions at: fburl.com/rn-remote-assets`, }); it('parses an error log with a component stack in the message', () => { - const error = { + const error: ExtendedExceptionData = { id: 0, isFatal: false, isComponentError: false, From 7970ee99980ac4c735812a9da9e1ca616313ed1a Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Mon, 21 Jul 2025 15:22:17 -0700 Subject: [PATCH 0214/1383] Prepare react-native for prettier v3: 2/n (#52745) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52745 Prettier v3 no longer loads plugin implicitly. This diff first configures the hermes-parser plugin explicitly to prepare for v3 rollout. D78590158 missed this config. Changelog: [Internal] Reviewed By: christophpurrer Differential Revision: D78673890 fbshipit-source-id: 1931718ef2b3f011621bf4d64c8936a698506374 --- packages/react-native-codegen/.prettierrc | 3 ++- private/helloworld/.prettierrc.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/react-native-codegen/.prettierrc b/packages/react-native-codegen/.prettierrc index 600a26c495189d..a96782c745a81a 100644 --- a/packages/react-native-codegen/.prettierrc +++ b/packages/react-native-codegen/.prettierrc @@ -4,5 +4,6 @@ "bracketSpacing": false, "requirePragma": true, "singleQuote": true, - "trailingComma": "all" + "trailingComma": "all", + "parser": "babel" } diff --git a/private/helloworld/.prettierrc.js b/private/helloworld/.prettierrc.js index e7f500b19a6675..974d91d1a148c2 100644 --- a/private/helloworld/.prettierrc.js +++ b/private/helloworld/.prettierrc.js @@ -13,4 +13,20 @@ module.exports = { bracketSpacing: false, singleQuote: true, trailingComma: 'all', + plugins: [ + // Using module.parent and createRequire hack to simulate prettier v2 plugin resolution behavior. + // The hack allows us to resolve the plugin from the install location of prettier. + (module.parent + ? require('module').createRequire(module.parent.id) + : require + ).resolve('prettier-plugin-hermes-parser'), + ], + overrides: [ + { + files: ['*.js', '*.js.flow'], + options: { + parser: 'hermes', + }, + }, + ], }; From 2c3a00b7b16168864a93372acf4d2828db2f9b22 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Mon, 21 Jul 2025 19:45:34 -0700 Subject: [PATCH 0215/1383] Use the prettier config at the root for react-native-codegen (#52746) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52746 The config is needed for build, so I renamed it. In this way, the formatting of js code in react-native repo will be consistently controlled by the prettier config in the root. This change will make prettier v3 upgrade easier. Changelog: [Internal] Reviewed By: pieterv Differential Revision: D78700564 fbshipit-source-id: 392ed490bf814870f285c8372ff68b454e228802 --- .../{.prettierrc => build.prettierrc} | 0 .../react-native-codegen/scripts/build.js | 2 +- .../generators/modules/GenerateModuleCpp.js | 8 ++-- .../src/generators/modules/GenerateModuleH.js | 16 +++---- .../modules/GenerateModuleJavaSpec.js | 12 ++--- .../source/serializeModule.js | 24 +++++----- .../__tests__/module-parser-e2e-test.js | 48 +++++++++---------- .../src/parsers/flow/parser.js | 20 ++++---- .../typescript/components/componentsUtils.js | 4 +- .../typescript-module-parser-e2e-test.js | 48 +++++++++---------- .../src/parsers/typescript/parser.js | 30 ++++++------ 11 files changed, 106 insertions(+), 106 deletions(-) rename packages/react-native-codegen/{.prettierrc => build.prettierrc} (100%) diff --git a/packages/react-native-codegen/.prettierrc b/packages/react-native-codegen/build.prettierrc similarity index 100% rename from packages/react-native-codegen/.prettierrc rename to packages/react-native-codegen/build.prettierrc diff --git a/packages/react-native-codegen/scripts/build.js b/packages/react-native-codegen/scripts/build.js index 862ccdd759860f..16a70ff703626d 100644 --- a/packages/react-native-codegen/scripts/build.js +++ b/packages/react-native-codegen/scripts/build.js @@ -32,7 +32,7 @@ const prettier = require('prettier'); const {styleText} = require('util'); const prettierConfig = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '..', '.prettierrc'), 'utf8'), + fs.readFileSync(path.resolve(__dirname, '..', 'build.prettierrc'), 'utf8'), ); const SRC_DIR = 'src'; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js index 3c4e9b4fe9f9ee..e26b789740bcb9 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js @@ -47,15 +47,15 @@ const HostFunctionTemplate = ({ isVoid ? `\n ${methodCall};` : isNullable - ? `\n auto result = ${methodCall};` - : '' + ? `\n auto result = ${methodCall};` + : '' } return ${ isVoid ? 'jsi::Value::undefined()' : isNullable - ? 'result ? jsi::Value(std::move(*result)) : jsi::Value::null()' - : methodCall + ? 'result ? jsi::Value(std::move(*result)) : jsi::Value::null()' + : methodCall }; }`; }; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js index 9537f4f044b8d7..2e666347e51446 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js @@ -572,17 +572,17 @@ function translateEventEmitterToCpp( ${ isVoidTypeAnnotation ? '' : `template ` }void emit${toPascalCase(eventEmitter.name)}(${ - isVoidTypeAnnotation - ? '' - : `${isArray ? `std::vector<${templateName}>` : templateName} value` - }) {${ - isVoidTypeAnnotation - ? '' - : ` + isVoidTypeAnnotation + ? '' + : `${isArray ? `std::vector<${templateName}>` : templateName} value` + }) {${ + isVoidTypeAnnotation + ? '' + : ` static_assert(bridging::supportsFromJs<${ isArray ? `std::vector<${templateName}>` : templateName }, ${jsiType}>, "value cannnot be converted to ${jsiType}");` - } + } static_cast&>(*delegate_.eventEmitterMap_["${eventEmitter.name}"]).emit(${ diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js index 8ff63e8c994a82..e634125797cae6 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js @@ -84,10 +84,10 @@ function EventEmitterTemplate( : '' }) { mEventEmitterCallback.invoke("${eventEmitter.name}"${ - eventEmitter.typeAnnotation.typeAnnotation.type !== 'VoidTypeAnnotation' - ? ', value' - : '' - }); + eventEmitter.typeAnnotation.typeAnnotation.type !== 'VoidTypeAnnotation' + ? ', value' + : '' + }); }`; } @@ -113,8 +113,8 @@ function MethodTemplate( const methodClosing = abstract ? ';' : methodBody != null && methodBody.length > 0 - ? ` { ${methodBody} }` - : ' {}'; + ? ` { ${methodBody} }` + : ' {}'; return ` ${methodJavaAnnotation} public ${methodQualifier}${translatedReturnType} ${methodName}(${traversedArgs.join( ', ', diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js index 10e3c2eeec9c6c..d4b80dcb054c29 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js @@ -74,22 +74,22 @@ namespace facebook::react { }), ) .join('\n' + ' '.repeat(8))}${ - eventEmitters.length > 0 - ? eventEmitters - .map(eventEmitter => { - return ` + eventEmitters.length > 0 + ? eventEmitters + .map(eventEmitter => { + return ` eventEmitterMap_["${eventEmitter.name}"] = std::make_shared>();`; - }) - .join('') - : '' -}${ - eventEmitters.length > 0 - ? ` + }) + .join('') + : '' + }${ + eventEmitters.length > 0 + ? ` setEventEmitterCallback([&](const std::string &name, id value) { static_cast &>(*eventEmitterMap_[name]).emit(value); });` - : '' -} + : '' + } } } // namespace facebook::react`; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js index 66b5dfc975db16..edfb10de5b018e 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js @@ -116,10 +116,10 @@ describe('Flow Module Parser', () => { nullable && optional ? 'a nullable and optional' : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : optional + ? 'an optional' + : 'a required'; function annotateArg(paramName: string, paramType: string) { if (nullable && optional) { @@ -167,10 +167,10 @@ describe('Flow Module Parser', () => { (nullable && optional ? 'Nullable and Optional' : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Parameter', + ? 'Nullable' + : optional + ? 'Optional' + : 'Required') + ' Parameter', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { expect(() => parseParamType('arg', 'Function')).toThrow( @@ -397,10 +397,10 @@ describe('Flow Module Parser', () => { isPropNullable && isPropOptional ? 'a nullable and optional' : isPropNullable - ? 'a nullable' - : isPropOptional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : isPropOptional + ? 'an optional' + : 'a required'; function annotateProp(propName: string, propType: string) { if (isPropNullable && isPropOptional) { @@ -465,10 +465,10 @@ describe('Flow Module Parser', () => { (isPropNullable && isPropOptional ? 'Nullable and Optional' : isPropNullable - ? 'Nullable' - : isPropOptional - ? 'Optional' - : 'Required') + ' Property', + ? 'Nullable' + : isPropOptional + ? 'Optional' + : 'Required') + ' Property', () => { describe('Props with Primitive Types', () => { PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { @@ -932,10 +932,10 @@ describe('Flow Module Parser', () => { nullable && optional ? 'a nullable and optional' : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : optional + ? 'an optional' + : 'a required'; function annotateProp(propName: string, propType: string) { if (nullable && optional) { @@ -1001,10 +1001,10 @@ describe('Flow Module Parser', () => { (nullable && optional ? 'Nullable and Optional' : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Property', + ? 'Nullable' + : optional + ? 'Optional' + : 'Required') + ' Property', () => { /** * TODO: Fill out props in promise diff --git a/packages/react-native-codegen/src/parsers/flow/parser.js b/packages/react-native-codegen/src/parsers/flow/parser.js index 4369892edab4ce..c8224d4e44e729 100644 --- a/packages/react-native-codegen/src/parsers/flow/parser.js +++ b/packages/react-native-codegen/src/parsers/flow/parser.js @@ -187,8 +187,8 @@ class FlowParser implements Parser { typeAnnotation.type === 'EnumStringBody' ? 'StringTypeAnnotation' : typeAnnotation.type === 'EnumNumberBody' - ? 'NumberTypeAnnotation' - : null; + ? 'NumberTypeAnnotation' + : null; if (!enumMembersType) { throw new Error( `Unknown enum type annotation type. Got: ${typeAnnotation.type}. Expected: EnumStringBody or EnumNumberBody.`, @@ -242,14 +242,14 @@ class FlowParser implements Parser { value: member.init.value, } : typeof member.init?.value === 'string' - ? { - type: 'StringLiteralTypeAnnotation', - value: member.init.value, - } - : { - type: 'StringLiteralTypeAnnotation', - value: member.id.name, - }; + ? { + type: 'StringLiteralTypeAnnotation', + value: member.init.value, + } + : { + type: 'StringLiteralTypeAnnotation', + value: member.id.name, + }; return { name: member.id.name, diff --git a/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js b/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js index e74f03572cc501..f178527433c2ea 100644 --- a/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js +++ b/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js @@ -353,8 +353,8 @@ function setDefaultValue( common.default = ((defaultValue === null ? null : defaultValue - ? defaultValue - : 0): number | null); + ? defaultValue + : 0): number | null); break; case 'BooleanTypeAnnotation': common.default = defaultValue === null ? null : !!defaultValue; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js index e1f260be8c3580..6f0eeeb6b55ad8 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js @@ -192,10 +192,10 @@ describe('TypeScript Module Parser', () => { nullable && optional ? 'a nullable and optional' : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : optional + ? 'an optional' + : 'a required'; function annotateArg(paramName: string, paramType: string) { if (nullable && optional) { @@ -243,10 +243,10 @@ describe('TypeScript Module Parser', () => { (nullable && optional ? 'Nullable and Optional' : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Parameter', + ? 'Nullable' + : optional + ? 'Optional' + : 'Required') + ' Parameter', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { expect(() => parseParamType('arg', 'Function')).toThrow( @@ -473,10 +473,10 @@ describe('TypeScript Module Parser', () => { isPropNullable && isPropOptional ? 'a nullable and optional' : isPropNullable - ? 'a nullable' - : isPropOptional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : isPropOptional + ? 'an optional' + : 'a required'; function annotateProp(propName: string, propType: string) { if (isPropNullable && isPropOptional) { @@ -541,10 +541,10 @@ describe('TypeScript Module Parser', () => { (isPropNullable && isPropOptional ? 'Nullable and Optional' : isPropNullable - ? 'Nullable' - : isPropOptional - ? 'Optional' - : 'Required') + ' Property', + ? 'Nullable' + : isPropOptional + ? 'Optional' + : 'Required') + ' Property', () => { describe('Props with Primitive Types', () => { PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { @@ -1007,10 +1007,10 @@ describe('TypeScript Module Parser', () => { nullable && optional ? 'a nullable and optional' : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; + ? 'a nullable' + : optional + ? 'an optional' + : 'a required'; function annotateProp(propName: string, propType: string) { if (nullable && optional) { @@ -1076,10 +1076,10 @@ describe('TypeScript Module Parser', () => { (nullable && optional ? 'Nullable and Optional' : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Property', + ? 'Nullable' + : optional + ? 'Optional' + : 'Required') + ' Property', () => { /** * TODO: Fill out props in promise diff --git a/packages/react-native-codegen/src/parsers/typescript/parser.js b/packages/react-native-codegen/src/parsers/typescript/parser.js index ca01a904c66461..82ac353a5f188b 100644 --- a/packages/react-native-codegen/src/parsers/typescript/parser.js +++ b/packages/react-native-codegen/src/parsers/typescript/parser.js @@ -233,8 +233,8 @@ class TypeScriptParser implements Parser { enumMembersType === 'StringTypeAnnotation' ? 'StringLiteral' : enumMembersType === 'NumberTypeAnnotation' - ? 'NumericLiteral' - : null; + ? 'NumericLiteral' + : null; typeAnnotation.members.forEach(member => { const isNegative = @@ -263,19 +263,19 @@ class TypeScriptParser implements Parser { value: -1 * member.initializer?.argument?.value, } : typeof member.initializer?.value === 'number' - ? { - type: 'NumberLiteralTypeAnnotation', - value: member.initializer?.value, - } - : typeof member.initializer?.value === 'string' - ? { - type: 'StringLiteralTypeAnnotation', - value: member.initializer?.value, - } - : { - type: 'StringLiteralTypeAnnotation', - value: member.id.name, - }; + ? { + type: 'NumberLiteralTypeAnnotation', + value: member.initializer?.value, + } + : typeof member.initializer?.value === 'string' + ? { + type: 'StringLiteralTypeAnnotation', + value: member.initializer?.value, + } + : { + type: 'StringLiteralTypeAnnotation', + value: member.id.name, + }; return { name: member.id.name, From c0eeebbd9da7a9c27334d9c1630c4f0e194ad960 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Tue, 22 Jul 2025 00:48:40 -0700 Subject: [PATCH 0216/1383] Apply clang-tidy setting: fantorm/rntester (#52731) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52731 Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D78634903 fbshipit-source-id: f4ad862061630a098e80a125e25ae3af17b9eb60 --- .../NativeCxxModuleExample.cpp | 67 ++++++++++--------- .../NativeCxxModuleExample.h | 9 +-- .../tester/src/NativeFantom.cpp | 4 +- .../tester/src/NativeFantom.h | 6 +- .../tester/src/TesterMountingManager.cpp | 2 +- 5 files changed, 46 insertions(+), 42 deletions(-) diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp index f36996e15daeea..1a5c836259f215 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace facebook::react { @@ -28,13 +29,13 @@ NativeCxxModuleExample::NativeCxxModuleExample( : NativeCxxModuleExampleCxxSpec(std::move(jsInvoker)) {} void NativeCxxModuleExample::getValueWithCallback( - jsi::Runtime& rt, - AsyncCallback callback) { + jsi::Runtime& /*rt*/, + const AsyncCallback& callback) { callback({"value from callback!"}); } std::function NativeCxxModuleExample::setValueCallbackWithSubscription( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, AsyncCallback callback) { valueCallback_ = std::make_optional(callback); return [&]() { @@ -46,46 +47,46 @@ std::function NativeCxxModuleExample::setValueCallbackWithSubscription( } std::vector> NativeCxxModuleExample::getArray( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::vector> arg) { return arg; } -bool NativeCxxModuleExample::getBool(jsi::Runtime& rt, bool arg) { +bool NativeCxxModuleExample::getBool(jsi::Runtime& /*rt*/, bool arg) { return arg; } -ConstantsStruct NativeCxxModuleExample::getConstants(jsi::Runtime& rt) { +ConstantsStruct NativeCxxModuleExample::getConstants(jsi::Runtime& /*rt*/) { return ConstantsStruct{true, 69, "react-native"}; } CustomEnumInt NativeCxxModuleExample::getCustomEnum( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, CustomEnumInt arg) { return arg; } std::shared_ptr NativeCxxModuleExample::getCustomHostObject( - jsi::Runtime& rt) { + jsi::Runtime& /*rt*/) { return std::make_shared( std::make_shared("answer", 42)); } std::string NativeCxxModuleExample::consumeCustomHostObject( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::shared_ptr arg) { auto value = arg->getValue(); return value->a_ + std::to_string(value->b_); } BinaryTreeNode NativeCxxModuleExample::getBinaryTreeNode( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, BinaryTreeNode arg) { return arg; } GraphNode NativeCxxModuleExample::getGraphNode( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, GraphNode arg) { if (arg.neighbors) { arg.neighbors->emplace_back(GraphNode{.label = "top"}); @@ -95,41 +96,41 @@ GraphNode NativeCxxModuleExample::getGraphNode( } NativeCxxModuleExampleEnumInt NativeCxxModuleExample::getNumEnum( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, NativeCxxModuleExampleEnumInt arg) { return arg; } NativeCxxModuleExampleEnumStr NativeCxxModuleExample::getStrEnum( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, NativeCxxModuleExampleEnumNone /*arg*/) { return NativeCxxModuleExampleEnumStr::SB; } std::map> NativeCxxModuleExample::getMap( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::map> arg) { return arg; } -double NativeCxxModuleExample::getNumber(jsi::Runtime& rt, double arg) { +double NativeCxxModuleExample::getNumber(jsi::Runtime& /*rt*/, double arg) { return arg; } ObjectStruct NativeCxxModuleExample::getObject( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, ObjectStruct arg) { return arg; } std::set NativeCxxModuleExample::getSet( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::set arg) { return arg; } std::string NativeCxxModuleExample::getString( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::string arg) { return arg; } @@ -137,7 +138,7 @@ std::string NativeCxxModuleExample::getString( std::string NativeCxxModuleExample::getUnion( jsi::Runtime& rt, float x, - std::string y, + const std::string& y, jsi::Object z) { std::string result = "x: " + to_string_with_precision(x) + ", y: " + y + ", z: { "; @@ -154,11 +155,11 @@ std::string NativeCxxModuleExample::getUnion( } ValueStruct NativeCxxModuleExample::getValue( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, double x, std::string y, ObjectStruct z) { - ValueStruct result{x, y, z}; + ValueStruct result{x, std::move(y), std::move(z)}; return result; } @@ -175,12 +176,12 @@ AsyncPromise NativeCxxModuleExample::getValueWithPromise( } std::optional NativeCxxModuleExample::getWithWithOptionalArgs( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, std::optional optionalArg) { return optionalArg; } -void NativeCxxModuleExample::voidFunc(jsi::Runtime& rt) { +void NativeCxxModuleExample::voidFunc(jsi::Runtime& /*rt*/) { // Emit some events emitOnPress(); emitOnClick("value from callback on click!"); @@ -198,17 +199,17 @@ AsyncPromise<> NativeCxxModuleExample::voidPromise(jsi::Runtime& rt) { return promise; } -void NativeCxxModuleExample::setMenu(jsi::Runtime& rt, MenuItem menuItem) { +void NativeCxxModuleExample::setMenu(jsi::Runtime& /*rt*/, MenuItem menuItem) { menuItem.onPress("value", true); if (menuItem.items) { - for (auto subMenuItem : *menuItem.items) { + for (const auto& subMenuItem : *menuItem.items) { subMenuItem.onPress("another value", false); } } } void NativeCxxModuleExample::emitCustomDeviceEvent( - jsi::Runtime& rt, + jsi::Runtime& /*rt*/, const std::string& eventName) { // Test emitting device events (RCTDeviceEventEmitter.emit) from C++ // TurboModule with arbitrary arguments. This can be called from any thread @@ -226,27 +227,27 @@ void NativeCxxModuleExample::emitCustomDeviceEvent( }); } -void NativeCxxModuleExample::voidFuncThrows(jsi::Runtime& rt) { +void NativeCxxModuleExample::voidFuncThrows(jsi::Runtime& /*rt*/) { throw std::runtime_error("Intentional exception from Cxx voidFuncThrows"); }; ObjectStruct NativeCxxModuleExample::getObjectThrows( - jsi::Runtime& rt, - ObjectStruct arg) { + jsi::Runtime& /*rt*/, + const ObjectStruct& /*arg*/) { throw std::runtime_error("Intentional exception from Cxx getObjectThrows"); }; -AsyncPromise<> NativeCxxModuleExample::promiseThrows(jsi::Runtime& rt) { +AsyncPromise<> NativeCxxModuleExample::promiseThrows(jsi::Runtime& /*rt*/) { throw std::runtime_error("Intentional exception from Cxx promiseThrows"); }; -void NativeCxxModuleExample::voidFuncAssert(jsi::Runtime& rt) { +void NativeCxxModuleExample::voidFuncAssert(jsi::Runtime& /*rt*/) { react_native_assert(false && "Intentional assert from Cxx voidFuncAssert"); }; ObjectStruct NativeCxxModuleExample::getObjectAssert( - jsi::Runtime& rt, - ObjectStruct arg) { + jsi::Runtime& /*rt*/, + const ObjectStruct& /*arg*/) { react_native_assert(false && "Intentional assert from Cxx getObjectAssert"); // Asserts disabled diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h index 885f4d8090c65c..b250f125341050 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h @@ -134,7 +134,7 @@ class NativeCxxModuleExample void getValueWithCallback( jsi::Runtime& rt, - AsyncCallback callback); + const AsyncCallback& callback); std::function setValueCallbackWithSubscription( jsi::Runtime& rt, @@ -180,7 +180,8 @@ class NativeCxxModuleExample std::string getString(jsi::Runtime& rt, std::string arg); - std::string getUnion(jsi::Runtime& rt, float x, std::string y, jsi::Object z); + std::string + getUnion(jsi::Runtime& rt, float x, const std::string& y, jsi::Object z); ValueStruct getValue(jsi::Runtime& rt, double x, std::string y, ObjectStruct z); @@ -201,13 +202,13 @@ class NativeCxxModuleExample void voidFuncThrows(jsi::Runtime& rt); - ObjectStruct getObjectThrows(jsi::Runtime& rt, ObjectStruct arg); + ObjectStruct getObjectThrows(jsi::Runtime& rt, const ObjectStruct& arg); AsyncPromise<> promiseThrows(jsi::Runtime& rt); void voidFuncAssert(jsi::Runtime& rt); - ObjectStruct getObjectAssert(jsi::Runtime& rt, ObjectStruct arg); + ObjectStruct getObjectAssert(jsi::Runtime& rt, const ObjectStruct& arg); AsyncPromise<> promiseAssert(jsi::Runtime& rt); diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp index e0ee7a1e8ccca5..0223f5b9063b3a 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.cpp +++ b/private/react-native-fantom/tester/src/NativeFantom.cpp @@ -91,7 +91,7 @@ std::string NativeFantom::getRenderedOutput( void NativeFantom::reportTestSuiteResultsJSON( jsi::Runtime& /*runtime*/, - std::string testSuiteResultsJSON) { + const std::string& testSuiteResultsJSON) { std::cout << testSuiteResultsJSON << std::endl; } @@ -242,7 +242,7 @@ jsi::Function NativeFantom::createShadowNodeRevisionGetter( void NativeFantom::saveJSMemoryHeapSnapshot( jsi::Runtime& runtime, - std::string filePath) { + const std::string& filePath) { runtime.instrumentation().collectGarbage("heapsnapshot"); runtime.instrumentation().createSnapshotToFile(filePath); } diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index 0e9ef4dee5264f..923ad92037b83b 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -105,7 +105,7 @@ class NativeFantom : public NativeFantomCxxSpec { void reportTestSuiteResultsJSON( jsi::Runtime& runtime, - std::string testSuiteResultsJSON); + const std::string& testSuiteResultsJSON); void enqueueNativeEvent( jsi::Runtime& runtime, @@ -142,7 +142,9 @@ class NativeFantom : public NativeFantomCxxSpec { jsi::Runtime& runtime, std::shared_ptr shadowNode); - void saveJSMemoryHeapSnapshot(jsi::Runtime& runtime, std::string filePath); + void saveJSMemoryHeapSnapshot( + jsi::Runtime& runtime, + const std::string& filePath); private: TesterAppDelegate& appDelegate_; diff --git a/private/react-native-fantom/tester/src/TesterMountingManager.cpp b/private/react-native-fantom/tester/src/TesterMountingManager.cpp index d7a5c4611d95e5..47b2191e1a603e 100644 --- a/private/react-native-fantom/tester/src/TesterMountingManager.cpp +++ b/private/react-native-fantom/tester/src/TesterMountingManager.cpp @@ -23,7 +23,7 @@ TesterMountingManager::TesterMountingManager( void TesterMountingManager::executeMount( SurfaceId surfaceId, MountingTransaction&& mountingTransaction) { - auto mutations = mountingTransaction.getMutations(); + const auto& mutations = mountingTransaction.getMutations(); LOG(INFO) << "executeMount: surfaceId = " << surfaceId; if (viewTrees_.find(surfaceId) != viewTrees_.end()) { From c102f245228c65c8107b0ec21d836fcf2f925937 Mon Sep 17 00:00:00 2001 From: React Native Bot Date: Tue, 22 Jul 2025 02:54:17 -0700 Subject: [PATCH 0217/1383] Add changelog for v0.81.0-rc.2 (#52744) Summary: Add Changelog for 0.81.0-rc.2 ## Changelog: [Internal] - Add Changelog for 0.81.0-rc.2 Pull Request resolved: https://github.com/facebook/react-native/pull/52744 Test Plan: N/A Reviewed By: cortinico Differential Revision: D78727514 Pulled By: rshest fbshipit-source-id: 7bee2ec44705c7844c6fe03781f6031472d7b341 --- CHANGELOG.md | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a4efb98fbff9c..ce8864326b72c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,114 @@ # Changelog +## v0.81.0-rc.2 + +### Breaking + + + +#### Android specific + + + +#### iOS specific + + + +### Added + + + +#### Android specific + + + +#### iOS specific + + + +### Changed + +- Added support to `react-native/babel-preset` for a `hermesParserOptions` option, that expects an object that enables overriding `hermes-parser` options. ([0508eddfe6](https://github.com/facebook/react-native/commit/0508eddfe60df60cb3bfa4074ae199bd0e492d5f) by [@yungsters](https://github.com/yungsters)) +- `NewAppScreen` no longer internally handles device safe area, use optional `safeAreaInsets` prop (aligned in 0.81 template) ([732bd12dc2](https://github.com/facebook/react-native/commit/732bd12dc21460641ef01b23f2eb722f26b060d5) by [@huntie](https://github.com/huntie)) + +#### Android specific + + + +#### iOS specific + + + +### Deprecated + + + +#### Android specific + + + +#### iOS specific + + + +### Removed + + + +#### Android specific + + + +#### iOS specific + + + +### Fixed + + + +#### Android specific + + + +#### iOS specific + +- Fixed issue with RNDeps release/debug switch failing ([4ee2b60a1e](https://github.com/facebook/react-native/commit/4ee2b60a1eacca744d58a7ad336ca9d3714289f6) by [@chrfalch](https://github.com/chrfalch)) +- Fixed missing script for resolving prebuilt xcframework when switching between release/debug ([2e55241a90](https://github.com/facebook/react-native/commit/2e55241a901b4cd95917de68ce9078928820a208) by [@chrfalch](https://github.com/chrfalch)) + +### Security + + + +#### Android specific + + + +#### iOS specific + + + +### Unknown + +- Release 0.81.0-rc.2 ([68ef746ec5](https://github.com/facebook/react-native/commit/68ef746ec5dd7d2874d190733e75bb8197034c5a) by [@react-native-bot](https://github.com/react-native-bot)) +- Fix E2E test script when the ci flag is not specified ([cdd7f99581](https://github.com/facebook/react-native/commit/cdd7f995813727b630ff38abc8a910a0f8f10b37) by [@cipolleschi](https://github.com/cipolleschi)) +- Fix E2E script when using CI artifacts ([d8bf94489a](https://github.com/facebook/react-native/commit/d8bf94489ab7498eba7e5f45d09dd2819fe739c3) by [@cipolleschi](https://github.com/cipolleschi)) +- Bump Podfile.lock ([10b63c15b6](https://github.com/facebook/react-native/commit/10b63c15b6faaf54d555ede879f82ac565f030a9) by [@react-native-bot](https://github.com/react-native-bot)) +- Release 0.81.0-rc.1 ([b06bb89ddd](https://github.com/facebook/react-native/commit/b06bb89ddd3cebddea4716036a4368b87a65f492) by [@react-native-bot](https://github.com/react-native-bot)) + +#### Android Unknown + + + +#### iOS Unknown + + + +#### Failed to parse + + + + ## v0.81.0-rc.1 ### Added From 59101d6809079913fbdddb0df196b6ed383f96e4 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 22 Jul 2025 03:16:48 -0700 Subject: [PATCH 0218/1383] Remove unnecessary OSSLibraryExample (#52705) Summary: This module is currently unused, so we can clean it up. ## Changelog: [INTERNAL] - Pull Request resolved: https://github.com/facebook/react-native/pull/52705 Test Plan: CI Reviewed By: cipolleschi Differential Revision: D78555763 Pulled By: cortinico fbshipit-source-id: 0a6152ab3d357cac0c6d7669f292680af7b87074 --- .gitignore | 1 - .../OSSLibraryExample.podspec | 24 -- packages/react-native-test-library/README.md | 9 - .../android/build.gradle.kts | 32 -- .../android/gradle.properties | 4 - .../fbreact/specs/NativeSampleModuleSpec.java | 37 --- .../osslibraryexample/NativeSampleModule.kt | 30 -- .../OSSLibraryExamplePackage.kt | 23 -- .../SampleNativeComponentViewManager.kt | 105 ------ .../osslibraryexample/SampleNativeView.kt | 97 ------ .../SampleNativeComponentManagerDelegate.java | 45 --- ...SampleNativeComponentManagerInterface.java | 21 -- .../android/src/main/jni/CMakeLists.txt | 26 -- .../jni/OSSLibraryExampleSpec-generated.cpp | 32 -- .../src/main/jni/OSSLibraryExampleSpec.h | 31 -- .../ComponentDescriptors.cpp | 22 -- .../ComponentDescriptors.h | 24 -- .../OSSLibraryExampleSpec/EventEmitters.cpp | 95 ------ .../OSSLibraryExampleSpec/EventEmitters.h | 49 --- .../OSSLibraryExampleSpecJSI-generated.cpp | 26 -- .../OSSLibraryExampleSpecJSI.h | 67 ---- .../OSSLibraryExampleSpec/Props.cpp | 26 -- .../components/OSSLibraryExampleSpec/Props.h | 29 -- .../OSSLibraryExampleSpec/ShadowNodes.cpp | 17 - .../OSSLibraryExampleSpec/ShadowNodes.h | 32 -- .../OSSLibraryExampleSpec/States.cpp | 16 - .../components/OSSLibraryExampleSpec/States.h | 29 -- .../react-native-test-library/babel.config.js | 18 -- packages/react-native-test-library/index.js | 16 - .../ComponentDescriptors.cpp | 22 -- .../ComponentDescriptors.h | 24 -- .../OSSLibraryExampleSpec/EventEmitters.cpp | 95 ------ .../ios/OSSLibraryExampleSpec/EventEmitters.h | 49 --- .../OSSLibraryExampleSpec-generated.mm | 29 -- .../OSSLibraryExampleSpec.h | 49 --- .../ios/OSSLibraryExampleSpec/Props.cpp | 26 -- .../ios/OSSLibraryExampleSpec/Props.h | 29 -- .../RCTComponentViewHelpers.h | 50 --- .../ios/OSSLibraryExampleSpec/ShadowNodes.cpp | 17 - .../ios/OSSLibraryExampleSpec/ShadowNodes.h | 32 -- .../ios/OSSLibraryExampleSpec/States.cpp | 16 - .../ios/OSSLibraryExampleSpec/States.h | 29 -- .../OSSLibraryExampleSpecJSI-generated.cpp | 26 -- .../ios/OSSLibraryExampleSpecJSI.h | 67 ---- .../ios/RCTNativeSampleModule.mm | 47 --- .../RCTSampleNativeComponentComponentView.mm | 139 -------- .../RCTSampleNativeComponentViewManager.mm | 72 ----- .../react-native-test-library/package.json | 54 ---- .../react-native.config.js | 19 -- .../src/NativeSampleModule.js | 19 -- .../src/SampleNativeComponent.js | 59 ---- packages/rn-tester/Podfile | 1 - packages/rn-tester/Podfile.lock | 304 ++++++++++++------ .../react/uiapp/RNTesterApplication.kt | 2 - .../OSSLibraryExample/OSSLibraryExample.js | 130 -------- .../js/utils/RNTesterList.android.js | 4 - .../rn-tester/js/utils/RNTesterList.ios.js | 4 - packages/rn-tester/metro.config.js | 1 - packages/rn-tester/package.json | 1 - 59 files changed, 197 insertions(+), 2202 deletions(-) delete mode 100644 packages/react-native-test-library/OSSLibraryExample.podspec delete mode 100644 packages/react-native-test-library/README.md delete mode 100644 packages/react-native-test-library/android/build.gradle.kts delete mode 100644 packages/react-native-test-library/android/gradle.properties delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/fbreact/specs/NativeSampleModuleSpec.java delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/NativeSampleModule.kt delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeComponentViewManager.kt delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeView.kt delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerDelegate.java delete mode 100644 packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerInterface.java delete mode 100644 packages/react-native-test-library/android/src/main/jni/CMakeLists.txt delete mode 100644 packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec-generated.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI-generated.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.h delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.cpp delete mode 100644 packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.h delete mode 100644 packages/react-native-test-library/babel.config.js delete mode 100644 packages/react-native-test-library/index.js delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec-generated.mm delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/RCTComponentViewHelpers.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.h delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI-generated.cpp delete mode 100644 packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI.h delete mode 100644 packages/react-native-test-library/ios/RCTNativeSampleModule.mm delete mode 100644 packages/react-native-test-library/ios/RCTSampleNativeComponentComponentView.mm delete mode 100644 packages/react-native-test-library/ios/RCTSampleNativeComponentViewManager.mm delete mode 100644 packages/react-native-test-library/package.json delete mode 100644 packages/react-native-test-library/react-native.config.js delete mode 100644 packages/react-native-test-library/src/NativeSampleModule.js delete mode 100644 packages/react-native-test-library/src/SampleNativeComponent.js delete mode 100644 packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js diff --git a/.gitignore b/.gitignore index b48711db9cfd8b..2adc014b63ff97 100644 --- a/.gitignore +++ b/.gitignore @@ -43,7 +43,6 @@ project.xcworkspace /private/helloworld/android/app/build/ /private/helloworld/android/build/ /packages/react-native-popup-menu-android/android/build/ -/packages/react-native-test-library/android/build/ # Buck .buckd diff --git a/packages/react-native-test-library/OSSLibraryExample.podspec b/packages/react-native-test-library/OSSLibraryExample.podspec deleted file mode 100644 index 232273917fd080..00000000000000 --- a/packages/react-native-test-library/OSSLibraryExample.podspec +++ /dev/null @@ -1,24 +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. - -require 'json' - -package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) - -Pod::Spec.new do |s| - s.name = 'OSSLibraryExample' - s.version = package['version'] - s.summary = package['description'] - s.description = package['description'] - s.homepage = package['homepage'] - s.license = package['license'] - s.platforms = min_supported_versions - s.author = 'Meta Platforms, Inc. and its affiliates' - s.source = { :git => package['repository']['url'], :tag => "#{s.version}" } - - s.source_files = 'ios/**/*.{h,m,mm,cpp}' - - install_modules_dependencies(s) -end diff --git a/packages/react-native-test-library/README.md b/packages/react-native-test-library/README.md deleted file mode 100644 index 77df8a6791b313..00000000000000 --- a/packages/react-native-test-library/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Important -This package is for testing only. It is a subject to frequent change. It does not represent the recomended structure for React native libraries. It should not be used as a referece for such purposes. - -## Building -``` -yarn install -yarn build -npx react-native codegen -``` diff --git a/packages/react-native-test-library/android/build.gradle.kts b/packages/react-native-test-library/android/build.gradle.kts deleted file mode 100644 index 903c15d07affbe..00000000000000 --- a/packages/react-native-test-library/android/build.gradle.kts +++ /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. - */ - -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.osslibraryexample" - - defaultConfig { minSdk = libs.versions.minSdk.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-test-library/android/gradle.properties b/packages/react-native-test-library/android/gradle.properties deleted file mode 100644 index 92a0f87956c8c7..00000000000000 --- a/packages/react-native-test-library/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ - -# 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-test-library/android/src/main/java/com/facebook/fbreact/specs/NativeSampleModuleSpec.java b/packages/react-native-test-library/android/src/main/java/com/facebook/fbreact/specs/NativeSampleModuleSpec.java deleted file mode 100644 index 94148064208997..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/fbreact/specs/NativeSampleModuleSpec.java +++ /dev/null @@ -1,37 +0,0 @@ - -/** - * 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: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -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.turbomodule.core.interfaces.TurboModule; -import javax.annotation.Nonnull; - -public abstract class NativeSampleModuleSpec extends ReactContextBaseJavaModule implements TurboModule { - public static final String NAME = "NativeSampleModule"; - - public NativeSampleModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @Override - public @Nonnull String getName() { - return NAME; - } - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract double getRandomNumber(); -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/NativeSampleModule.kt b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/NativeSampleModule.kt deleted file mode 100644 index 1304ded97845bd..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/NativeSampleModule.kt +++ /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. - */ - -package com.facebook.react.osslibraryexample - -import com.facebook.fbreact.specs.NativeSampleModuleSpec -import com.facebook.react.bridge.ReactApplicationContext -import com.facebook.react.bridge.ReactContextBaseJavaModule -import com.facebook.react.bridge.ReactMethod -import com.facebook.react.module.annotations.ReactModule - -@ReactModule(name = NativeSampleModuleSpec.NAME) -public class NativeSampleModule(reactContext: ReactApplicationContext?) : - ReactContextBaseJavaModule(reactContext) { - - override fun getName(): String = NAME - - private companion object { - const val NAME = "NativeSampleModule" - } - - @ReactMethod - public fun getRandomNumber(): Int { - return (0..99).random() - } -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt deleted file mode 100644 index 428cd61ed9e621..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/OSSLibraryExamplePackage.kt +++ /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. - */ - -package com.facebook.react.osslibraryexample - -import com.facebook.react.ReactPackage -import com.facebook.react.bridge.NativeModule -import com.facebook.react.bridge.ReactApplicationContext -import com.facebook.react.uimanager.ViewManager - -@Suppress("DEPRECATION") -public class OSSLibraryExamplePackage : ReactPackage { - @Deprecated("Migrate to [BaseReactPackage] and implement [getModule] instead.") - override fun createNativeModules(reactContext: ReactApplicationContext): List = - listOf(NativeSampleModule(reactContext)) - - override fun createViewManagers(reactContext: ReactApplicationContext): List> = - listOf(SampleNativeComponentViewManager()) -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeComponentViewManager.kt b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeComponentViewManager.kt deleted file mode 100644 index 3ab92ac3bd8cb1..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeComponentViewManager.kt +++ /dev/null @@ -1,105 +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.osslibraryexample - -import android.annotation.SuppressLint -import android.graphics.Color -import com.facebook.react.bridge.ReadableArray -import com.facebook.react.module.annotations.ReactModule -import com.facebook.react.uimanager.SimpleViewManager -import com.facebook.react.uimanager.ThemedReactContext -import com.facebook.react.uimanager.ViewProps -import com.facebook.react.uimanager.annotations.ReactProp -import com.facebook.react.viewmanagers.SampleNativeComponentManagerInterface - -/** Legacy View manager (non Fabric compatible) for {@link SampleNativeView} components. */ -@ReactModule(name = SampleNativeComponentViewManager.REACT_CLASS) -internal class SampleNativeComponentViewManager : - SimpleViewManager(), SampleNativeComponentManagerInterface { - - override fun getName(): String = REACT_CLASS - - // @ReactProp(name = ViewProps.OPACITY, defaultFloat = 1f) - override fun setOpacity(view: SampleNativeView, opacity: Float) { - super.setOpacity(view, opacity) - } - - @SuppressLint("BadMethodUse-android.view.View.setBackgroundColor") - @ReactProp(name = ViewProps.COLOR) - fun setColor(view: SampleNativeView, color: String) { - view.setBackgroundColor(Color.parseColor(color)) - } - - @ReactProp(name = "cornerRadius") - fun setCornerRadius(view: SampleNativeView, cornerRadius: Float) { - view.setCornerRadius(cornerRadius) - } - - override fun createViewInstance(reactContext: ThemedReactContext): SampleNativeView = - SampleNativeView(reactContext) - - @SuppressLint("BadMethodUse-android.view.View.setBackgroundColor") - override fun changeBackgroundColor(view: SampleNativeView, color: String) { - view.setBackgroundColor(Color.parseColor(color)) - } - - override fun getExportedViewConstants(): Map = mapOf("PI" to 3.14) - - override fun getExportedCustomBubblingEventTypeConstants(): Map { - return mapOf( - "onColorChanged" to - mapOf( - "phasedRegistrationNames" to - mapOf( - "bubbled" to "onColorChanged", - "captured" to "onColorChangedCapture", - )), - "topIntArrayChanged" to - mapOf( - "phasedRegistrationNames" to - mapOf( - "bubbled" to "topIntArrayChanged", - "captured" to "topIntArrayChangedCapture", - ))) - } - - @SuppressLint("BadMethodUse-android.view.View.setBackgroundColor") - override fun receiveCommand(view: SampleNativeView, commandId: String, args: ReadableArray?) { - if (commandId.contentEquals("changeBackgroundColor")) { - val sentColor: Int = Color.parseColor(args?.getString(0)) - view.setBackgroundColor(sentColor) - } - } - - @Deprecated("Deprecated in Java") - @SuppressLint("BadMethodUse-android.view.View.setBackgroundColor") - @Suppress("DEPRECATION") // We intentionally want to test against the legacy API here. - override fun receiveCommand(view: SampleNativeView, commandId: Int, args: ReadableArray?) { - when (commandId) { - COMMAND_CHANGE_BACKGROUND_COLOR -> { - val sentColor: Int = Color.parseColor(args?.getString(0)) - view.setBackgroundColor(sentColor) - } - } - } - - override fun getCommandsMap(): Map = - mapOf("changeBackgroundColor" to COMMAND_CHANGE_BACKGROUND_COLOR) - - companion object { - const val REACT_CLASS = "SampleNativeComponent" - const val COMMAND_CHANGE_BACKGROUND_COLOR = 42 - } - - @ReactProp(name = "values") - override fun setValues(view: SampleNativeView, value: ReadableArray?) { - val values = mutableListOf() - value?.toArrayList()?.forEach { values.add((it as Double).toInt()) } - view.emitOnArrayChangedEvent(values) - } -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeView.kt b/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeView.kt deleted file mode 100644 index 3a4a8cf32f6342..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/osslibraryexample/SampleNativeView.kt +++ /dev/null @@ -1,97 +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.osslibraryexample - -import android.graphics.drawable.GradientDrawable -import android.view.View -import com.facebook.react.bridge.Arguments -import com.facebook.react.bridge.ReactContext -import com.facebook.react.bridge.WritableArray -import com.facebook.react.bridge.WritableMap -import com.facebook.react.uimanager.ThemedReactContext -import com.facebook.react.uimanager.UIManagerHelper -import com.facebook.react.uimanager.events.Event - -public class SampleNativeView(context: ThemedReactContext) : View(context) { - private var currentColor = 0 - private var background: GradientDrawable = GradientDrawable() - private val reactContext: ReactContext = context.reactApplicationContext - - override fun setBackgroundColor(color: Int) { - if (color != currentColor) { - background.setColor(color) - currentColor = color - setBackground(background) - } - } - - public fun setCornerRadius(cornerRadius: Float) { - background.cornerRadius = cornerRadius - setBackground(background) - } - - public fun emitOnArrayChangedEvent(ints: List) { - val newIntArray = Arguments.createArray() - val newBoolArray = Arguments.createArray() - val newFloatArray = Arguments.createArray() - val newDoubleArray = Arguments.createArray() - val newYesNoArray = Arguments.createArray() - val newStringArray = Arguments.createArray() - val newObjectArray = Arguments.createArray() - val newArrayArray = Arguments.createArray() - - for (i in ints) { - newIntArray.pushInt(i * 2) - newBoolArray.pushBoolean(i % 2 == 1) - newFloatArray.pushDouble(i * 3.14) - newDoubleArray.pushDouble(i / 3.14) - newYesNoArray.pushString(if (i % 2 == 1) "yep" else "nope") - newStringArray.pushString(i.toString()) - - val latLon = Arguments.createMap() - latLon.putDouble("lat", -1.0 * i) - latLon.putDouble("lon", 2.0 * i) - newObjectArray.pushMap(latLon) - - val innerArray: WritableArray = Arguments.createArray() - innerArray.pushInt(i) - innerArray.pushInt(i) - innerArray.pushInt(i) - newArrayArray.pushArray(innerArray) - } - - val payload = - Arguments.createMap().apply { - putArray("values", newIntArray) - putArray("boolValues", newBoolArray) - putArray("floats", newFloatArray) - putArray("doubles", newDoubleArray) - putArray("yesNos", newYesNoArray) - putArray("strings", newStringArray) - putArray("latLons", newObjectArray) - putArray("multiArrays", newArrayArray) - } - - val reactContext = context as ReactContext - val surfaceId = UIManagerHelper.getSurfaceId(reactContext) - val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id) - val event = OnIntArrayChangedEvent(surfaceId, id, payload) - - eventDispatcher?.dispatchEvent(event) - } - - private inner class OnIntArrayChangedEvent( - surfaceId: Int, - viewId: Int, - private val payload: WritableMap - ) : Event(surfaceId, viewId) { - override fun getEventName() = "topIntArrayChanged" - - override fun getEventData() = payload - } -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerDelegate.java b/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerDelegate.java deleted file mode 100644 index bb5b9b5273607f..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerDelegate.java +++ /dev/null @@ -1,45 +0,0 @@ -/** -* 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.BaseViewManager; -import com.facebook.react.uimanager.LayoutShadowNode; - -public class SampleNativeComponentManagerDelegate & SampleNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public SampleNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case "opacity": - mViewManager.setOpacity(view, value == null ? 0f : ((Double) value).floatValue()); - break; - case "values": - mViewManager.setValues(view, (ReadableArray) value); - break; - default: - super.setProperty(view, propName, value); - } - } - - @Override - public void receiveCommand(T view, String commandName, @Nullable ReadableArray args) { - switch (commandName) { - case "changeBackgroundColor": - mViewManager.changeBackgroundColor(view, args.getString(0)); - break; - } - } -} diff --git a/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerInterface.java b/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerInterface.java deleted file mode 100644 index 576aec6af7cf7e..00000000000000 --- a/packages/react-native-test-library/android/src/main/java/com/facebook/react/viewmanagers/SampleNativeComponentManagerInterface.java +++ /dev/null @@ -1,21 +0,0 @@ -/** -* 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; -import com.facebook.react.uimanager.ViewManagerWithGeneratedInterface; - -public interface SampleNativeComponentManagerInterface extends ViewManagerWithGeneratedInterface { - void setOpacity(T view, float value); - void setValues(T view, @Nullable ReadableArray value); - void changeBackgroundColor(T view, String color); -} diff --git a/packages/react-native-test-library/android/src/main/jni/CMakeLists.txt b/packages/react-native-test-library/android/src/main/jni/CMakeLists.txt deleted file mode 100644 index 1d9a3091aefbf3..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/CMakeLists.txt +++ /dev/null @@ -1,26 +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) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/OSSLibraryExampleSpec/*.cpp) - -add_library( - react_codegen_OSSLibraryExampleSpec - OBJECT - ${react_codegen_SRCS} -) - -target_include_directories(react_codegen_OSSLibraryExampleSpec PUBLIC . react/renderer/components/OSSLibraryExampleSpec) - -target_link_libraries( - react_codegen_OSSLibraryExampleSpec - fbjni - jsi - reactnative -) - -target_compile_reactnative_options(react_codegen_OSSLibraryExampleSpec PRIVATE) diff --git a/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec-generated.cpp b/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec-generated.cpp deleted file mode 100644 index b940af418aa7a2..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec-generated.cpp +++ /dev/null @@ -1,32 +0,0 @@ - -/** - * 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: GenerateModuleJniCpp.js - */ - -#include "OSSLibraryExampleSpec.h" - -namespace facebook::react { - -static facebook::jsi::Value __hostFunction_NativeSampleModuleSpecJSI_getRandomNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, NumberKind, "getRandomNumber", "()D", args, count, cachedMethodId); -} - -NativeSampleModuleSpecJSI::NativeSampleModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_["getRandomNumber"] = MethodMetadata {0, __hostFunction_NativeSampleModuleSpecJSI_getRandomNumber}; -} - -std::shared_ptr OSSLibraryExampleSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == "NativeSampleModule") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec.h b/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec.h deleted file mode 100644 index 6d39f6b6de3dbf..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/OSSLibraryExampleSpec.h +++ /dev/null @@ -1,31 +0,0 @@ - -/** - * 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: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -/** - * JNI C++ class for module 'NativeSampleModule' - */ -class JSI_EXPORT NativeSampleModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr OSSLibraryExampleSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.cpp deleted file mode 100644 index 385369e4c052a3..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.cpp +++ /dev/null @@ -1,22 +0,0 @@ - -/** - * 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: GenerateComponentDescriptorCpp.js - */ - -#include "ComponentDescriptors.h" -#include -#include - -namespace facebook::react { - -void OSSLibraryExampleSpec_registerComponentDescriptorsFromCodegen( - std::shared_ptr registry) { -registry->add(concreteComponentDescriptorProvider()); -} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.h deleted file mode 100644 index eac078b81d9d74..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ComponentDescriptors.h +++ /dev/null @@ -1,24 +0,0 @@ - -/** - * 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 -#include - -namespace facebook::react { - -using SampleNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -void OSSLibraryExampleSpec_registerComponentDescriptorsFromCodegen( - std::shared_ptr registry); - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.cpp deleted file mode 100644 index c5746ac5306da6..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.cpp +++ /dev/null @@ -1,95 +0,0 @@ - -/** - * 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 SampleNativeComponentEventEmitter::onIntArrayChanged(OnIntArrayChanged $event) const { - dispatchEvent("intArrayChanged", [$event=std::move($event)](jsi::Runtime &runtime) { - auto $payload = jsi::Object(runtime); - - auto values = jsi::Array(runtime, $event.values.size()); - size_t valuesIndex = 0; - for (auto valuesValue : $event.values) { - values.setValueAtIndex(runtime, valuesIndex++, valuesValue); - } - $payload.setProperty(runtime, "values", values); - - - auto boolValues = jsi::Array(runtime, $event.boolValues.size()); - size_t boolValuesIndex = 0; - for (auto boolValuesValue : $event.boolValues) { - boolValues.setValueAtIndex(runtime, boolValuesIndex++, (bool)boolValuesValue); - } - $payload.setProperty(runtime, "boolValues", boolValues); - - - auto floats = jsi::Array(runtime, $event.floats.size()); - size_t floatsIndex = 0; - for (auto floatsValue : $event.floats) { - floats.setValueAtIndex(runtime, floatsIndex++, floatsValue); - } - $payload.setProperty(runtime, "floats", floats); - - - auto doubles = jsi::Array(runtime, $event.doubles.size()); - size_t doublesIndex = 0; - for (auto doublesValue : $event.doubles) { - doubles.setValueAtIndex(runtime, doublesIndex++, doublesValue); - } - $payload.setProperty(runtime, "doubles", doubles); - - - auto yesNos = jsi::Array(runtime, $event.yesNos.size()); - size_t yesNosIndex = 0; - for (auto yesNosValue : $event.yesNos) { - yesNos.setValueAtIndex(runtime, yesNosIndex++, toString(yesNosValue)); - } - $payload.setProperty(runtime, "yesNos", yesNos); - - - auto strings = jsi::Array(runtime, $event.strings.size()); - size_t stringsIndex = 0; - for (auto stringsValue : $event.strings) { - strings.setValueAtIndex(runtime, stringsIndex++, stringsValue); - } - $payload.setProperty(runtime, "strings", strings); - - - auto latLons = jsi::Array(runtime, $event.latLons.size()); - size_t latLonsIndex = 0; - for (auto latLonsValue : $event.latLons) { - auto latLonsObject = jsi::Object(runtime); - latLonsObject.setProperty(runtime, "lat", latLonsValue.lat); -latLonsObject.setProperty(runtime, "lon", latLonsValue.lon); - latLons.setValueAtIndex(runtime, latLonsIndex++, latLonsObject); - } - $payload.setProperty(runtime, "latLons", latLons); - - - auto multiArrays = jsi::Array(runtime, $event.multiArrays.size()); - size_t multiArraysIndex = 0; - for (auto multiArraysValue : $event.multiArrays) { - auto multiArraysArray = jsi::Array(runtime, multiArraysValue.size()); - size_t multiArraysIndexInternal = 0; - for (auto multiArraysValueInternal : multiArraysValue) { - multiArraysArray.setValueAtIndex(runtime, multiArraysIndexInternal++, multiArraysValueInternal); - } - multiArrays.setValueAtIndex(runtime, multiArraysIndex++, multiArraysArray); - } - $payload.setProperty(runtime, "multiArrays", multiArrays); - - return $payload; - }); -} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.h deleted file mode 100644 index bfb9cc27ae82e1..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/EventEmitters.h +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * 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 SampleNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - enum class OnIntArrayChangedYesNos { - Yep, - Nope - }; - - static char const *toString(const OnIntArrayChangedYesNos value) { - switch (value) { - case OnIntArrayChangedYesNos::Yep: return "yep"; - case OnIntArrayChangedYesNos::Nope: return "nope"; - } - } - - struct OnIntArrayChangedLatLons { - double lat; - double lon; - }; - - struct OnIntArrayChanged { - std::vector values; - std::vector boolValues; - std::vector floats; - std::vector doubles; - std::vector yesNos; - std::vector strings; - std::vector latLons; - std::vector> multiArrays; - }; - void onIntArrayChanged(OnIntArrayChanged value) const; -}; -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI-generated.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI-generated.cpp deleted file mode 100644 index fc734d9e6f30e6..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI-generated.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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: GenerateModuleCpp.js - */ - -#include "OSSLibraryExampleSpecJSI.h" - -namespace facebook::react { - -static jsi::Value __hostFunction_NativeSampleModuleCxxSpecJSI_getRandomNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getRandomNumber( - rt - ); -} - -NativeSampleModuleCxxSpecJSI::NativeSampleModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule("NativeSampleModule", jsInvoker) { - methodMap_["getRandomNumber"] = MethodMetadata {0, __hostFunction_NativeSampleModuleCxxSpecJSI_getRandomNumber}; -} - - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI.h deleted file mode 100644 index c19f8f089d3815..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/OSSLibraryExampleSpecJSI.h +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 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: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - - - class JSI_EXPORT NativeSampleModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual double getRandomNumber(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeSampleModuleCxxSpec : public TurboModule { -public: - jsi::Value create(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.create(rt, propName); - } - - static constexpr std::string_view kModuleName = "NativeSampleModule"; - -protected: - NativeSampleModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(std::string{NativeSampleModuleCxxSpec::kModuleName}, jsInvoker), - delegate_(reinterpret_cast(this), jsInvoker) {} - - -private: - class Delegate : public NativeSampleModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) { - - } - - double getRandomNumber(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getRandomNumber) == 1, - "Expected getRandomNumber(...) to have 1 parameters"); - - return bridging::callFromJs( - rt, &T::getRandomNumber, jsInvoker_, instance_); - } - - private: - friend class NativeSampleModuleCxxSpec; - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.cpp deleted file mode 100644 index 595766f26bd083..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.cpp +++ /dev/null @@ -1,26 +0,0 @@ - -/** - * 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 { - -SampleNativeComponentProps::SampleNativeComponentProps( - const PropsParserContext &context, - const SampleNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - opacity(convertRawProp(context, rawProps, "opacity", sourceProps.opacity, {0.0})), - values(convertRawProp(context, rawProps, "values", sourceProps.values, {})) - {} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.h deleted file mode 100644 index fd7ad9642bcb22..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/Props.h +++ /dev/null @@ -1,29 +0,0 @@ - -/** - * 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 SampleNativeComponentProps final : public ViewProps { - public: - SampleNativeComponentProps() = default; - SampleNativeComponentProps(const PropsParserContext& context, const SampleNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Float opacity{0.0}; - std::vector values{}; -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.cpp deleted file mode 100644 index 790189cffd6e1e..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.cpp +++ /dev/null @@ -1,17 +0,0 @@ - -/** - * 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 SampleNativeComponentComponentName[] = "SampleNativeComponent"; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.h deleted file mode 100644 index 20b9db3837a1c7..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/ShadowNodes.h +++ /dev/null @@ -1,32 +0,0 @@ - -/** - * 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 SampleNativeComponentComponentName[]; - -/* - * `ShadowNode` for component. - */ -using SampleNativeComponentShadowNode = ConcreteViewShadowNode< - SampleNativeComponentComponentName, - SampleNativeComponentProps, - SampleNativeComponentEventEmitter, - SampleNativeComponentState>; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.cpp b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.cpp deleted file mode 100644 index 1dbb184cbddb62..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.cpp +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * 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-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.h b/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.h deleted file mode 100644 index 1cffd0cfe6dc9a..00000000000000 --- a/packages/react-native-test-library/android/src/main/jni/react/renderer/components/OSSLibraryExampleSpec/States.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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 RN_SERIALIZABLE_STATE -#include -#endif - -namespace facebook::react { - -class SampleNativeComponentState { -public: - SampleNativeComponentState() = default; - -#ifdef RN_SERIALIZABLE_STATE - SampleNativeComponentState(SampleNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; -#endif -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/babel.config.js b/packages/react-native-test-library/babel.config.js deleted file mode 100644 index 87d86f0b5a5e54..00000000000000 --- a/packages/react-native-test-library/babel.config.js +++ /dev/null @@ -1,18 +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 - * @noflow - */ - -module.exports = { - presets: [ - [ - 'module:@react-native/babel-preset', - {disableStaticViewConfigsCodegen: false}, - ], - ], -}; diff --git a/packages/react-native-test-library/index.js b/packages/react-native-test-library/index.js deleted file mode 100644 index 7e033cab5a6d15..00000000000000 --- a/packages/react-native-test-library/index.js +++ /dev/null @@ -1,16 +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 - */ - -export {default as SampleNativeComponent} from './src/SampleNativeComponent'; -export type {NativeComponentType} from './src/SampleNativeComponent'; -import {Commands as SampleNativeComponentCommands} from './src/SampleNativeComponent'; - -export {SampleNativeComponentCommands}; -export {default as NativeSampleModule} from './src/NativeSampleModule'; diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.cpp deleted file mode 100644 index 385369e4c052a3..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.cpp +++ /dev/null @@ -1,22 +0,0 @@ - -/** - * 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: GenerateComponentDescriptorCpp.js - */ - -#include "ComponentDescriptors.h" -#include -#include - -namespace facebook::react { - -void OSSLibraryExampleSpec_registerComponentDescriptorsFromCodegen( - std::shared_ptr registry) { -registry->add(concreteComponentDescriptorProvider()); -} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.h deleted file mode 100644 index eac078b81d9d74..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ComponentDescriptors.h +++ /dev/null @@ -1,24 +0,0 @@ - -/** - * 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 -#include - -namespace facebook::react { - -using SampleNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -void OSSLibraryExampleSpec_registerComponentDescriptorsFromCodegen( - std::shared_ptr registry); - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.cpp deleted file mode 100644 index c5746ac5306da6..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.cpp +++ /dev/null @@ -1,95 +0,0 @@ - -/** - * 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 SampleNativeComponentEventEmitter::onIntArrayChanged(OnIntArrayChanged $event) const { - dispatchEvent("intArrayChanged", [$event=std::move($event)](jsi::Runtime &runtime) { - auto $payload = jsi::Object(runtime); - - auto values = jsi::Array(runtime, $event.values.size()); - size_t valuesIndex = 0; - for (auto valuesValue : $event.values) { - values.setValueAtIndex(runtime, valuesIndex++, valuesValue); - } - $payload.setProperty(runtime, "values", values); - - - auto boolValues = jsi::Array(runtime, $event.boolValues.size()); - size_t boolValuesIndex = 0; - for (auto boolValuesValue : $event.boolValues) { - boolValues.setValueAtIndex(runtime, boolValuesIndex++, (bool)boolValuesValue); - } - $payload.setProperty(runtime, "boolValues", boolValues); - - - auto floats = jsi::Array(runtime, $event.floats.size()); - size_t floatsIndex = 0; - for (auto floatsValue : $event.floats) { - floats.setValueAtIndex(runtime, floatsIndex++, floatsValue); - } - $payload.setProperty(runtime, "floats", floats); - - - auto doubles = jsi::Array(runtime, $event.doubles.size()); - size_t doublesIndex = 0; - for (auto doublesValue : $event.doubles) { - doubles.setValueAtIndex(runtime, doublesIndex++, doublesValue); - } - $payload.setProperty(runtime, "doubles", doubles); - - - auto yesNos = jsi::Array(runtime, $event.yesNos.size()); - size_t yesNosIndex = 0; - for (auto yesNosValue : $event.yesNos) { - yesNos.setValueAtIndex(runtime, yesNosIndex++, toString(yesNosValue)); - } - $payload.setProperty(runtime, "yesNos", yesNos); - - - auto strings = jsi::Array(runtime, $event.strings.size()); - size_t stringsIndex = 0; - for (auto stringsValue : $event.strings) { - strings.setValueAtIndex(runtime, stringsIndex++, stringsValue); - } - $payload.setProperty(runtime, "strings", strings); - - - auto latLons = jsi::Array(runtime, $event.latLons.size()); - size_t latLonsIndex = 0; - for (auto latLonsValue : $event.latLons) { - auto latLonsObject = jsi::Object(runtime); - latLonsObject.setProperty(runtime, "lat", latLonsValue.lat); -latLonsObject.setProperty(runtime, "lon", latLonsValue.lon); - latLons.setValueAtIndex(runtime, latLonsIndex++, latLonsObject); - } - $payload.setProperty(runtime, "latLons", latLons); - - - auto multiArrays = jsi::Array(runtime, $event.multiArrays.size()); - size_t multiArraysIndex = 0; - for (auto multiArraysValue : $event.multiArrays) { - auto multiArraysArray = jsi::Array(runtime, multiArraysValue.size()); - size_t multiArraysIndexInternal = 0; - for (auto multiArraysValueInternal : multiArraysValue) { - multiArraysArray.setValueAtIndex(runtime, multiArraysIndexInternal++, multiArraysValueInternal); - } - multiArrays.setValueAtIndex(runtime, multiArraysIndex++, multiArraysArray); - } - $payload.setProperty(runtime, "multiArrays", multiArrays); - - return $payload; - }); -} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.h deleted file mode 100644 index bfb9cc27ae82e1..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/EventEmitters.h +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * 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 SampleNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - enum class OnIntArrayChangedYesNos { - Yep, - Nope - }; - - static char const *toString(const OnIntArrayChangedYesNos value) { - switch (value) { - case OnIntArrayChangedYesNos::Yep: return "yep"; - case OnIntArrayChangedYesNos::Nope: return "nope"; - } - } - - struct OnIntArrayChangedLatLons { - double lat; - double lon; - }; - - struct OnIntArrayChanged { - std::vector values; - std::vector boolValues; - std::vector floats; - std::vector doubles; - std::vector yesNos; - std::vector strings; - std::vector latLons; - std::vector> multiArrays; - }; - void onIntArrayChanged(OnIntArrayChanged value) const; -}; -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec-generated.mm b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec-generated.mm deleted file mode 100644 index faf7056af985a4..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec-generated.mm +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import "OSSLibraryExampleSpec.h" - - -namespace facebook::react { - - static facebook::jsi::Value __hostFunction_NativeSampleModuleSpecJSI_getRandomNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, "getRandomNumber", @selector(getRandomNumber), args, count); - } - - NativeSampleModuleSpecJSI::NativeSampleModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_["getRandomNumber"] = MethodMetadata {0, __hostFunction_NativeSampleModuleSpecJSI_getRandomNumber}; - - } -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec.h deleted file mode 100644 index 1ff5010b13fced..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/OSSLibraryExampleSpec.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif - -// Avoid multiple includes of OSSLibraryExampleSpec symbols -#ifndef OSSLibraryExampleSpec_H -#define OSSLibraryExampleSpec_H - -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -@protocol NativeSampleModuleSpec - -- (NSNumber *)getRandomNumber; - -@end -namespace facebook::react { - /** - * ObjC++ class for module 'NativeSampleModule' - */ - class JSI_EXPORT NativeSampleModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; -} // namespace facebook::react - -#endif // OSSLibraryExampleSpec_H diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.cpp deleted file mode 100644 index 595766f26bd083..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.cpp +++ /dev/null @@ -1,26 +0,0 @@ - -/** - * 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 { - -SampleNativeComponentProps::SampleNativeComponentProps( - const PropsParserContext &context, - const SampleNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - opacity(convertRawProp(context, rawProps, "opacity", sourceProps.opacity, {0.0})), - values(convertRawProp(context, rawProps, "values", sourceProps.values, {})) - {} - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.h deleted file mode 100644 index fd7ad9642bcb22..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/Props.h +++ /dev/null @@ -1,29 +0,0 @@ - -/** - * 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 SampleNativeComponentProps final : public ViewProps { - public: - SampleNativeComponentProps() = default; - SampleNativeComponentProps(const PropsParserContext& context, const SampleNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Float opacity{0.0}; - std::vector values{}; -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/RCTComponentViewHelpers.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/RCTComponentViewHelpers.h deleted file mode 100644 index d6e5a3531eedff..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/RCTComponentViewHelpers.h +++ /dev/null @@ -1,50 +0,0 @@ -/** -* 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: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTSampleNativeComponentViewProtocol -- (void)changeBackgroundColor:(NSString *)color; -@end - -RCT_EXTERN inline void RCTSampleNativeComponentHandleCommand( - id componentView, - NSString const *commandName, - NSArray const *args) -{ - if ([commandName isEqualToString:@"changeBackgroundColor"]) { -#if RCT_DEBUG - if ([args count] != 1) { - RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"SampleNativeComponent", commandName, (int)[args count], 1); - return; - } -#endif - - NSObject *arg0 = args[0]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"SampleNativeComponent", commandName, @"1st")) { - return; - } -#endif - NSString * color = (NSString *)arg0; - - [componentView changeBackgroundColor:color]; - return; -} - -#if RCT_DEBUG - RCTLogError(@"%@ received command %@, which is not a supported command.", @"SampleNativeComponent", commandName); -#endif -} - -NS_ASSUME_NONNULL_END \ No newline at end of file diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.cpp deleted file mode 100644 index 790189cffd6e1e..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.cpp +++ /dev/null @@ -1,17 +0,0 @@ - -/** - * 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 SampleNativeComponentComponentName[] = "SampleNativeComponent"; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.h deleted file mode 100644 index 20b9db3837a1c7..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/ShadowNodes.h +++ /dev/null @@ -1,32 +0,0 @@ - -/** - * 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 SampleNativeComponentComponentName[]; - -/* - * `ShadowNode` for component. - */ -using SampleNativeComponentShadowNode = ConcreteViewShadowNode< - SampleNativeComponentComponentName, - SampleNativeComponentProps, - SampleNativeComponentEventEmitter, - SampleNativeComponentState>; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.cpp deleted file mode 100644 index 1dbb184cbddb62..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.cpp +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * 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-test-library/ios/OSSLibraryExampleSpec/States.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.h deleted file mode 100644 index 1cffd0cfe6dc9a..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpec/States.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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 RN_SERIALIZABLE_STATE -#include -#endif - -namespace facebook::react { - -class SampleNativeComponentState { -public: - SampleNativeComponentState() = default; - -#ifdef RN_SERIALIZABLE_STATE - SampleNativeComponentState(SampleNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; -#endif -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI-generated.cpp b/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI-generated.cpp deleted file mode 100644 index fc734d9e6f30e6..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI-generated.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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: GenerateModuleCpp.js - */ - -#include "OSSLibraryExampleSpecJSI.h" - -namespace facebook::react { - -static jsi::Value __hostFunction_NativeSampleModuleCxxSpecJSI_getRandomNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getRandomNumber( - rt - ); -} - -NativeSampleModuleCxxSpecJSI::NativeSampleModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule("NativeSampleModule", jsInvoker) { - methodMap_["getRandomNumber"] = MethodMetadata {0, __hostFunction_NativeSampleModuleCxxSpecJSI_getRandomNumber}; -} - - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI.h b/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI.h deleted file mode 100644 index c19f8f089d3815..00000000000000 --- a/packages/react-native-test-library/ios/OSSLibraryExampleSpecJSI.h +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 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: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook::react { - - - class JSI_EXPORT NativeSampleModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual double getRandomNumber(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeSampleModuleCxxSpec : public TurboModule { -public: - jsi::Value create(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.create(rt, propName); - } - - static constexpr std::string_view kModuleName = "NativeSampleModule"; - -protected: - NativeSampleModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(std::string{NativeSampleModuleCxxSpec::kModuleName}, jsInvoker), - delegate_(reinterpret_cast(this), jsInvoker) {} - - -private: - class Delegate : public NativeSampleModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) { - - } - - double getRandomNumber(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getRandomNumber) == 1, - "Expected getRandomNumber(...) to have 1 parameters"); - - return bridging::callFromJs( - rt, &T::getRandomNumber, jsInvoker_, instance_); - } - - private: - friend class NativeSampleModuleCxxSpec; - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace facebook::react diff --git a/packages/react-native-test-library/ios/RCTNativeSampleModule.mm b/packages/react-native-test-library/ios/RCTNativeSampleModule.mm deleted file mode 100644 index b5a059b7f6e61a..00000000000000 --- a/packages/react-native-test-library/ios/RCTNativeSampleModule.mm +++ /dev/null @@ -1,47 +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. - */ - -#ifdef RCT_NEW_ARCH_ENABLED -#import "OSSLibraryExampleSpec/OSSLibraryExampleSpec.h" -#else -#import -#endif - -#import -#include -#include - -#ifdef RCT_NEW_ARCH_ENABLED -@interface RCTNativeSampleModule : NSObject -#else -@interface RCTNativeSampleModule : NSObject -#endif - -@end - -@implementation RCTNativeSampleModule - -RCT_EXPORT_MODULE(); - -#ifdef RCT_NEW_ARCH_ENABLED -- (std::shared_ptr)getTurboModule: - (const facebook::react::ObjCTurboModule::InitParams &)params -{ - return std::make_shared(params); -} -#endif - -#ifdef RCT_NEW_ARCH_ENABLED -- (NSNumber *)getRandomNumber -#else -RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSNumber *, getRandomNumber) -#endif -{ - return @(arc4random_uniform(99)); -} - -@end diff --git a/packages/react-native-test-library/ios/RCTSampleNativeComponentComponentView.mm b/packages/react-native-test-library/ios/RCTSampleNativeComponentComponentView.mm deleted file mode 100644 index 13dca042838eab..00000000000000 --- a/packages/react-native-test-library/ios/RCTSampleNativeComponentComponentView.mm +++ /dev/null @@ -1,139 +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. - */ - -#import "OSSLibraryExampleSpec/ComponentDescriptors.h" -#import "OSSLibraryExampleSpec/EventEmitters.h" -#import "OSSLibraryExampleSpec/Props.h" -#import "OSSLibraryExampleSpec/RCTComponentViewHelpers.h" - -#import "RCTFabricComponentsPlugins.h" - -#import -#import -#import - -using namespace facebook::react; - -static UIColor *UIColorFromHexString(const std::string hexString) -{ - unsigned rgbValue = 0; - NSString *colorString = [NSString stringWithCString:hexString.c_str() encoding:[NSString defaultCStringEncoding]]; - NSScanner *scanner = [NSScanner scannerWithString:colorString]; - [scanner setScanLocation:1]; // bypass '#' character - [scanner scanHexInt:&rgbValue]; - return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 - green:((rgbValue & 0xFF00) >> 8) / 255.0 - blue:(rgbValue & 0xFF) / 255.0 - alpha:1.0]; -} - -@interface RCTSampleNativeComponentComponentView : RCTViewComponentView - -@property (nonatomic, copy) RCTBubblingEventBlock onIntArrayChanged; - -@end - -@implementation RCTSampleNativeComponentComponentView { - UIView *_view; -} - -+ (ComponentDescriptorProvider)componentDescriptorProvider -{ - return concreteComponentDescriptorProvider(); -} - -// Load is not invoked if it is not defined, therefore, we must ask to update this. -// See the Apple documentation: https://developer.apple.com/documentation/objectivec/nsobject/1418815-load?language=objc -// "[...] but only if the newly loaded class or category implements a method that can respond." -+ (void)load -{ - [super load]; -} - -- (instancetype)initWithFrame:(CGRect)frame -{ - if (self = [super initWithFrame:frame]) { - static const auto defaultProps = std::make_shared(); - _props = defaultProps; - - _view = [[UIView alloc] init]; - _view.backgroundColor = [UIColor redColor]; - - self.contentView = _view; - } - - return self; -} - -- (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &)oldProps -{ - const auto &oldViewProps = *std::static_pointer_cast(_props); - const auto &newViewProps = *std::static_pointer_cast(props); - - if (oldViewProps.values != newViewProps.values) { - if (_eventEmitter) { - std::vector newVector = {}; - std::vector newBoolVector = {}; - std::vector newFloatVector = {}; - std::vector newDoubleVector = {}; - std::vector newYesNoVector = {}; - std::vector newStringVector = {}; - std::vector newLatLonVector = {}; - std::vector> newIntVectorVector = {}; - for (auto val : newViewProps.values) { - newVector.push_back(val * 2); - newBoolVector.push_back(val % 2 ? true : false); - newFloatVector.push_back(val * 3.14); - newDoubleVector.push_back(val / 3.14); - newYesNoVector.push_back( - val % 2 ? SampleNativeComponentEventEmitter::OnIntArrayChangedYesNos::Yep - : SampleNativeComponentEventEmitter::OnIntArrayChangedYesNos::Nope); - newStringVector.push_back(std::to_string(val)); - newLatLonVector.push_back({-1.0 * val, 2.0 * val}); - newIntVectorVector.push_back({val, val, val}); - } - SampleNativeComponentEventEmitter::OnIntArrayChanged value = { - newVector, - newBoolVector, - newFloatVector, - newDoubleVector, - newYesNoVector, - newStringVector, - newLatLonVector, - newIntVectorVector}; - std::static_pointer_cast(_eventEmitter)->onIntArrayChanged(value); - } - } - - [super updateProps:props oldProps:oldProps]; -} - -- (void)onChange:(UIView *)sender -{ - // No-op - // std::dynamic_pointer_cast(_eventEmitter) - // ->onChange(ViewEventEmitter::OnChange{.value = static_cast(sender.on)}); -} - -#pragma mark - Native Commands - -- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args -{ - RCTSampleNativeComponentHandleCommand(self, commandName, args); -} - -- (void)changeBackgroundColor:(NSString *)color -{ - _view.backgroundColor = UIColorFromHexString(std::string(color.UTF8String)); -} - -@end - -Class SampleNativeComponentCls(void) -{ - return RCTSampleNativeComponentComponentView.class; -} diff --git a/packages/react-native-test-library/ios/RCTSampleNativeComponentViewManager.mm b/packages/react-native-test-library/ios/RCTSampleNativeComponentViewManager.mm deleted file mode 100644 index 809812602093b5..00000000000000 --- a/packages/react-native-test-library/ios/RCTSampleNativeComponentViewManager.mm +++ /dev/null @@ -1,72 +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. - */ - -#import -#import -#import - -#import - -static UIColor *UIColorFromHexString(const std::string hexString) -{ - unsigned rgbValue = 0; - NSString *colorString = [NSString stringWithCString:hexString.c_str() encoding:[NSString defaultCStringEncoding]]; - NSScanner *scanner = [NSScanner scannerWithString:colorString]; - [scanner setScanLocation:1]; // bypass '#' character - [scanner scanHexInt:&rgbValue]; - return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 - green:((rgbValue & 0xFF00) >> 8) / 255.0 - blue:(rgbValue & 0xFF) / 255.0 - alpha:1.0]; -} - -@interface RCTSampleNativeComponentViewManager : RCTViewManager -@end - -@implementation RCTSampleNativeComponentViewManager - -RCT_EXPORT_MODULE(SampleNativeComponent) - -RCT_REMAP_VIEW_PROPERTY(color, backgroundColor, UIColor) - -RCT_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) - -RCT_EXPORT_VIEW_PROPERTY(onColorChanged, RCTBubblingEventBlock) - -RCT_CUSTOM_VIEW_PROPERTY(cornerRadius, CGFloat, UIView) -{ - view.clipsToBounds = true; - NSNumber *cornerRadius = (NSNumber *)json; - view.layer.cornerRadius = [cornerRadius floatValue]; -} - -RCT_EXPORT_METHOD(changeBackgroundColor : (nonnull NSNumber *)reactTag color : (NSString *)color) -{ - [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { - if (UIView *view = [RCTSampleNativeComponentViewManager getViewByTag:viewRegistry reactTag:reactTag]) { - view.backgroundColor = UIColorFromHexString(std::string(color.UTF8String)); - } - }]; -} - -+ (UIView *)getViewByTag:(NSDictionary *)viewRegistry reactTag:(nonnull NSNumber *)reactTag -{ - UIView *view = viewRegistry[reactTag]; - if (view == nil) { - RCTLogError(@"Cannot find view with tag #%@", reactTag); - } - return view; -} - -- (UIView *)view -{ - UIView *view = [UIView new]; - view.backgroundColor = UIColor.redColor; - return view; -} - -@end diff --git a/packages/react-native-test-library/package.json b/packages/react-native-test-library/package.json deleted file mode 100644 index e3cc74d743aa6c..00000000000000 --- a/packages/react-native-test-library/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@react-native/oss-library-example", - "version": "0.82.0-main", - "private": true, - "description": "Package that includes native module exapmle, native component example, targets both the old and the new architecture. It should serve as an example of a real-world OSS library.", - "license": "MIT", - "homepage": "https://github.com/facebook/react-native.git", - "repository": { - "type": "git", - "url": "https://github.com/facebook/react-native.git", - "directory": "packages/react-native-test-library" - }, - "main": "./index.js", - "exports": { - ".": "./index.js", - "./package.json": "./package.json" - }, - "scripts": { - "build": "yarn clean && babel --out-dir lib src", - "clean": "rimraf lib", - "codegen": "npx react-native codegen", - "prepare": "yarn run codegen && yarn run build" - }, - "files": [ - "generated" - ], - "devDependencies": { - "@babel/core": "^7.25.2", - "@react-native/babel-preset": "0.82.0-main", - "react-native": "1000.0.0" - }, - "peerDependencies": { - "react": "*", - "react-native": "*" - }, - "codegenConfig": { - "name": "OSSLibraryExampleSpec", - "type": "all", - "jsSrcsDir": "src", - "outputDir": { - "ios": "ios", - "android": "android/src/main" - }, - "includesGeneratedCode": true, - "android": { - "javaPackageName": "com.reactnative.osslibraryexample" - }, - "ios": { - "componentProvider": { - "SampleNativeComponent": "RCTSampleNativeComponentComponentView" - } - } - } -} diff --git a/packages/react-native-test-library/react-native.config.js b/packages/react-native-test-library/react-native.config.js deleted file mode 100644 index 5301f495f7d6cc..00000000000000 --- a/packages/react-native-test-library/react-native.config.js +++ /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. - * - * @format - * @noflow - */ - -module.exports = { - dependency: { - platforms: { - android: { - cmakeListsPath: '../android/src/main/jni/CMakeLists.txt', - }, - }, - }, -}; diff --git a/packages/react-native-test-library/src/NativeSampleModule.js b/packages/react-native-test-library/src/NativeSampleModule.js deleted file mode 100644 index de546b74e53d62..00000000000000 --- a/packages/react-native-test-library/src/NativeSampleModule.js +++ /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. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; - -import {TurboModuleRegistry} from 'react-native'; - -export interface Spec extends TurboModule { - +getRandomNumber: () => number; -} - -export default (TurboModuleRegistry.get('NativeSampleModule'): ?Spec); diff --git a/packages/react-native-test-library/src/SampleNativeComponent.js b/packages/react-native-test-library/src/SampleNativeComponent.js deleted file mode 100644 index 854db39f005afd..00000000000000 --- a/packages/react-native-test-library/src/SampleNativeComponent.js +++ /dev/null @@ -1,59 +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 - */ - -import type {HostComponent} from 'react-native'; -import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes'; -import type { - BubblingEventHandler, - Double, - Float, - Int32, -} from 'react-native/Libraries/Types/CodegenTypes'; - -import * as React from 'react'; -import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands'; -import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent'; - -type Event = $ReadOnly<{ - values: $ReadOnlyArray, - boolValues: $ReadOnlyArray, - floats: $ReadOnlyArray, - doubles: $ReadOnlyArray, - yesNos: $ReadOnlyArray<'yep' | 'nope'>, - strings: $ReadOnlyArray, - latLons: $ReadOnlyArray<{lat: Double, lon: Double}>, - multiArrays: $ReadOnlyArray<$ReadOnlyArray>, -}>; - -type NativeProps = $ReadOnly<{ - ...ViewProps, - opacity?: Float, - values: $ReadOnlyArray, - - // Events - onIntArrayChanged?: ?BubblingEventHandler, -}>; - -export type NativeComponentType = HostComponent; - -interface NativeCommands { - +changeBackgroundColor: ( - viewRef: React.ElementRef, - color: string, - ) => void; -} - -export const Commands: NativeCommands = codegenNativeCommands({ - supportedCommands: ['changeBackgroundColor'], -}); - -export default (codegenNativeComponent( - 'SampleNativeComponent', -): NativeComponentType); diff --git a/packages/rn-tester/Podfile b/packages/rn-tester/Podfile index e35ee5883ad777..dae3a107f6bb3b 100644 --- a/packages/rn-tester/Podfile +++ b/packages/rn-tester/Podfile @@ -54,7 +54,6 @@ def pods(target_name, options = {}) pod 'ScreenshotManager', :path => "NativeModuleExample" pod 'MyNativeView', :path => "NativeComponentExample" pod 'NativeCxxModuleExample', :path => "NativeCxxModuleExample" - pod 'OSSLibraryExample', :path => '../react-native-test-library' end target 'RNTester' do diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index 2a568e1874e6b4..43235e7bc09192 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -16,7 +16,7 @@ PODS: - hermes-engine/inspector (1000.0.0) - hermes-engine/inspector_chrome (1000.0.0) - hermes-engine/Public (1000.0.0) - - MyNativeView (0.80.0-main): + - MyNativeView (0.81.0-main): - boost - DoubleConversion - fast_float @@ -44,7 +44,7 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga - - NativeCxxModuleExample (0.80.0-main): + - NativeCxxModuleExample (0.81.0-main): - boost - DoubleConversion - fast_float @@ -73,34 +73,6 @@ PODS: - SocketRocket - Yoga - OCMock (3.9.4) - - OSSLibraryExample (0.80.0-main): - - boost - - DoubleConversion - - fast_float - - fmt - - glog - - hermes-engine - - RCT-Folly - - RCT-Folly/Fabric - - RCTRequired - - RCTTypeSafety - - React-Core - - React-debug - - React-Fabric - - React-featureflags - - React-graphics - - React-ImageManager - - React-jsi - - React-NativeModulesApple - - React-RCTFabric - - React-renderercss - - React-rendererdebug - - React-utils - - ReactCodegen - - ReactCommon/turbomodule/bridging - - ReactCommon/turbomodule/core - - SocketRocket - - Yoga - RCT-Folly (2024.11.18.00): - boost - DoubleConversion @@ -584,6 +556,7 @@ PODS: - RCT-Folly - RCT-Folly/Fabric - React-Fabric + - React-Fabric/bridging - React-FabricComponents - React-graphics - React-jsi @@ -609,6 +582,7 @@ PODS: - React-debug - React-Fabric/animations (= 1000.0.0) - React-Fabric/attributedstring (= 1000.0.0) + - React-Fabric/bridging (= 1000.0.0) - React-Fabric/componentregistry (= 1000.0.0) - React-Fabric/componentregistrynative (= 1000.0.0) - React-Fabric/components (= 1000.0.0) @@ -684,6 +658,31 @@ PODS: - React-utils - ReactCommon/turbomodule/core - SocketRocket + - React-Fabric/bridging (1000.0.0): + - boost + - DoubleConversion + - fast_float + - fmt + - glog + - hermes-engine + - RCT-Folly + - RCT-Folly/Fabric + - RCTRequired + - RCTTypeSafety + - React-Core + - React-cxxreact + - React-debug + - React-featureflags + - React-graphics + - React-jsi + - React-jsiexecutor + - React-logger + - React-rendererdebug + - React-runtimeexecutor + - React-runtimescheduler + - React-utils + - ReactCommon/turbomodule/core + - SocketRocket - React-Fabric/componentregistry (1000.0.0): - boost - DoubleConversion @@ -1243,11 +1242,14 @@ PODS: - React-FabricComponents/components/inputaccessory (= 1000.0.0) - React-FabricComponents/components/iostextinput (= 1000.0.0) - React-FabricComponents/components/modal (= 1000.0.0) + - React-FabricComponents/components/rncore (= 1000.0.0) - React-FabricComponents/components/safeareaview (= 1000.0.0) - React-FabricComponents/components/scrollview (= 1000.0.0) - React-FabricComponents/components/text (= 1000.0.0) - React-FabricComponents/components/textinput (= 1000.0.0) - React-FabricComponents/components/unimplementedview (= 1000.0.0) + - React-FabricComponents/components/virtualview (= 1000.0.0) + - React-FabricComponents/components/virtualviewexperimental (= 1000.0.0) - React-featureflags - React-graphics - React-jsi @@ -1341,6 +1343,33 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga + - React-FabricComponents/components/rncore (1000.0.0): + - boost + - DoubleConversion + - fast_float + - fmt + - glog + - hermes-engine + - RCT-Folly + - RCT-Folly/Fabric + - RCTRequired + - RCTTypeSafety + - React-Core + - React-cxxreact + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-jsi + - React-jsiexecutor + - React-logger + - React-RCTFBReactNativeSpec + - React-rendererdebug + - React-runtimescheduler + - React-utils + - ReactCommon/turbomodule/core + - SocketRocket + - Yoga - React-FabricComponents/components/safeareaview (1000.0.0): - boost - DoubleConversion @@ -1476,6 +1505,60 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga + - React-FabricComponents/components/virtualview (1000.0.0): + - boost + - DoubleConversion + - fast_float + - fmt + - glog + - hermes-engine + - RCT-Folly + - RCT-Folly/Fabric + - RCTRequired + - RCTTypeSafety + - React-Core + - React-cxxreact + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-jsi + - React-jsiexecutor + - React-logger + - React-RCTFBReactNativeSpec + - React-rendererdebug + - React-runtimescheduler + - React-utils + - ReactCommon/turbomodule/core + - SocketRocket + - Yoga + - React-FabricComponents/components/virtualviewexperimental (1000.0.0): + - boost + - DoubleConversion + - fast_float + - fmt + - glog + - hermes-engine + - RCT-Folly + - RCT-Folly/Fabric + - RCTRequired + - RCTTypeSafety + - React-Core + - React-cxxreact + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-jsi + - React-jsiexecutor + - React-logger + - React-RCTFBReactNativeSpec + - React-rendererdebug + - React-runtimescheduler + - React-utils + - ReactCommon/turbomodule/core + - SocketRocket + - Yoga - React-FabricComponents/textlayoutmanager (1000.0.0): - boost - DoubleConversion @@ -2122,7 +2205,18 @@ PODS: - React-utils - SocketRocket - React-runtimeexecutor (1000.0.0): + - boost + - DoubleConversion + - fast_float + - fmt + - glog + - RCT-Folly + - RCT-Folly/Fabric + - React-debug + - React-featureflags - React-jsi (= 1000.0.0) + - React-utils + - SocketRocket - React-RuntimeHermes (1000.0.0): - boost - DoubleConversion @@ -2283,7 +2377,7 @@ PODS: - React-perflogger (= 1000.0.0) - React-utils (= 1000.0.0) - SocketRocket - - ScreenshotManager (0.80.0-main): + - ScreenshotManager (0.81.0-main): - boost - DoubleConversion - fast_float @@ -2325,7 +2419,6 @@ DEPENDENCIES: - MyNativeView (from `NativeComponentExample`) - NativeCxxModuleExample (from `NativeCxxModuleExample`) - OCMock (~> 3.9.1) - - OSSLibraryExample (from `../react-native-test-library`) - RCT-Folly (from `../react-native/third-party-podspecs/RCT-Folly.podspec`) - RCTDeprecation (from `../react-native/ReactApple/Libraries/RCTFoundation/RCTDeprecation`) - RCTRequired (from `../react-native/Libraries/Required`) @@ -2422,8 +2515,6 @@ EXTERNAL SOURCES: :path: NativeComponentExample NativeCxxModuleExample: :path: NativeCxxModuleExample - OSSLibraryExample: - :path: "../react-native-test-library" RCT-Folly: :podspec: "../react-native/third-party-podspecs/RCT-Folly.podspec" RCTDeprecation: @@ -2565,84 +2656,83 @@ SPEC CHECKSUMS: boost: 7e761d76ca2ce687f7cc98e698152abd03a18f90 DoubleConversion: cb417026b2400c8f53ae97020b2be961b59470cb fast_float: b32c788ed9c6a8c584d114d0047beda9664e7cc6 - FBLazyVector: d3c2dd739a63c1a124e775df075dc7c517a719cb + FBLazyVector: a67ac982f94e725e28eb5fdf00ae785a88fee122 fmt: a40bb5bd0294ea969aaaba240a927bd33d878cdd glog: 5683914934d5b6e4240e497e0f4a3b42d1854183 - hermes-engine: fd5605ca4043c8317548d649d0b64e5dafc2a124 - MyNativeView: 9b03b64f5cd9220bf7ef49fcdfc468effe704fa0 - NativeCxxModuleExample: 2897d5f3aee8a02dd201a3dd41fbc94ada1aac5e + hermes-engine: 3350cd88070588a0c3ebf47ea6f81ba28c7aaf9f + MyNativeView: f9ac5b43a4d23e7d40f2e7c4337b40fc98f645cc + NativeCxxModuleExample: 9abb81d71be6898827e6c0bb65b1715f6f3b75a2 OCMock: 589f2c84dacb1f5aaf6e4cec1f292551fe748e74 - OSSLibraryExample: bf5b5a4238613dae3c536faff58f87528e6191cf - RCT-Folly: 846fda9475e61ec7bcbf8a3fe81edfcaeb090669 + RCT-Folly: 59ec0ac1f2f39672a0c6e6cecdd39383b764646f RCTDeprecation: 3808e36294137f9ee5668f4df2e73dc079cd1dcf - RCTRequired: a00614e2da5344c2cda3d287050b6cee00e21dc6 - RCTTypeSafety: 459a16418c6b413060d35434ba3e83f5b0bd2651 - React: 170a01a19ba2525ab7f11243e2df6b19bf268093 - React-callinvoker: f08f425e4043cd1998a158b6e39a6aed1fd1d718 - React-Core: d35c5cf69898fd026e5cd93a0454b1d42e999d3e - React-CoreModules: 3ce1d43f6cc37f43759ec543ce1c0010080f1de1 - React-cxxreact: 3169b106af8f405e182d131d3a0844201e3252e2 - React-debug: 195df38487d3f48a7af04deddeb4a5c6d4440416 - React-defaultsnativemodule: 8afea5a4bd07addb523bf48489b8a684ea1bdff0 - React-domnativemodule: 8a813559774e65bc800fe489bbb454cd546f21d7 - React-Fabric: e9846203f11ab49be8b1329c76301bbd399ef2ad - React-FabricComponents: 032d6f01f1d6966633418c0fece18f698ddb7897 - React-FabricImage: 264c9ce5241e43e25b94c8de55ac6c3c8a046472 - React-featureflags: 595651ea13c63a9f77f06d9a1973b665b4a28b7e - React-featureflagsnativemodule: 06823479a2ee210cfa0e9c19447c2722a8d995f2 - React-graphics: 1f99b9b5515eac389f0cf9c85b03abc366d6a933 - React-hermes: 745eb45a6d0aae7e890d0aae0def54670bbd103c - React-idlecallbacksnativemodule: 4e65f183318b8a0fbabc481a4eafc0f0d62d1cbf - React-ImageManager: a6833445e17879933378b7c0ba45ee42115c14bc - React-jserrorhandler: bec134a192c50338193544404d45df24fb8a19ca - React-jsi: 4ad77650fb0ca4229569eb2532db7a87e3d12662 - React-jsiexecutor: fa5b80bdbe1ceffc33a892da20fc07b4dfa4df7a - React-jsinspector: 10b5dc4eef2a3d05b80be2114ed676496c5bf59c - React-jsinspectorcdp: 5fb266e5f23d3a2819ba848e9d4d0b6b00f95934 - React-jsinspectornetwork: 1655a81f3fe14789df41e063bd56dd130cc3562a - React-jsinspectortracing: 5b0be488e06958a572e1badfe8509929ae1cc83b - React-jsitooling: 9e563b89f94cf4baf872fe47105d60ae83f4ce4d - React-jsitracing: ce443686f52538d1033ce7db1e7d643e866262f0 - React-logger: 116c3ae5a9906671d157aa00882a5ee75a5a7ebc - React-Mapbuffer: fc937cfa41140d7724c559c3d16c50dd725361c8 - React-microtasksnativemodule: 09899c7389250279bdcc5384f0281bb069979855 - React-NativeModulesApple: d05b718ccd8b68c184e76dbc1efb63385197595b - React-oscompat: 7133e0e945cda067ae36b22502df663d73002864 - React-perflogger: ada3cdf3dfc8b7cd1fabe3c91b672e23981611ab - React-performancetimeline: e7d5849d89ee39557dcd56dfb6e7b0d49003d925 - React-RCTActionSheet: 1bf8cc8086ad1c15da3407dfb7bc9dd94dc7595d - React-RCTAnimation: 263593e66c89bf810604b1ace15dfa382a1ca2df - React-RCTAppDelegate: 3a99437ffa7460f85045de65f9bed6b1c47d5f09 - React-RCTBlob: 7b76230c53fe87d305eeeb250b0aae031bb6cbae - React-RCTFabric: 2fd2ef899c7219fd39fd61c39750510f88a81434 - React-RCTFBReactNativeSpec: 4ed3b463eb26726b04ac65c73797207ecab5634c - React-RCTImage: de404b6b0ebe53976a97e3a0dee819c83e12977b - React-RCTLinking: 06742cfad41c506091403a414370743a4ed75af3 - React-RCTNetwork: b4577eec0092c16d8996e415e4cac7a372d6d362 - React-RCTPushNotification: ea11178d499696516e0ff9ae335edbe99b06f94b - React-RCTRuntime: 925039e78fc530e0421c308ccc607f214f3c7be1 - React-RCTSettings: d3c2dd305ec81f7faf42762ec598d57f07fd43be - React-RCTTest: 2db46eda60bc2228cb67622a580e8e86b00088d9 - React-RCTText: e416825b80c530647040ef91d23ffd35ccc87981 - React-RCTVibration: 1837a27fc16eeffc9509779c3334fde54c012bcc - React-rendererconsistency: 777c894edc43dde01499189917ac54ee76ae6a6a - React-renderercss: a9cb6ba7f49a80dc4b4f7008bae1590d12f27049 - React-rendererdebug: fea8bde927403a198742b2d940a5f1cd8230c0b4 - React-RuntimeApple: 6a0c164a8855edb4987b90da2d4d8601302de72d - React-RuntimeCore: 6dec37113b759b76641bd028bfbbbec8cf923356 - React-runtimeexecutor: a16a24b964e964afe833a652d703e1bb39f10dc9 - React-RuntimeHermes: d4f661204d3061219a63951eb4efed4dcaf3f12f - React-runtimescheduler: ae44fe8b4170a9d59f62e8b7d7b060c179db739d - React-timing: 9d49179631e5e3c759e6e82d4c613c73da80a144 - React-utils: 0944df8d553d66b27f486282c42a84a969fd2f6c - ReactAppDependencyProvider: 68f2d2cefd6c9b9f2865246be2bfe86ebd49238d - ReactCodegen: 8fc4c8b6562a59409b5650e67f78719093d093bf - ReactCommon: a53973ab35d399560ace331ec9e2b26db0592cec - ReactCommon-Samples: dcc128cbf51ac38d2578791750d0a046d1b8a5e9 - ScreenshotManager: 6ac0b11c7bbd5cf1abd9448fb3b856fe6fd65ff7 + RCTRequired: 2122b76857162ff9aa7e211de2575089ffe611d6 + RCTTypeSafety: cda30ca2aadf5786d66ba137b5c06d2190e697e9 + React: 662099b139948fd652fa9dc369f2a6aece1e18b2 + React-callinvoker: 49a5a4449dbb4830fdac6341be9027ebf8ffc3bf + React-Core: 7e0f44e57d0dc4a814c1be194e8667ca6ee052b7 + React-CoreModules: a82c6f0d605188a1261b020b4c43cd5c39a9e57f + React-cxxreact: bec05af5ce328afa9428fafa6d33730400e4b68c + React-debug: 40cbf9f72c96613c639f12f7fcc9a6cb8d54f588 + React-defaultsnativemodule: 68c0affa6e5c4de5db8352aac0ff53eeace95035 + React-domnativemodule: b9dc5b7141dbfb65e53039aa708f342c24ca2d30 + React-Fabric: 15cced8cd4c50826215448b633362106dcfb98d4 + React-FabricComponents: f6ef214976c812eb2bb59f8e9d10f4ada46ffe12 + React-FabricImage: 32b54b2b17d61df7b22a0ff8b78b57de1245a588 + React-featureflags: d2a5f1ee99706701567ad6ffacfefe54bf839813 + React-featureflagsnativemodule: 722fa94f9d7ac24632df7d178b845c77ac794d36 + React-graphics: aae15c16655f51e02f4ba211f108bb591d02f82a + React-hermes: afd04a013d8e73fcea46019a38724097d410c53c + React-idlecallbacksnativemodule: fdb1f69e1725303cd2fb302c6c104b117871dabc + React-ImageManager: c2119408bc90c98b037eb418855eac8484b79987 + React-jserrorhandler: 710e7a368c42914e44a9065ad0f878286511c181 + React-jsi: 6b6955a311c687ce2560fac466ed7ea6ae1ba851 + React-jsiexecutor: a1837ded1bd224b94d57e36ee72bd26299cb0624 + React-jsinspector: 99852440c65d84257ed9bb1a9f6a943ab3b2dc53 + React-jsinspectorcdp: 51b7b9e98f69a5f43a200286e0f1809b8be2e7d6 + React-jsinspectornetwork: 31c2d9f486c87f670ae8d76c5eee606995e9a994 + React-jsinspectortracing: af188edab74f98d132a4170013a4073f13e02323 + React-jsitooling: c16793498697b5bf00b2b5245529f5ad1bd7dc03 + React-jsitracing: 1e5621e281f794777dd6933960b63b4001ff6688 + React-logger: 6be7039c28299972c00f0b326591085037f2224b + React-Mapbuffer: c7da77a5d048ec7d7e1e050b3f946551241a768c + React-microtasksnativemodule: 394af907fa98cc28f993ed949975c6f4d3d53f5f + React-NativeModulesApple: 15bfbf94f0a1286ee7bf4fe0b0d3e8a04a9a3f26 + React-oscompat: 496762720e2a4dd97786fa08f788e3f8763404ea + React-perflogger: 64a1b6eac6ff95474c02c3ee1734c8752a7a1da8 + React-performancetimeline: 5bfcaa23bc90980d8cc4f0d4dd92e08fbdd10638 + React-RCTActionSheet: fda681f38788c81040b6e0aebd7050580d5fd74d + React-RCTAnimation: 983a1257c6ca45998848a2129d1ea9ada70824a6 + React-RCTAppDelegate: 15a4c95028249abb71d2769b9d5ec158ce81a9f8 + React-RCTBlob: 8986952d547b4c81e2827f7dfa9d8457b36c673b + React-RCTFabric: 511cc7ff0f99c790330855d20ce7e7a7d28f548a + React-RCTFBReactNativeSpec: b4a3bfa2a45af3dcdba1cd13285a7b5c7da29b21 + React-RCTImage: e4fa15c647802b7ed6c7e405d40db829e2146d02 + React-RCTLinking: dc1cc3b29036a58f7c828d1ca0a6b24ea7801a97 + React-RCTNetwork: dffe5f8de5ea63ba22baace02df4b84438e09986 + React-RCTPushNotification: 4d8081e9d2c636469b7098e137ff39d141643a18 + React-RCTRuntime: 0abb761a26d449eacfdd47f378ae365b830076c8 + React-RCTSettings: 9ba77f0aebce1bf71582ee8845db723b264039f6 + React-RCTTest: 09f99c5f8b2e5e00b9fa6b796ae81fd162843b2d + React-RCTText: 58b4e7484e6ce4903e5a9333c9fb744b84b16a05 + React-RCTVibration: b65dc9f78e1c5d482599205e4a52ec33815c7a1c + React-rendererconsistency: 0d60f7275a5f39b37c3753d548e72186562c3a48 + React-renderercss: 88f92ff8dc85711a2ff861f815876cf8e312fe49 + React-rendererdebug: fa30da9cdff3556e43a29c5fd5468faee8615850 + React-RuntimeApple: 415a26184ba8fc6cf372f39d351665b73f0ceeaf + React-RuntimeCore: a875f3c5479b1fc07ca3ae0c0797c623baf6516e + React-runtimeexecutor: 344502ff6d944ae095379ee587cea61720812751 + React-RuntimeHermes: 8e0734f0dd51840d957bc2f5216ea84a599dad03 + React-runtimescheduler: e3d95a3e38dd7c30b1faffdd808cf915fec0c991 + React-timing: 1c3682ededd5ab4158b7f065404b9c493d1f97f9 + React-utils: 99cab5ff9f585e8f6d57d97f35d2d38e1d51b4b7 + ReactAppDependencyProvider: b3db1f6073cd2d5085705f812a6eef258aa9a9d7 + ReactCodegen: 17ffed80c08ee934120f5962a19c8cdae62615f9 + ReactCommon: 8135b5504e1ddab9348bb09a7e6c829eb1b21bc6 + ReactCommon-Samples: 0fc23e4c63e23897cc41f2f6867f5358e7e60806 + ScreenshotManager: 3b0059e34e3ac8ec152874e4ac9b7a304216ecca SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 - Yoga: c4e80f1c2235fa6236d71a49e5bb2ee74d987921 + Yoga: d4ae2f851e524b23cb324409594f60bc3f091403 -PODFILE CHECKSUM: 8591f96a513620a2a83a0b9a125ad3fa32ea1369 +PODFILE CHECKSUM: 995beda3236c2c76801e7a4efc7fedcd390220e6 COCOAPODS: 1.15.2 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 05ca30df409d12..d3bf047cced87f 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 @@ -26,7 +26,6 @@ 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.osslibraryexample.OSSLibraryExamplePackage import com.facebook.react.popupmenu.PopupMenuPackage import com.facebook.react.shell.MainReactPackage import com.facebook.react.soloader.OpenSourceMergedSoMapping @@ -54,7 +53,6 @@ internal class RNTesterApplication : Application(), ReactApplication { return listOf( MainReactPackage(), PopupMenuPackage(), - OSSLibraryExamplePackage(), object : BaseReactPackage() { override fun getModule( name: String, diff --git a/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js b/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js deleted file mode 100644 index c7217a33c663c5..00000000000000 --- a/packages/rn-tester/js/examples/OSSLibraryExample/OSSLibraryExample.js +++ /dev/null @@ -1,130 +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 - * @format - */ - -'use strict'; - -import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; -import type {NativeComponentType} from '@react-native/oss-library-example'; - -import RNTesterText from '../../components/RNTesterText'; -import { - SampleNativeComponent, - SampleNativeComponentCommands, -} from '@react-native/oss-library-example'; -import {NativeSampleModule} from '@react-native/oss-library-example'; -import * as React from 'react'; -import {useRef, useState} from 'react'; -import {Button, View} from 'react-native'; -import {StyleSheet} from 'react-native'; - -const colors = [ - '#0000FF', - '#FF0000', - '#00FF00', - '#003300', - '#330000', - '#000033', -]; - -// $FlowFixMe[value-as-type] -const styles: StyleSheet = StyleSheet.create({ - container: { - flex: 1, - }, - column: { - flex: 2, - justifyContent: 'center', - paddingLeft: 5, - paddingRight: 5, - }, -}); - -function SampleNativeComponentContainer(props: {}): React.Node { - const ref = useRef | null>(null); - const [opacity, setOpacity] = useState(1.0); - const [arrayValues, setArrayValues] = useState([1, 2, 3]); - return ( - - { - console.log(event.nativeEvent.values); - console.log(event.nativeEvent.boolValues); - console.log(event.nativeEvent.floats); - console.log(event.nativeEvent.doubles); - console.log(event.nativeEvent.yesNos); - console.log(event.nativeEvent.strings); - console.log(event.nativeEvent.latLons); - console.log(event.nativeEvent.multiArrays); - }} - /> -