metro 0.84.1 → 0.84.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/package.json +15 -15
  2. package/src/Assets.d.ts +90 -0
  3. package/src/Bundler/util.d.ts +34 -0
  4. package/src/Bundler/util.js.flow +3 -3
  5. package/src/Bundler.d.ts +45 -0
  6. package/src/DeltaBundler/DeltaCalculator.d.ts +68 -0
  7. package/src/DeltaBundler/DeltaCalculator.js +55 -46
  8. package/src/DeltaBundler/DeltaCalculator.js.flow +72 -61
  9. package/src/DeltaBundler/Graph.d.ts +174 -0
  10. package/src/DeltaBundler/Serializers/baseJSBundle.d.ts +27 -0
  11. package/src/DeltaBundler/Serializers/getAllFiles.d.ts +29 -0
  12. package/src/DeltaBundler/Serializers/getAssets.d.ts +32 -0
  13. package/src/DeltaBundler/Serializers/getExplodedSourceMap.d.ts +33 -0
  14. package/src/DeltaBundler/Serializers/getRamBundleInfo.d.ts +55 -0
  15. package/src/DeltaBundler/Serializers/helpers/getInlineSourceMappingURL.d.ts +19 -0
  16. package/src/DeltaBundler/Serializers/helpers/getSourceMapInfo.d.ts +40 -0
  17. package/src/DeltaBundler/Serializers/helpers/getTransitiveDependencies.d.ts +24 -0
  18. package/src/DeltaBundler/Serializers/helpers/js.d.ts +37 -0
  19. package/src/DeltaBundler/Serializers/helpers/processModules.d.ts +32 -0
  20. package/src/DeltaBundler/Serializers/hmrJSBundle.d.ts +37 -0
  21. package/src/DeltaBundler/Serializers/sourceMapGenerator.d.ts +36 -0
  22. package/src/DeltaBundler/Serializers/sourceMapObject.d.ts +30 -0
  23. package/src/DeltaBundler/Serializers/sourceMapString.d.ts +29 -0
  24. package/src/DeltaBundler/Transformer.d.ts +45 -0
  25. package/src/DeltaBundler/Worker.d.ts +44 -0
  26. package/src/DeltaBundler/WorkerFarm.d.ts +77 -0
  27. package/src/DeltaBundler/buildSubgraph.d.ts +37 -0
  28. package/src/DeltaBundler/getTransformCacheKey.d.ts +25 -0
  29. package/src/DeltaBundler/getTransformCacheKey.js +3 -1
  30. package/src/DeltaBundler/getTransformCacheKey.js.flow +7 -2
  31. package/src/DeltaBundler/mergeDeltas.d.ts +24 -0
  32. package/src/DeltaBundler/types.d.ts +170 -0
  33. package/src/DeltaBundler.d.ts +67 -0
  34. package/src/HmrServer.d.ts +98 -0
  35. package/src/HmrServer.js +7 -0
  36. package/src/HmrServer.js.flow +15 -5
  37. package/src/IncrementalBundler/GraphNotFoundError.d.ts +24 -0
  38. package/src/IncrementalBundler/ResourceNotFoundError.d.ts +22 -0
  39. package/src/IncrementalBundler/RevisionNotFoundError.d.ts +24 -0
  40. package/src/IncrementalBundler.d.ts +103 -0
  41. package/src/ModuleGraph/worker/JsFileWrapping.d.ts +36 -0
  42. package/src/ModuleGraph/worker/collectDependencies.d.ts +138 -0
  43. package/src/ModuleGraph/worker/generateImportNames.d.ts +26 -0
  44. package/src/ModuleGraph/worker/importLocationsPlugin.d.ts +33 -0
  45. package/src/Server/MultipartResponse.d.ts +37 -0
  46. package/src/Server/symbolicate.d.ts +38 -0
  47. package/src/Server.d.ts +278 -0
  48. package/src/cli/parseKeyValueParamArray.d.ts +21 -0
  49. package/src/cli-utils.d.ts +26 -0
  50. package/src/commands/build.d.ts +23 -0
  51. package/src/commands/dependencies.d.ts +23 -0
  52. package/src/commands/serve.d.ts +23 -0
  53. package/src/index.d.ts +206 -0
  54. package/src/index.flow.js.flow +21 -2
  55. package/src/lib/BatchProcessor.d.ts +61 -0
  56. package/src/lib/CountingSet.d.ts +55 -0
  57. package/src/lib/JsonReporter.d.ts +44 -0
  58. package/src/lib/JsonReporter.js.flow +2 -2
  59. package/src/lib/RamBundleParser.d.ts +36 -0
  60. package/src/lib/TerminalReporter.d.ts +125 -0
  61. package/src/lib/bundleProgressUtils.d.ts +33 -0
  62. package/src/lib/bundleToString.d.ts +26 -0
  63. package/src/lib/contextModule.d.ts +40 -0
  64. package/src/lib/contextModuleTemplates.d.ts +32 -0
  65. package/src/lib/countLines.d.ts +19 -0
  66. package/src/lib/createWebsocketServer.d.ts +50 -0
  67. package/src/lib/debounceAsyncQueue.d.ts +22 -0
  68. package/src/lib/formatBundlingError.d.ts +30 -0
  69. package/src/lib/getAppendScripts.d.ts +38 -0
  70. package/src/lib/getAppendScripts.js.flow +2 -2
  71. package/src/lib/getGraphId.d.ts +32 -0
  72. package/src/lib/getPreludeCode.d.ts +25 -0
  73. package/src/lib/getPrependedScripts.d.ts +31 -0
  74. package/src/lib/isResolvedDependency.d.ts +22 -0
  75. package/src/lib/logToConsole.d.ts +26 -0
  76. package/src/lib/parseBundleOptionsFromBundleRequestUrl.d.ts +24 -0
  77. package/src/lib/parseCustomResolverOptions.d.ts +23 -0
  78. package/src/lib/parseCustomTransformOptions.d.ts +23 -0
  79. package/src/lib/parseJsonBody.d.ts +34 -0
  80. package/src/lib/pathUtils.d.ts +21 -0
  81. package/src/lib/relativizeSourceMap.d.ts +24 -0
  82. package/src/lib/reporting.d.ts +135 -0
  83. package/src/lib/splitBundleOptions.d.ts +23 -0
  84. package/src/lib/transformHelpers.d.ts +42 -0
  85. package/src/node-haste/DependencyGraph/ModuleResolution.d.ts +120 -0
  86. package/src/node-haste/DependencyGraph/ModuleResolution.js +4 -22
  87. package/src/node-haste/DependencyGraph/ModuleResolution.js.flow +10 -59
  88. package/src/node-haste/DependencyGraph/createFileMap.d.ts +36 -0
  89. package/src/node-haste/DependencyGraph/createFileMap.js +1 -1
  90. package/src/node-haste/DependencyGraph/createFileMap.js.flow +4 -2
  91. package/src/node-haste/DependencyGraph.d.ts +90 -0
  92. package/src/node-haste/DependencyGraph.js +22 -11
  93. package/src/node-haste/DependencyGraph.js.flow +24 -13
  94. package/src/node-haste/PackageCache.d.ts +37 -0
  95. package/src/node-haste/PackageCache.js +65 -54
  96. package/src/node-haste/PackageCache.js.flow +103 -79
  97. package/src/node-haste/lib/AssetPaths.d.ts +36 -0
  98. package/src/node-haste/lib/parsePlatformFilePath.d.ts +32 -0
  99. package/src/shared/output/RamBundle/as-assets.d.ts +32 -0
  100. package/src/shared/output/RamBundle/as-indexed-file.d.ts +45 -0
  101. package/src/shared/output/RamBundle/buildSourcemapWithMetadata.d.ts +30 -0
  102. package/src/shared/output/RamBundle/magic-number.d.ts +21 -0
  103. package/src/shared/output/RamBundle/util.d.ts +48 -0
  104. package/src/shared/output/RamBundle/write-sourcemap.d.ts +23 -0
  105. package/src/shared/output/RamBundle.d.ts +33 -0
  106. package/src/shared/output/bundle.d.ts +34 -0
  107. package/src/shared/output/meta.d.ts +22 -0
  108. package/src/shared/output/unbundle.d.ts +18 -0
  109. package/src/shared/output/writeFile.d.ts +23 -0
  110. package/src/shared/types.d.ts +152 -0
  111. package/src/node-haste/Package.js +0 -28
  112. package/src/node-haste/Package.js.flow +0 -39
@@ -35,28 +35,7 @@ import util from 'util';
35
35
 
36
36
  export type DirExistsFn = (filePath: string) => boolean;
37
37
 
38
- export type Packageish = interface {
39
- path: string,
40
- read(): PackageJson,
41
- };
42
-
43
- export type Moduleish = interface {
44
- +path: string,
45
- };
46
-
47
- export type PackageishCache<TPackage> = interface {
48
- getPackage(
49
- name: string,
50
- platform?: string,
51
- supportsNativePlatform?: boolean,
52
- ): TPackage,
53
- getPackageOf(absolutePath: string): ?{
54
- pkg: TPackage,
55
- packageRelativePath: string,
56
- },
57
- };
58
-
59
- type Options<TPackage> = Readonly<{
38
+ type Options = Readonly<{
60
39
  assetExts: ReadonlySet<string>,
61
40
  dirExists: DirExistsFn,
62
41
  disableHierarchicalLookup: boolean,
@@ -67,7 +46,8 @@ type Options<TPackage> = Readonly<{
67
46
  getHasteModulePath: (name: string, platform: ?string) => ?string,
68
47
  getHastePackagePath: (name: string, platform: ?string) => ?string,
69
48
  mainFields: ReadonlyArray<string>,
70
- packageCache: PackageishCache<TPackage>,
49
+ getPackage: (packageJsonPath: string) => ?PackageJson,
50
+ getPackageForModule: (absolutePath: string) => ?PackageForModule,
71
51
  nodeModulesPaths: ReadonlyArray<string>,
72
52
  preferNativePlatform: boolean,
73
53
  projectRoot: string,
@@ -83,14 +63,14 @@ type Options<TPackage> = Readonly<{
83
63
  unstable_incrementalResolution: boolean,
84
64
  }>;
85
65
 
86
- export class ModuleResolver<TPackage: Packageish> {
87
- _options: Options<TPackage>;
66
+ export class ModuleResolver {
67
+ _options: Options;
88
68
  // A module representing the project root, used as the origin when resolving `emptyModulePath`.
89
69
  _projectRootFakeModulePath: string;
90
70
  // An empty module, the result of resolving `emptyModulePath` from the project root.
91
71
  _cachedEmptyModule: ?BundlerResolution;
92
72
 
93
- constructor(options: Options<TPackage>) {
73
+ constructor(options: Options) {
94
74
  this._options = options;
95
75
  const {projectRoot} = this._options;
96
76
  this._projectRootFakeModulePath = path.join(projectRoot, '_');
@@ -132,6 +112,8 @@ export class ModuleResolver<TPackage: Packageish> {
132
112
  doesFileExist,
133
113
  extraNodeModules,
134
114
  fileSystemLookup,
115
+ getPackage,
116
+ getPackageForModule,
135
117
  mainFields,
136
118
  nodeModulesPaths,
137
119
  preferNativePlatform,
@@ -156,9 +138,8 @@ export class ModuleResolver<TPackage: Packageish> {
156
138
  doesFileExist,
157
139
  extraNodeModules,
158
140
  fileSystemLookup,
159
- getPackage: this._getPackage,
160
- getPackageForModule: (absoluteModulePath: string) =>
161
- this._getPackageForModule(absoluteModulePath),
141
+ getPackage,
142
+ getPackageForModule,
162
143
  isESMImport: dependency.data.isESMImport,
163
144
  mainFields,
164
145
  nodeModulesPaths,
@@ -240,36 +221,6 @@ export class ModuleResolver<TPackage: Packageish> {
240
221
  }
241
222
  }
242
223
 
243
- _getPackage = (packageJsonPath: string): ?PackageJson => {
244
- try {
245
- return this._options.packageCache.getPackage(packageJsonPath).read();
246
- } catch (e) {
247
- // Do nothing. The standard module cache does not trigger any error, but
248
- // the ModuleGraph one does, if the module does not exist.
249
- }
250
-
251
- return null;
252
- };
253
-
254
- _getPackageForModule = (absolutePath: string): ?PackageForModule => {
255
- let result;
256
-
257
- try {
258
- result = this._options.packageCache.getPackageOf(absolutePath);
259
- } catch (e) {
260
- // Do nothing. The standard module cache does not trigger any error, but
261
- // the ModuleGraph one does, if the module does not exist.
262
- }
263
-
264
- return result != null
265
- ? {
266
- packageJson: result.pkg.read(),
267
- packageRelativePath: result.packageRelativePath,
268
- rootPath: path.dirname(result.pkg.path),
269
- }
270
- : null;
271
- };
272
-
273
224
  /**
274
225
  * TODO: Return Resolution instead of coercing to BundlerResolution here
275
226
  */
@@ -0,0 +1,36 @@
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
+ * @noformat
8
+ * @oncall react_native
9
+ * @generated SignedSource<<c008adad2ea747972e2f301a6375b447>>
10
+ *
11
+ * This file was translated from Flow by scripts/generateTypeScriptDefinitions.js
12
+ * Original file: packages/metro/src/node-haste/DependencyGraph/createFileMap.js
13
+ * To regenerate, run:
14
+ * js1 build metro-ts-defs (internal) OR
15
+ * yarn run build-ts-defs (OSS)
16
+ */
17
+
18
+ import type {ConfigT} from 'metro-config';
19
+ import type {HasteMap} from 'metro-file-map';
20
+
21
+ import MetroFileMap, {DependencyPlugin} from 'metro-file-map';
22
+
23
+ declare function createFileMap(
24
+ config: ConfigT,
25
+ options?: Readonly<{
26
+ extractDependencies?: boolean;
27
+ watch?: boolean;
28
+ throwOnModuleCollision?: boolean;
29
+ cacheFilePrefix?: string;
30
+ }>,
31
+ ): {
32
+ fileMap: MetroFileMap;
33
+ hasteMap: HasteMap;
34
+ dependencyPlugin: null | undefined | DependencyPlugin;
35
+ };
36
+ export default createFileMap;
@@ -71,7 +71,7 @@ function createFileMap(config, options) {
71
71
  const { enabled: autoSaveEnabled, ...autoSaveOpts } =
72
72
  config.watcher.unstable_autoSaveCache ?? {};
73
73
  const autoSave = watch && autoSaveEnabled ? autoSaveOpts : false;
74
- const plugins = [];
74
+ const plugins = [...(config.unstable_fileMapPlugins ?? [])];
75
75
  let dependencyPlugin = null;
76
76
  if (
77
77
  config.resolver.dependencyExtractor != null &&
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import type {ConfigT} from 'metro-config';
13
- import type {HasteMap} from 'metro-file-map';
13
+ import type {HasteMap, InputFileMapPlugin} from 'metro-file-map';
14
14
 
15
15
  import ci from 'ci-info';
16
16
  import MetroFileMap, {
@@ -75,7 +75,9 @@ export default function createFileMap(
75
75
  config.watcher.unstable_autoSaveCache ?? {};
76
76
  const autoSave = watch && autoSaveEnabled ? autoSaveOpts : false;
77
77
 
78
- const plugins: Array<DependencyPlugin | HastePlugin> = [];
78
+ const plugins: Array<InputFileMapPlugin> = [
79
+ ...(config.unstable_fileMapPlugins ?? []),
80
+ ];
79
81
 
80
82
  let dependencyPlugin = null;
81
83
  // Add DependencyPlugin if dependencies should be extracted
@@ -0,0 +1,90 @@
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
+ * @noformat
8
+ * @oncall react_native
9
+ * @generated SignedSource<<13f1483d2a732241f8d9eae463399b0e>>
10
+ *
11
+ * This file was translated from Flow by scripts/generateTypeScriptDefinitions.js
12
+ * Original file: packages/metro/src/node-haste/DependencyGraph.js
13
+ * To regenerate, run:
14
+ * js1 build metro-ts-defs (internal) OR
15
+ * yarn run build-ts-defs (OSS)
16
+ */
17
+
18
+ import type {
19
+ BundlerResolution,
20
+ TransformResultDependency,
21
+ } from '../DeltaBundler/types';
22
+ import type {ResolverInputOptions} from '../shared/types';
23
+ import type {ConfigT} from 'metro-config';
24
+ import type {
25
+ ChangeEvent,
26
+ FileSystem,
27
+ HasteMap,
28
+ HealthCheckResult,
29
+ WatcherStatus,
30
+ default as MetroFileMap,
31
+ } from 'metro-file-map';
32
+
33
+ import {ModuleResolver} from './DependencyGraph/ModuleResolution';
34
+ import EventEmitter from 'events';
35
+
36
+ declare class DependencyGraph extends EventEmitter {
37
+ _config: ConfigT;
38
+ _haste: MetroFileMap;
39
+ _fileSystem: FileSystem;
40
+ _hasteMap: HasteMap;
41
+ _moduleResolver: ModuleResolver;
42
+ _resolutionCache: Map<
43
+ string | symbol,
44
+ Map<
45
+ string | symbol,
46
+ Map<string | symbol, Map<string | symbol, BundlerResolution>>
47
+ >
48
+ >;
49
+ _initializedPromise: Promise<void>;
50
+ constructor(
51
+ config: ConfigT,
52
+ options?: {
53
+ readonly hasReducedPerformance?: boolean;
54
+ readonly watch?: boolean;
55
+ },
56
+ );
57
+ _onWatcherHealthCheck(result: HealthCheckResult): void;
58
+ _onWatcherStatus(status: WatcherStatus): void;
59
+ ready(): Promise<void>;
60
+ _onHasteChange($$PARAM_0$$: ChangeEvent): void;
61
+ _createModuleResolver(): void;
62
+ _getClosestPackage(
63
+ absoluteModulePath: string,
64
+ ): null | undefined | {packageJsonPath: string; packageRelativePath: string};
65
+ getAllFiles(): Array<string>;
66
+ /**
67
+ * Used when watcher.unstable_lazySha1 is true
68
+ */
69
+ getOrComputeSha1(
70
+ mixedPath: string,
71
+ ): Promise<{content?: Buffer; sha1: string}>;
72
+ getWatcher(): EventEmitter;
73
+ end(): void;
74
+ /** Given a search context, return a list of file paths matching the query. */
75
+ matchFilesWithContext(
76
+ from: string,
77
+ context: Readonly<{recursive: boolean; filter: RegExp}>,
78
+ ): Iterable<string>;
79
+ resolveDependency(
80
+ originModulePath: string,
81
+ dependency: TransformResultDependency,
82
+ platform: string | null,
83
+ resolverOptions: ResolverInputOptions,
84
+ $$PARAM_4$$?: {assumeFlatNodeModules: boolean},
85
+ ): BundlerResolution;
86
+ doesFileExist: (filePath: string) => boolean;
87
+ getHasteName(filePath: string): string;
88
+ getDependencies(filePath: string): Array<string>;
89
+ }
90
+ export default DependencyGraph;
@@ -71,7 +71,10 @@ class DependencyGraph extends _events.default {
71
71
  this._onWatcherHealthCheck(result),
72
72
  );
73
73
  this._resolutionCache = new Map();
74
- this.#packageCache = this._createPackageCache();
74
+ this.#packageCache = new _PackageCache.PackageCache({
75
+ getClosestPackage: (absoluteModulePath) =>
76
+ this._getClosestPackage(absoluteModulePath),
77
+ });
75
78
  this._createModuleResolver();
76
79
  });
77
80
  }
@@ -90,10 +93,14 @@ class DependencyGraph extends _events.default {
90
93
  async ready() {
91
94
  await this._initializedPromise;
92
95
  }
93
- _onHasteChange({ eventsQueue }) {
96
+ _onHasteChange({ changes, rootDir }) {
94
97
  this._resolutionCache = new Map();
95
- eventsQueue.forEach(({ filePath }) =>
96
- this.#packageCache.invalidate(filePath),
98
+ [
99
+ ...changes.addedFiles,
100
+ ...changes.modifiedFiles,
101
+ ...changes.removedFiles,
102
+ ].forEach(([canonicalPath]) =>
103
+ this.#packageCache.invalidate(_path.default.join(rootDir, canonicalPath)),
97
104
  );
98
105
  this._createModuleResolver();
99
106
  this.emit("change");
@@ -130,9 +137,19 @@ class DependencyGraph extends _events.default {
130
137
  this._hasteMap.getModule(name, platform, true),
131
138
  getHastePackagePath: (name, platform) =>
132
139
  this._hasteMap.getPackage(name, platform, true),
140
+ getPackage: (packageJsonPath) => {
141
+ try {
142
+ return (
143
+ this.#packageCache.getPackage(packageJsonPath).packageJson ?? null
144
+ );
145
+ } catch {
146
+ return null;
147
+ }
148
+ },
149
+ getPackageForModule: (absolutePath) =>
150
+ this.#packageCache.getPackageForModule(absolutePath),
133
151
  mainFields: this._config.resolver.resolverMainFields,
134
152
  nodeModulesPaths: this._config.resolver.nodeModulesPaths,
135
- packageCache: this.#packageCache,
136
153
  preferNativePlatform: true,
137
154
  projectRoot: this._config.projectRoot,
138
155
  reporter: this._config.reporter,
@@ -176,12 +193,6 @@ class DependencyGraph extends _events.default {
176
193
  }
177
194
  : null;
178
195
  }
179
- _createPackageCache() {
180
- return new _PackageCache.PackageCache({
181
- getClosestPackage: (absolutePath) =>
182
- this._getClosestPackage(absolutePath),
183
- });
184
- }
185
196
  getAllFiles() {
186
197
  return (0, _nullthrows.default)(this._fileSystem).getAllFiles();
187
198
  }
@@ -14,7 +14,6 @@ import type {
14
14
  TransformResultDependency,
15
15
  } from '../DeltaBundler/types';
16
16
  import type {ResolverInputOptions} from '../shared/types';
17
- import type Package from './Package';
18
17
  import type {ConfigT} from 'metro-config';
19
18
  import type {
20
19
  ChangeEvent,
@@ -66,7 +65,7 @@ export default class DependencyGraph extends EventEmitter {
66
65
  #packageCache: PackageCache;
67
66
  _hasteMap: HasteMap;
68
67
  #dependencyPlugin: ?DependencyPlugin;
69
- _moduleResolver: ModuleResolver<Package>;
68
+ _moduleResolver: ModuleResolver;
70
69
  _resolutionCache: Map<
71
70
  // Custom resolver options
72
71
  string | symbol,
@@ -131,7 +130,10 @@ export default class DependencyGraph extends EventEmitter {
131
130
  this._onWatcherHealthCheck(result),
132
131
  );
133
132
  this._resolutionCache = new Map();
134
- this.#packageCache = this._createPackageCache();
133
+ this.#packageCache = new PackageCache({
134
+ getClosestPackage: absoluteModulePath =>
135
+ this._getClosestPackage(absoluteModulePath),
136
+ });
135
137
  this._createModuleResolver();
136
138
  });
137
139
  }
@@ -150,10 +152,14 @@ export default class DependencyGraph extends EventEmitter {
150
152
  await this._initializedPromise;
151
153
  }
152
154
 
153
- _onHasteChange({eventsQueue}: ChangeEvent) {
155
+ _onHasteChange({changes, rootDir}: ChangeEvent) {
154
156
  this._resolutionCache = new Map();
155
- eventsQueue.forEach(({filePath}) =>
156
- this.#packageCache.invalidate(filePath),
157
+ [
158
+ ...changes.addedFiles,
159
+ ...changes.modifiedFiles,
160
+ ...changes.removedFiles,
161
+ ].forEach(([canonicalPath]) =>
162
+ this.#packageCache.invalidate(path.join(rootDir, canonicalPath)),
157
163
  );
158
164
  this._createModuleResolver();
159
165
  this.emit('change');
@@ -190,9 +196,20 @@ export default class DependencyGraph extends EventEmitter {
190
196
  this._hasteMap.getModule(name, platform, true),
191
197
  getHastePackagePath: (name, platform) =>
192
198
  this._hasteMap.getPackage(name, platform, true),
199
+ getPackage: (packageJsonPath: string) => {
200
+ try {
201
+ return (
202
+ this.#packageCache.getPackage(packageJsonPath).packageJson ?? null
203
+ );
204
+ } catch {
205
+ // Non-existence or malformed JSON, we treat both as non-existent
206
+ return null;
207
+ }
208
+ },
209
+ getPackageForModule: (absolutePath: string) =>
210
+ this.#packageCache.getPackageForModule(absolutePath),
193
211
  mainFields: this._config.resolver.resolverMainFields,
194
212
  nodeModulesPaths: this._config.resolver.nodeModulesPaths,
195
- packageCache: this.#packageCache,
196
213
  preferNativePlatform: true,
197
214
  projectRoot: this._config.projectRoot,
198
215
  reporter: this._config.reporter,
@@ -241,12 +258,6 @@ export default class DependencyGraph extends EventEmitter {
241
258
  : null;
242
259
  }
243
260
 
244
- _createPackageCache(): PackageCache {
245
- return new PackageCache({
246
- getClosestPackage: absolutePath => this._getClosestPackage(absolutePath),
247
- });
248
- }
249
-
250
261
  getAllFiles(): Array<string> {
251
262
  return nullthrows(this._fileSystem).getAllFiles();
252
263
  }
@@ -0,0 +1,37 @@
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
+ * @noformat
8
+ * @oncall react_native
9
+ * @generated SignedSource<<768dba0958b531c8edd43c2df24e25f6>>
10
+ *
11
+ * This file was translated from Flow by scripts/generateTypeScriptDefinitions.js
12
+ * Original file: packages/metro/src/node-haste/PackageCache.js
13
+ * To regenerate, run:
14
+ * js1 build metro-ts-defs (internal) OR
15
+ * yarn run build-ts-defs (OSS)
16
+ */
17
+
18
+ import type {PackageJson} from 'metro-resolver/private/types';
19
+
20
+ type GetClosestPackageFn = (
21
+ absoluteFilePath: string,
22
+ ) => null | undefined | {packageJsonPath: string; packageRelativePath: string};
23
+ type PackageForModule = Readonly<{
24
+ packageJson: PackageJson;
25
+ rootPath: string;
26
+ packageRelativePath: string;
27
+ }>;
28
+ export declare class PackageCache {
29
+ constructor(options: {getClosestPackage: GetClosestPackageFn});
30
+ getPackage(
31
+ filePath: string,
32
+ ): Readonly<{rootPath: string; packageJson: PackageJson}>;
33
+ getPackageForModule(
34
+ absoluteModulePath: string,
35
+ ): null | undefined | PackageForModule;
36
+ invalidate(filePath: string): void;
37
+ }
@@ -4,78 +4,89 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true,
5
5
  });
6
6
  exports.PackageCache = void 0;
7
- var _Package = _interopRequireDefault(require("./Package"));
8
- function _interopRequireDefault(e) {
9
- return e && e.__esModule ? e : { default: e };
10
- }
7
+ var _fs = require("fs");
8
+ var _path = require("path");
11
9
  class PackageCache {
10
+ #getClosestPackage;
11
+ #packageCache;
12
+ #resultByModulePath;
13
+ #modulePathsByPackagePath;
14
+ #modulePathsWithNoPackage;
12
15
  constructor(options) {
13
- this._getClosestPackage = options.getClosestPackage;
14
- this._packageCache = Object.create(null);
15
- this._packagePathAndSubpathByModulePath = Object.create(null);
16
- this._modulePathsByPackagePath = Object.create(null);
16
+ this.#getClosestPackage = options.getClosestPackage;
17
+ this.#packageCache = new Map();
18
+ this.#resultByModulePath = new Map();
19
+ this.#modulePathsByPackagePath = new Map();
20
+ this.#modulePathsWithNoPackage = new Set();
17
21
  }
18
22
  getPackage(filePath) {
19
- if (!this._packageCache[filePath]) {
20
- this._packageCache[filePath] = new _Package.default({
21
- file: filePath,
22
- });
23
+ let cached = this.#packageCache.get(filePath);
24
+ if (cached == null) {
25
+ cached = {
26
+ rootPath: (0, _path.dirname)(filePath),
27
+ packageJson: JSON.parse((0, _fs.readFileSync)(filePath, "utf8")),
28
+ };
29
+ this.#packageCache.set(filePath, cached);
23
30
  }
24
- return this._packageCache[filePath];
31
+ return cached;
25
32
  }
26
- getPackageOf(absoluteModulePath) {
27
- let packagePathAndSubpath =
28
- this._packagePathAndSubpathByModulePath[absoluteModulePath];
29
- if (
30
- packagePathAndSubpath &&
31
- this._packageCache[packagePathAndSubpath.packageJsonPath]
32
- ) {
33
- return {
34
- pkg: this._packageCache[packagePathAndSubpath.packageJsonPath],
35
- packageRelativePath: packagePathAndSubpath.packageRelativePath,
36
- };
33
+ getPackageForModule(absoluteModulePath) {
34
+ const cached = this.#resultByModulePath.get(absoluteModulePath);
35
+ if (cached !== undefined) {
36
+ return cached;
37
37
  }
38
- packagePathAndSubpath = this._getClosestPackage(absoluteModulePath);
39
- if (!packagePathAndSubpath) {
38
+ const closest = this.#getClosestPackage(absoluteModulePath);
39
+ if (closest == null) {
40
+ this.#resultByModulePath.set(absoluteModulePath, null);
41
+ this.#modulePathsWithNoPackage.add(absoluteModulePath);
40
42
  return null;
41
43
  }
42
- const packagePath = packagePathAndSubpath.packageJsonPath;
43
- this._packagePathAndSubpathByModulePath[absoluteModulePath] =
44
- packagePathAndSubpath;
45
- const modulePaths =
46
- this._modulePathsByPackagePath[packagePath] ?? new Set();
44
+ const packagePath = closest.packageJsonPath;
45
+ let modulePaths = this.#modulePathsByPackagePath.get(packagePath);
46
+ if (modulePaths == null) {
47
+ modulePaths = new Set();
48
+ this.#modulePathsByPackagePath.set(packagePath, modulePaths);
49
+ }
47
50
  modulePaths.add(absoluteModulePath);
48
- this._modulePathsByPackagePath[packagePath] = modulePaths;
49
- return {
50
- pkg: this.getPackage(packagePath),
51
- packageRelativePath: packagePathAndSubpath.packageRelativePath,
51
+ const pkg = this.getPackage(packagePath);
52
+ if (pkg == null) {
53
+ return null;
54
+ }
55
+ const result = {
56
+ packageJson: pkg.packageJson,
57
+ packageRelativePath: closest.packageRelativePath,
58
+ rootPath: pkg.rootPath,
52
59
  };
60
+ this.#resultByModulePath.set(absoluteModulePath, result);
61
+ return result;
53
62
  }
54
63
  invalidate(filePath) {
55
- if (this._packageCache[filePath]) {
56
- this._packageCache[filePath].invalidate();
57
- delete this._packageCache[filePath];
58
- }
59
- const packagePathAndSubpath =
60
- this._packagePathAndSubpathByModulePath[filePath];
61
- if (packagePathAndSubpath) {
62
- const packagePath = packagePathAndSubpath.packageJsonPath;
63
- delete this._packagePathAndSubpathByModulePath[filePath];
64
- const modulePaths = this._modulePathsByPackagePath[packagePath];
65
- if (modulePaths) {
66
- modulePaths.delete(filePath);
67
- if (modulePaths.size === 0) {
68
- delete this._modulePathsByPackagePath[packagePath];
64
+ this.#packageCache.delete(filePath);
65
+ const cachedResult = this.#resultByModulePath.get(filePath);
66
+ this.#resultByModulePath.delete(filePath);
67
+ this.#modulePathsWithNoPackage.delete(filePath);
68
+ if (cachedResult != null) {
69
+ const packagePath = cachedResult.rootPath + _path.sep + "package.json";
70
+ const modules = this.#modulePathsByPackagePath.get(packagePath);
71
+ if (modules != null) {
72
+ modules.delete(filePath);
73
+ if (modules.size === 0) {
74
+ this.#modulePathsByPackagePath.delete(packagePath);
69
75
  }
70
76
  }
71
77
  }
72
- if (this._modulePathsByPackagePath[filePath]) {
73
- const modulePaths = this._modulePathsByPackagePath[filePath];
78
+ const modulePaths = this.#modulePathsByPackagePath.get(filePath);
79
+ if (modulePaths != null) {
74
80
  for (const modulePath of modulePaths) {
75
- delete this._packagePathAndSubpathByModulePath[modulePath];
81
+ this.#resultByModulePath.delete(modulePath);
82
+ }
83
+ this.#modulePathsByPackagePath.delete(filePath);
84
+ }
85
+ if (filePath.endsWith(_path.sep + "package.json")) {
86
+ for (const modulePath of this.#modulePathsWithNoPackage) {
87
+ this.#resultByModulePath.delete(modulePath);
76
88
  }
77
- modulePaths.clear();
78
- delete this._modulePathsByPackagePath[filePath];
89
+ this.#modulePathsWithNoPackage.clear();
79
90
  }
80
91
  }
81
92
  }