| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @flow |
| 8 | */ |
| 9 | |
| 10 | import type {HookSourceAndMetadata} from './loadSourceAndMetadata'; |
| 11 | import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks'; |
| 12 | import type {HookNames} from 'react-devtools-shared/src/frontend/types'; |
| 13 | import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext'; |
| 14 | |
| 15 | import 'react'; |
| 16 | |
| 17 | import {withAsyncPerfMeasurements} from 'react-devtools-shared/src/PerformanceLoggingUtils'; |
| 18 | import WorkerizedParseSourceAndMetadata from './parseSourceAndMetadata.worker'; |
| 19 | import typeof * as ParseSourceAndMetadataModule from './parseSourceAndMetadata'; |
| 20 | import {flattenHooksList, loadSourceAndMetadata} from './loadSourceAndMetadata'; |
| 21 | |
| 22 | const workerizedParseHookNames: ParseSourceAndMetadataModule = |
| 23 | WorkerizedParseSourceAndMetadata(); |
| 24 | |
| 25 | export function parseSourceAndMetadata( |
| 26 | hooksList: Array<HooksNode>, |
| 27 | locationKeyToHookSourceAndMetadata: Map<string, HookSourceAndMetadata>, |
| 28 | ): Promise<HookNames | null> { |
| 29 | return workerizedParseHookNames.parseSourceAndMetadata( |
| 30 | hooksList, |
| 31 | locationKeyToHookSourceAndMetadata, |
| 32 | ); |
| 33 | } |
| 34 | |
| 35 | export const purgeCachedMetadata = workerizedParseHookNames.purgeCachedMetadata; |
| 36 | |
| 37 | const EMPTY_MAP: HookNames = new Map(); |
| 38 | |
| 39 | export async function parseHookNames( |
| 40 | hooksTree: HooksTree, |
| 41 | fetchFileWithCaching: FetchFileWithCaching | null, |
| 42 | ): Promise<HookNames | null> { |
| 43 | return withAsyncPerfMeasurements('parseHookNames', async () => { |
| 44 | const hooksList = flattenHooksList(hooksTree); |
| 45 | if (hooksList.length === 0) { |
| 46 | // This component tree contains no named hooks. |
| 47 | return EMPTY_MAP; |
| 48 | } |
| 49 | |
| 50 | // Runs on the main/UI thread so it can reuse Network cache: |
| 51 | const locationKeyToHookSourceAndMetadata = await loadSourceAndMetadata( |
| 52 | hooksList, |
| 53 | fetchFileWithCaching, |
| 54 | ); |
| 55 | |
| 56 | // Runs in a Worker because it's CPU intensive: |
| 57 | return parseSourceAndMetadata( |
| 58 | hooksList, |
| 59 | locationKeyToHookSourceAndMetadata, |
| 60 | ); |
| 61 | }); |
| 62 | } |