metro 0.71.0 → 0.71.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 (57) hide show
  1. package/package.json +23 -22
  2. package/src/Bundler.js +0 -2
  3. package/src/Bundler.js.flow +1 -1
  4. package/src/DeltaBundler/DeltaCalculator.js +2 -0
  5. package/src/DeltaBundler/DeltaCalculator.js.flow +2 -0
  6. package/src/DeltaBundler/Worker.flow.js +78 -0
  7. package/src/DeltaBundler/Worker.flow.js.flow +121 -0
  8. package/src/DeltaBundler/Worker.js +8 -66
  9. package/src/DeltaBundler/Worker.js.flow +8 -107
  10. package/src/DeltaBundler/WorkerFarm.js.flow +2 -2
  11. package/src/DeltaBundler/__fixtures__/hasteImpl.js +4 -0
  12. package/src/DeltaBundler/graphOperations.js +382 -222
  13. package/src/DeltaBundler/graphOperations.js.flow +404 -232
  14. package/src/DeltaBundler/types.flow.js +6 -0
  15. package/src/DeltaBundler/types.flow.js.flow +7 -1
  16. package/src/DeltaBundler.js +0 -2
  17. package/src/DeltaBundler.js.flow +1 -1
  18. package/src/HmrServer.js +0 -2
  19. package/src/HmrServer.js.flow +1 -2
  20. package/src/ModuleGraph/node-haste/node-haste.flow.js +0 -1
  21. package/src/ModuleGraph/node-haste/node-haste.flow.js.flow +1 -2
  22. package/src/ModuleGraph/node-haste/node-haste.js.flow +7 -2
  23. package/src/ModuleGraph/output/util.js.flow +2 -2
  24. package/src/ModuleGraph/silent-console.js +5 -4
  25. package/src/ModuleGraph/silent-console.js.flow +8 -4
  26. package/src/ModuleGraph/worker/collectDependencies.js +215 -8
  27. package/src/ModuleGraph/worker/collectDependencies.js.flow +233 -13
  28. package/src/Server.js +2 -0
  29. package/src/Server.js.flow +9 -2
  30. package/src/cli.js +5 -0
  31. package/src/cli.js.flow +5 -0
  32. package/src/commands/build.js +4 -3
  33. package/src/commands/build.js.flow +3 -1
  34. package/src/commands/serve.js +3 -3
  35. package/src/commands/serve.js.flow +3 -1
  36. package/src/index.flow.js +392 -0
  37. package/src/index.flow.js.flow +480 -0
  38. package/src/index.js +8 -380
  39. package/src/index.js.flow +8 -466
  40. package/src/lib/CountingSet.js +116 -0
  41. package/src/lib/CountingSet.js.flow +126 -0
  42. package/src/lib/JsonReporter.js +0 -2
  43. package/src/lib/JsonReporter.js.flow +1 -1
  44. package/src/lib/getAppendScripts.js +10 -4
  45. package/src/lib/getAppendScripts.js.flow +6 -4
  46. package/src/lib/getPreludeCode.js +19 -1
  47. package/src/lib/getPreludeCode.js.flow +15 -0
  48. package/src/lib/getPrependedScripts.js +10 -2
  49. package/src/lib/getPrependedScripts.js.flow +11 -2
  50. package/src/lib/reporting.js +0 -2
  51. package/src/lib/reporting.js.flow +2 -1
  52. package/src/node-haste/DependencyGraph/ModuleResolution.js +15 -3
  53. package/src/node-haste/DependencyGraph/ModuleResolution.js.flow +15 -0
  54. package/src/node-haste/DependencyGraph/createHasteMap.js +78 -19
  55. package/src/node-haste/DependencyGraph/createHasteMap.js.flow +14 -9
  56. package/src/node-haste/DependencyGraph.js +2 -2
  57. package/src/node-haste/DependencyGraph.js.flow +4 -2
package/src/index.js.flow CHANGED
@@ -10,471 +10,13 @@
10
10
 
11
11
  'use strict';
12
12
 
13
- import type {Graph} from './DeltaBundler';
14
- import type {ServerOptions} from './Server';
15
- import type {OutputOptions, RequestOptions} from './shared/types.flow.js';
16
- import type {Server as HttpServer} from 'http';
17
- import type {Server as HttpsServer} from 'https';
18
- import type {
19
- ConfigT,
20
- InputConfigT,
21
- Middleware,
22
- } from 'metro-config/src/configTypes.flow';
23
- import type {CustomTransformOptions} from 'metro-transform-worker';
24
- import typeof Yargs from 'yargs';
13
+ /*::
14
+ export type * from './index.flow';
15
+ */
25
16
 
26
- const makeBuildCommand = require('./commands/build');
27
- const makeDependenciesCommand = require('./commands/dependencies');
28
- const makeServeCommand = require('./commands/serve');
29
- const MetroHmrServer = require('./HmrServer');
30
- const IncrementalBundler = require('./IncrementalBundler');
31
- const createWebsocketServer = require('./lib/createWebsocketServer');
32
- const MetroServer = require('./Server');
33
- const outputBundle = require('./shared/output/bundle');
34
- const chalk = require('chalk');
35
- const fs = require('fs');
36
- const http = require('http');
37
- const https = require('https');
38
- const {getDefaultConfig, loadConfig, mergeConfig} = require('metro-config');
39
- const {InspectorProxy} = require('metro-inspector-proxy');
40
- const net = require('net');
41
- const {parse} = require('url');
42
- const ws = require('ws');
17
+ try {
18
+ // $FlowFixMe[untyped-import]
19
+ require('metro-babel-register').unstable_registerForMetroMonorepo();
20
+ } catch {}
43
21
 
44
- type MetroMiddleWare = {
45
- attachHmrServer: (httpServer: HttpServer | HttpsServer) => void,
46
- end: () => void,
47
- metroServer: MetroServer,
48
- middleware: Middleware,
49
- };
50
-
51
- export type RunMetroOptions = {
52
- ...ServerOptions,
53
- waitForBundler?: boolean,
54
- };
55
-
56
- export type RunServerOptions = {
57
- hasReducedPerformance?: boolean,
58
- host?: string,
59
- onError?: (Error & {code?: string}) => void,
60
- onReady?: (server: HttpServer | HttpsServer) => void,
61
- runInspectorProxy?: boolean,
62
- secureServerOptions?: Object,
63
- secure?: boolean, // deprecated
64
- secureCert?: string, // deprecated
65
- secureKey?: string, // deprecated
66
- waitForBundler?: boolean,
67
- websocketEndpoints?: {
68
- [path: string]: typeof ws.Server,
69
- },
70
- };
71
-
72
- type BuildGraphOptions = {
73
- entries: $ReadOnlyArray<string>,
74
- customTransformOptions?: CustomTransformOptions,
75
- dev?: boolean,
76
- minify?: boolean,
77
- onProgress?: (transformedFileCount: number, totalFileCount: number) => void,
78
- platform?: string,
79
- type?: 'module' | 'script',
80
- };
81
-
82
- export type RunBuildOptions = {
83
- entry: string,
84
- dev?: boolean,
85
- out?: string,
86
- onBegin?: () => void,
87
- onComplete?: () => void,
88
- onProgress?: (transformedFileCount: number, totalFileCount: number) => void,
89
- minify?: boolean,
90
- output?: {
91
- build: (
92
- MetroServer,
93
- RequestOptions,
94
- ) => Promise<{
95
- code: string,
96
- map: string,
97
- ...
98
- }>,
99
- save: (
100
- {
101
- code: string,
102
- map: string,
103
- ...
104
- },
105
- OutputOptions,
106
- (...args: Array<string>) => void,
107
- ) => Promise<mixed>,
108
- ...
109
- },
110
- platform?: string,
111
- sourceMap?: boolean,
112
- sourceMapUrl?: string,
113
- };
114
-
115
- type BuildCommandOptions = {} | null;
116
- type ServeCommandOptions = {} | null;
117
-
118
- async function getConfig(config: InputConfigT): Promise<ConfigT> {
119
- const defaultConfig = await getDefaultConfig(config.projectRoot);
120
- return mergeConfig(defaultConfig, config);
121
- }
122
-
123
- async function runMetro(
124
- config: InputConfigT,
125
- options?: RunMetroOptions,
126
- ): Promise<MetroServer> {
127
- const mergedConfig = await getConfig(config);
128
- const {
129
- reporter,
130
- server: {port},
131
- } = mergedConfig;
132
-
133
- reporter.update({
134
- hasReducedPerformance: options
135
- ? Boolean(options.hasReducedPerformance)
136
- : false,
137
- port,
138
- type: 'initialize_started',
139
- });
140
-
141
- const {waitForBundler = false, ...serverOptions} = options ?? {};
142
- const server = new MetroServer(mergedConfig, serverOptions);
143
-
144
- const readyPromise = server
145
- .ready()
146
- .then(() => {
147
- reporter.update({
148
- type: 'initialize_done',
149
- port,
150
- });
151
- })
152
- .catch(error => {
153
- reporter.update({
154
- type: 'initialize_failed',
155
- port,
156
- error,
157
- });
158
- });
159
- if (waitForBundler) {
160
- await readyPromise;
161
- }
162
-
163
- return server;
164
- }
165
-
166
- exports.runMetro = runMetro;
167
- exports.loadConfig = loadConfig;
168
-
169
- const createConnectMiddleware = async function (
170
- config: ConfigT,
171
- options?: RunMetroOptions,
172
- ): Promise<MetroMiddleWare> {
173
- const metroServer = await runMetro(config, options);
174
-
175
- let enhancedMiddleware: Middleware = metroServer.processRequest;
176
-
177
- // Enhance the resulting middleware using the config options
178
- if (config.server.enhanceMiddleware) {
179
- enhancedMiddleware = config.server.enhanceMiddleware(
180
- enhancedMiddleware,
181
- metroServer,
182
- );
183
- }
184
-
185
- return {
186
- attachHmrServer(httpServer: HttpServer | HttpsServer): void {
187
- const wss = createWebsocketServer({
188
- websocketServer: new MetroHmrServer(
189
- metroServer.getBundler(),
190
- metroServer.getCreateModuleId(),
191
- config,
192
- ),
193
- });
194
- httpServer.on('upgrade', (request, socket, head) => {
195
- const {pathname} = parse(request.url);
196
- if (pathname === '/hot') {
197
- wss.handleUpgrade(request, socket, head, ws => {
198
- wss.emit('connection', ws, request);
199
- });
200
- } else {
201
- socket.destroy();
202
- }
203
- });
204
- },
205
- metroServer,
206
- middleware: enhancedMiddleware,
207
- end(): void {
208
- metroServer.end();
209
- },
210
- };
211
- };
212
- exports.createConnectMiddleware = createConnectMiddleware;
213
-
214
- exports.runServer = async (
215
- config: ConfigT,
216
- {
217
- hasReducedPerformance = false,
218
- host,
219
- onError,
220
- onReady,
221
- secureServerOptions,
222
- secure, //deprecated
223
- secureCert, // deprecated
224
- secureKey, // deprecated
225
- waitForBundler = false,
226
- websocketEndpoints = {},
227
- }: RunServerOptions,
228
- ): Promise<HttpServer | HttpsServer> => {
229
- await earlyPortCheck(host, config.server.port);
230
-
231
- if (secure != null || secureCert != null || secureKey != null) {
232
- // eslint-disable-next-line no-console
233
- console.warn(
234
- chalk.inverse.yellow.bold(' DEPRECATED '),
235
- 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +
236
- 'Please use the `secureServerOptions` object instead to pass options to ' +
237
- "Metro's https development server.",
238
- );
239
- }
240
- // Lazy require
241
- const connect = require('connect');
242
-
243
- const serverApp = connect();
244
-
245
- const {middleware, end, metroServer} = await createConnectMiddleware(config, {
246
- hasReducedPerformance,
247
- waitForBundler,
248
- });
249
-
250
- serverApp.use(middleware);
251
-
252
- let inspectorProxy: ?InspectorProxy = null;
253
- if (config.server.runInspectorProxy) {
254
- inspectorProxy = new InspectorProxy(config.projectRoot);
255
- }
256
-
257
- let httpServer;
258
-
259
- if (secure || secureServerOptions != null) {
260
- let options = secureServerOptions;
261
- if (typeof secureKey === 'string' && typeof secureCert === 'string') {
262
- options = {
263
- key: fs.readFileSync(secureKey),
264
- cert: fs.readFileSync(secureCert),
265
- ...secureServerOptions,
266
- };
267
- }
268
- httpServer = https.createServer(options, serverApp);
269
- } else {
270
- httpServer = http.createServer(serverApp);
271
- }
272
- return new Promise(
273
- (
274
- resolve: (result: HttpServer | HttpsServer) => void,
275
- reject: mixed => mixed,
276
- ) => {
277
- httpServer.on('error', error => {
278
- if (onError) {
279
- onError(error);
280
- }
281
- reject(error);
282
- end();
283
- });
284
-
285
- httpServer.listen(config.server.port, host, () => {
286
- if (onReady) {
287
- onReady(httpServer);
288
- }
289
-
290
- Object.assign(websocketEndpoints, {
291
- ...(inspectorProxy
292
- ? {...inspectorProxy.createWebSocketListeners(httpServer)}
293
- : {}),
294
- '/hot': createWebsocketServer({
295
- websocketServer: new MetroHmrServer(
296
- metroServer.getBundler(),
297
- metroServer.getCreateModuleId(),
298
- config,
299
- ),
300
- }),
301
- });
302
-
303
- httpServer.on('upgrade', (request, socket, head) => {
304
- const {pathname} = parse(request.url);
305
- if (pathname != null && websocketEndpoints[pathname]) {
306
- websocketEndpoints[pathname].handleUpgrade(
307
- request,
308
- socket,
309
- head,
310
- ws => {
311
- websocketEndpoints[pathname].emit('connection', ws, request);
312
- },
313
- );
314
- } else {
315
- socket.destroy();
316
- }
317
- });
318
-
319
- if (inspectorProxy) {
320
- // TODO(hypuk): Refactor inspectorProxy.processRequest into separate request handlers
321
- // so that we could provide routes (/json/list and /json/version) here.
322
- // Currently this causes Metro to give warning about T31407894.
323
- // $FlowFixMe[method-unbinding] added when improving typing for this parameters
324
- serverApp.use(inspectorProxy.processRequest.bind(inspectorProxy));
325
- }
326
-
327
- resolve(httpServer);
328
- });
329
-
330
- // Disable any kind of automatic timeout behavior for incoming
331
- // requests in case it takes the packager more than the default
332
- // timeout of 120 seconds to respond to a request.
333
- httpServer.timeout = 0;
334
-
335
- httpServer.on('close', () => {
336
- end();
337
- });
338
- },
339
- );
340
- };
341
-
342
- exports.runBuild = async (
343
- config: ConfigT,
344
- {
345
- dev = false,
346
- entry,
347
- onBegin,
348
- onComplete,
349
- onProgress,
350
- minify = true,
351
- output = outputBundle,
352
- out,
353
- platform = 'web',
354
- sourceMap = false,
355
- sourceMapUrl,
356
- }: RunBuildOptions,
357
- ): Promise<{
358
- code: string,
359
- map: string,
360
- ...
361
- }> => {
362
- const metroServer = await runMetro(config, {
363
- watch: false,
364
- });
365
-
366
- try {
367
- const requestOptions: RequestOptions = {
368
- dev,
369
- entryFile: entry,
370
- inlineSourceMap: sourceMap && !sourceMapUrl,
371
- minify,
372
- platform,
373
- sourceMapUrl: sourceMap === false ? undefined : sourceMapUrl,
374
- createModuleIdFactory: config.serializer.createModuleIdFactory,
375
- onProgress,
376
- };
377
-
378
- if (onBegin) {
379
- onBegin();
380
- }
381
-
382
- const metroBundle = await output.build(metroServer, requestOptions);
383
-
384
- if (onComplete) {
385
- onComplete();
386
- }
387
-
388
- if (out) {
389
- const bundleOutput = out.replace(/(\.js)?$/, '.js');
390
- const sourcemapOutput =
391
- sourceMap === false ? undefined : out.replace(/(\.js)?$/, '.map');
392
-
393
- const outputOptions: OutputOptions = {
394
- bundleOutput,
395
- sourcemapOutput,
396
- dev,
397
- platform,
398
- };
399
-
400
- // eslint-disable-next-line no-console
401
- await output.save(metroBundle, outputOptions, console.log);
402
- }
403
-
404
- return metroBundle;
405
- } finally {
406
- await metroServer.end();
407
- }
408
- };
409
-
410
- exports.buildGraph = async function (
411
- config: InputConfigT,
412
- {
413
- customTransformOptions = Object.create(null),
414
- dev = false,
415
- entries,
416
- minify = false,
417
- onProgress,
418
- platform = 'web',
419
- type = 'module',
420
- }: BuildGraphOptions,
421
- ): Promise<Graph<>> {
422
- const mergedConfig = await getConfig(config);
423
-
424
- const bundler = new IncrementalBundler(mergedConfig);
425
-
426
- try {
427
- return await bundler.buildGraphForEntries(entries, {
428
- ...MetroServer.DEFAULT_GRAPH_OPTIONS,
429
- customTransformOptions,
430
- dev,
431
- minify,
432
- platform,
433
- type,
434
- });
435
- } finally {
436
- bundler.end();
437
- }
438
- };
439
-
440
- exports.attachMetroCli = function (
441
- yargs: Yargs,
442
- {
443
- build = {},
444
- serve = {},
445
- dependencies = {},
446
- }: {
447
- build: BuildCommandOptions,
448
- serve: ServeCommandOptions,
449
- dependencies: any,
450
- ...
451
- } = {},
452
- ): Yargs {
453
- if (build) {
454
- const {command, description, builder, handler} = makeBuildCommand();
455
- yargs.command(command, description, builder, handler);
456
- }
457
- if (serve) {
458
- const {command, description, builder, handler} = makeServeCommand();
459
- yargs.command(command, description, builder, handler);
460
- }
461
- if (dependencies) {
462
- const {command, description, builder, handler} = makeDependenciesCommand();
463
- yargs.command(command, description, builder, handler);
464
- }
465
- return yargs;
466
- };
467
-
468
- async function earlyPortCheck(host: void | string, port: number) {
469
- const server = net.createServer(c => c.end());
470
- try {
471
- await new Promise((resolve, reject) => {
472
- server.on('error', err => {
473
- reject(err);
474
- });
475
- server.listen(port, host, undefined, () => resolve());
476
- });
477
- } finally {
478
- await new Promise(resolve => server.close(() => resolve()));
479
- }
480
- }
22
+ module.exports = require('./index.flow');
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true,
5
+ });
6
+ exports.default = void 0;
7
+
8
+ /**
9
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
10
+ *
11
+ * This source code is licensed under the MIT license found in the
12
+ * LICENSE file in the root directory of this source tree.
13
+ *
14
+ *
15
+ * @format
16
+ */
17
+
18
+ /**
19
+ * A Set that only deletes a given item when the number of delete(item) calls
20
+ * matches the number of add(item) calls. Iteration and `size` are in terms of
21
+ * *unique* items.
22
+ */
23
+ class CountingSet {
24
+ #map = new Map();
25
+
26
+ constructor(items) {
27
+ if (items) {
28
+ if (items instanceof CountingSet) {
29
+ this.#map = new Map(items.#map);
30
+ } else {
31
+ for (const item of items) {
32
+ this.add(item);
33
+ }
34
+ }
35
+ }
36
+ }
37
+
38
+ has(item) {
39
+ return this.#map.has(item);
40
+ }
41
+
42
+ add(item) {
43
+ const newCount = this.count(item) + 1;
44
+ this.#map.set(item, newCount);
45
+ }
46
+
47
+ delete(item) {
48
+ const newCount = this.count(item) - 1;
49
+
50
+ if (newCount <= 0) {
51
+ this.#map.delete(item);
52
+ } else {
53
+ this.#map.set(item, newCount);
54
+ }
55
+ }
56
+
57
+ keys() {
58
+ return this.#map.keys();
59
+ }
60
+
61
+ values() {
62
+ return this.#map.keys();
63
+ }
64
+
65
+ *entries() {
66
+ for (const item of this) {
67
+ yield [item, item];
68
+ }
69
+ } // Iterate over unique entries
70
+ // $FlowIssue[unsupported-syntax]
71
+
72
+ [Symbol.iterator]() {
73
+ return this.values();
74
+ }
75
+ /*::
76
+ // For Flow's benefit
77
+ @@iterator(): Iterator<T> {
78
+ return this.values();
79
+ }
80
+ */
81
+ // Number of unique entries
82
+ // $FlowIssue[unsafe-getters-setters]
83
+
84
+ get size() {
85
+ return this.#map.size;
86
+ }
87
+
88
+ count(item) {
89
+ var _this$map$get;
90
+
91
+ return (_this$map$get = this.#map.get(item)) !== null &&
92
+ _this$map$get !== void 0
93
+ ? _this$map$get
94
+ : 0;
95
+ }
96
+
97
+ clear() {
98
+ this.#map.clear();
99
+ }
100
+
101
+ forEach(callbackFn, thisArg) {
102
+ for (const item of this) {
103
+ callbackFn.call(thisArg, item, item, this);
104
+ }
105
+ } // For Jest purposes. Ideally a custom serializer would be enough, but in
106
+ // practice there is hardcoded magic for Set in toEqual (etc) that we cannot
107
+ // extend to custom collection classes. Instead let's assume values are
108
+ // sortable ( = strings) and make this look like an array with some stable
109
+ // order.
110
+
111
+ toJSON() {
112
+ return [...this].sort();
113
+ }
114
+ }
115
+
116
+ exports.default = CountingSet;
@@ -0,0 +1,126 @@
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 strict-local
8
+ * @format
9
+ */
10
+
11
+ export interface ReadOnlyCountingSet<T> extends Iterable<T> {
12
+ has(item: T): boolean;
13
+ @@iterator(): Iterator<T>;
14
+ +size: number;
15
+ count(item: T): number;
16
+ forEach<ThisT>(
17
+ callbackFn: (
18
+ this: ThisT,
19
+ value: T,
20
+ key: T,
21
+ set: ReadOnlyCountingSet<T>,
22
+ ) => mixed,
23
+
24
+ // NOTE: Should be optional, but Flow seems happy to infer undefined here
25
+ // which is what we want.
26
+ thisArg: ThisT,
27
+ ): void;
28
+ }
29
+
30
+ /**
31
+ * A Set that only deletes a given item when the number of delete(item) calls
32
+ * matches the number of add(item) calls. Iteration and `size` are in terms of
33
+ * *unique* items.
34
+ */
35
+ export default class CountingSet<T> implements ReadOnlyCountingSet<T> {
36
+ #map: Map<T, number> = new Map();
37
+
38
+ constructor(items?: Iterable<T>) {
39
+ if (items) {
40
+ if (items instanceof CountingSet) {
41
+ this.#map = new Map(items.#map);
42
+ } else {
43
+ for (const item of items) {
44
+ this.add(item);
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ has(item: T): boolean {
51
+ return this.#map.has(item);
52
+ }
53
+
54
+ add(item: T): void {
55
+ const newCount = this.count(item) + 1;
56
+ this.#map.set(item, newCount);
57
+ }
58
+
59
+ delete(item: T): void {
60
+ const newCount = this.count(item) - 1;
61
+ if (newCount <= 0) {
62
+ this.#map.delete(item);
63
+ } else {
64
+ this.#map.set(item, newCount);
65
+ }
66
+ }
67
+
68
+ keys(): Iterator<T> {
69
+ return this.#map.keys();
70
+ }
71
+
72
+ values(): Iterator<T> {
73
+ return this.#map.keys();
74
+ }
75
+
76
+ *entries(): Iterator<[T, T]> {
77
+ for (const item of this) {
78
+ yield [item, item];
79
+ }
80
+ }
81
+
82
+ // Iterate over unique entries
83
+ // $FlowIssue[unsupported-syntax]
84
+ [Symbol.iterator](): Iterator<T> {
85
+ return this.values();
86
+ }
87
+
88
+ /*::
89
+ // For Flow's benefit
90
+ @@iterator(): Iterator<T> {
91
+ return this.values();
92
+ }
93
+ */
94
+
95
+ // Number of unique entries
96
+ // $FlowIssue[unsafe-getters-setters]
97
+ get size(): number {
98
+ return this.#map.size;
99
+ }
100
+
101
+ count(item: T): number {
102
+ return this.#map.get(item) ?? 0;
103
+ }
104
+
105
+ clear(): void {
106
+ this.#map.clear();
107
+ }
108
+
109
+ forEach<ThisT>(
110
+ callbackFn: (this: ThisT, value: T, key: T, set: CountingSet<T>) => mixed,
111
+ thisArg: ThisT,
112
+ ): void {
113
+ for (const item of this) {
114
+ callbackFn.call(thisArg, item, item, this);
115
+ }
116
+ }
117
+
118
+ // For Jest purposes. Ideally a custom serializer would be enough, but in
119
+ // practice there is hardcoded magic for Set in toEqual (etc) that we cannot
120
+ // extend to custom collection classes. Instead let's assume values are
121
+ // sortable ( = strings) and make this look like an array with some stable
122
+ // order.
123
+ toJSON(): mixed {
124
+ return [...this].sort();
125
+ }
126
+ }