1*26ad19fcSEvan Bacon/**
2*26ad19fcSEvan Bacon * Copyright © 2022 650 Industries.
3*26ad19fcSEvan Bacon *
4*26ad19fcSEvan Bacon * This source code is licensed under the MIT license found in the
5*26ad19fcSEvan Bacon * LICENSE file in the root directory of this source tree.
6*26ad19fcSEvan Bacon */
7*26ad19fcSEvan Bacon
8*26ad19fcSEvan Baconimport { loadBundleAsync } from './loadBundle';
9*26ad19fcSEvan Bacon
10*26ad19fcSEvan Bacon/**
11*26ad19fcSEvan Bacon * Must satisfy the requirements of the Metro bundler.
12*26ad19fcSEvan Bacon * https://github.com/react-native-community/discussions-and-proposals/blob/main/proposals/0605-lazy-bundling.md#__loadbundleasync-in-metro
13*26ad19fcSEvan Bacon */
14*26ad19fcSEvan Bacontype AsyncRequire = (path: string) => Promise<void>;
15*26ad19fcSEvan Bacon
16*26ad19fcSEvan Bacon/** Create an `loadBundleAsync` function in the expected shape for Metro bundler. */
17*26ad19fcSEvan Baconexport function buildAsyncRequire(): AsyncRequire {
18*26ad19fcSEvan Bacon  const cache = new Map<string, Promise<void>>();
19*26ad19fcSEvan Bacon
20*26ad19fcSEvan Bacon  return async function universal_loadBundleAsync(path: string): Promise<void> {
21*26ad19fcSEvan Bacon    if (cache.has(path)) {
22*26ad19fcSEvan Bacon      return cache.get(path)!;
23*26ad19fcSEvan Bacon    }
24*26ad19fcSEvan Bacon
25*26ad19fcSEvan Bacon    const promise = loadBundleAsync(path).catch((error) => {
26*26ad19fcSEvan Bacon      cache.delete(path);
27*26ad19fcSEvan Bacon      throw error;
28*26ad19fcSEvan Bacon    });
29*26ad19fcSEvan Bacon
30*26ad19fcSEvan Bacon    cache.set(path, promise);
31*26ad19fcSEvan Bacon
32*26ad19fcSEvan Bacon    return promise;
33*26ad19fcSEvan Bacon  };
34*26ad19fcSEvan Bacon}
35