-
Notifications
You must be signed in to change notification settings - Fork 626
/
require.js
1032 lines (937 loc) Β· 30.7 KB
/
require.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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
* @oncall react_native
* @polyfill
*/
'use strict';
/* eslint-disable no-bitwise */
declare var __DEV__: boolean;
declare var __METRO_GLOBAL_PREFIX__: string;
// A simpler $ArrayLike<T>. Not iterable and doesn't have a `length`.
// This is compatible with actual arrays as well as with objects that look like
// {0: 'value', 1: '...'}
type ArrayIndexable<T> = interface {
+[indexer: number]: T,
};
type DependencyMap = $ReadOnly<
ArrayIndexable<ModuleID> & {
paths?: {[id: ModuleID]: string},
},
>;
type InverseDependencyMap = {[key: ModuleID]: Array<ModuleID>, ...};
type Exports = any;
type FactoryFn = (
global: Object,
require: RequireFn,
metroImportDefault: RequireFn,
metroImportAll: RequireFn,
moduleObject: {exports: {...}, ...},
exports: {...},
dependencyMap: ?DependencyMap,
) => void;
type HotModuleReloadingCallback = () => void;
type HotModuleReloadingData = {
_acceptCallback: ?HotModuleReloadingCallback,
_disposeCallback: ?HotModuleReloadingCallback,
_didAccept: boolean,
accept: (callback?: HotModuleReloadingCallback) => void,
dispose: (callback?: HotModuleReloadingCallback) => void,
};
type ModuleID = number;
type Module = {
id?: ModuleID,
exports: Exports,
hot?: HotModuleReloadingData,
...
};
type ModuleDefinition = {
dependencyMap: ?DependencyMap,
error?: any,
factory: FactoryFn,
hasError: boolean,
hot?: HotModuleReloadingData,
importedAll: any,
importedDefault: any,
isInitialized: boolean,
path?: string,
publicModule: Module,
verboseName?: string,
};
type ModuleList = {
[number]: ?ModuleDefinition,
__proto__: null,
...
};
export type RequireFn = (id: ModuleID | VerboseModuleNameForDev) => Exports;
export type DefineFn = (
factory: FactoryFn,
moduleId: number,
dependencyMap?: DependencyMap,
verboseName?: string,
inverseDependencies?: InverseDependencyMap,
) => void;
type VerboseModuleNameForDev = string;
type ModuleDefiner = (moduleId: ModuleID) => void;
global.__r = (metroRequire: RequireFn);
global[`${__METRO_GLOBAL_PREFIX__}__d`] = (define: DefineFn);
global.__c = clear;
global.__registerSegment = registerSegment;
var modules = clear();
// Don't use a Symbol here, it would pull in an extra polyfill with all sorts of
// additional stuff (e.g. Array.from).
const EMPTY = {};
const CYCLE_DETECTED = {};
const {hasOwnProperty} = {};
if (__DEV__) {
global.$RefreshReg$ = () => {};
global.$RefreshSig$ = () => type => type;
}
function clear(): ModuleList {
modules = (Object.create(null): ModuleList);
// We return modules here so that we can assign an initial value to modules
// when defining it. Otherwise, we would have to do "let modules = null",
// which will force us to add "nullthrows" everywhere.
return modules;
}
if (__DEV__) {
var verboseNamesToModuleIds: {
[key: string]: number,
__proto__: null,
...
} = Object.create(null);
var initializingModuleIds: Array<number> = [];
}
function define(
factory: FactoryFn,
moduleId: number,
dependencyMap?: DependencyMap,
): void {
if (modules[moduleId] != null) {
if (__DEV__) {
// (We take `inverseDependencies` from `arguments` to avoid an unused
// named parameter in `define` in production.
const inverseDependencies = arguments[4];
// If the module has already been defined and the define method has been
// called with inverseDependencies, we can hot reload it.
if (inverseDependencies) {
global.__accept(moduleId, factory, dependencyMap, inverseDependencies);
}
}
// prevent repeated calls to `global.nativeRequire` to overwrite modules
// that are already loaded
return;
}
const mod: ModuleDefinition = {
dependencyMap,
factory,
hasError: false,
importedAll: EMPTY,
importedDefault: EMPTY,
isInitialized: false,
publicModule: {exports: {}},
};
modules[moduleId] = mod;
if (__DEV__) {
// HMR
mod.hot = createHotReloadingObject();
// DEBUGGABLE MODULES NAMES
// we take `verboseName` from `arguments` to avoid an unused named parameter
// in `define` in production.
const verboseName: string | void = arguments[3];
if (verboseName) {
mod.verboseName = verboseName;
verboseNamesToModuleIds[verboseName] = moduleId;
}
}
}
function metroRequire(moduleId: ModuleID | VerboseModuleNameForDev): Exports {
if (__DEV__ && typeof moduleId === 'string') {
const verboseName = moduleId;
moduleId = verboseNamesToModuleIds[verboseName];
if (moduleId == null) {
throw new Error(`Unknown named module: "${verboseName}"`);
} else {
console.warn(
`Requiring module "${verboseName}" by name is only supported for ` +
'debugging purposes and will BREAK IN PRODUCTION!',
);
}
}
//$FlowFixMe: at this point we know that moduleId is a number
const moduleIdReallyIsNumber: number = moduleId;
if (__DEV__) {
const initializingIndex = initializingModuleIds.indexOf(
moduleIdReallyIsNumber,
);
if (initializingIndex !== -1) {
const cycle = initializingModuleIds
.slice(initializingIndex)
.map((id: number) =>
modules[id] ? modules[id].verboseName : '[unknown]',
);
if (shouldPrintRequireCycle(cycle)) {
cycle.push(cycle[0]); // We want to print A -> B -> A:
console.warn(
`Require cycle: ${cycle.join(' -> ')}\n\n` +
'Require cycles are allowed, but can result in uninitialized values. ' +
'Consider refactoring to remove the need for a cycle.',
);
}
}
}
const module = modules[moduleIdReallyIsNumber];
return module && module.isInitialized
? module.publicModule.exports
: guardedLoadModule(moduleIdReallyIsNumber, module);
}
// We print require cycles unless they match a pattern in the
// `requireCycleIgnorePatterns` configuration.
function shouldPrintRequireCycle(modules: $ReadOnlyArray<?string>): boolean {
const regExps =
global[__METRO_GLOBAL_PREFIX__ + '__requireCycleIgnorePatterns'];
if (!Array.isArray(regExps)) {
return true;
}
const isIgnored = (module: ?string) =>
module != null && regExps.some(regExp => regExp.test(module));
// Print the cycle unless any part of it is ignored
return modules.every(module => !isIgnored(module));
}
function metroImportDefault(
moduleId: ModuleID | VerboseModuleNameForDev,
): any | Exports {
if (__DEV__ && typeof moduleId === 'string') {
const verboseName = moduleId;
moduleId = verboseNamesToModuleIds[verboseName];
}
//$FlowFixMe: at this point we know that moduleId is a number
const moduleIdReallyIsNumber: number = moduleId;
if (
modules[moduleIdReallyIsNumber] &&
modules[moduleIdReallyIsNumber].importedDefault !== EMPTY
) {
return modules[moduleIdReallyIsNumber].importedDefault;
}
const exports: Exports = metroRequire(moduleIdReallyIsNumber);
const importedDefault: any | Exports =
exports && exports.__esModule ? exports.default : exports;
// $FlowFixMe The metroRequire call above will throw if modules[id] is null
return (modules[moduleIdReallyIsNumber].importedDefault = importedDefault);
}
metroRequire.importDefault = metroImportDefault;
function metroImportAll(
moduleId: ModuleID | VerboseModuleNameForDev | number,
): any | Exports | {[string]: any} {
if (__DEV__ && typeof moduleId === 'string') {
const verboseName = moduleId;
moduleId = verboseNamesToModuleIds[verboseName];
}
//$FlowFixMe: at this point we know that moduleId is a number
const moduleIdReallyIsNumber: number = moduleId;
if (
modules[moduleIdReallyIsNumber] &&
modules[moduleIdReallyIsNumber].importedAll !== EMPTY
) {
return modules[moduleIdReallyIsNumber].importedAll;
}
const exports: Exports = metroRequire(moduleIdReallyIsNumber);
let importedAll: Exports | {[string]: any};
if (exports && exports.__esModule) {
importedAll = exports;
} else {
importedAll = ({}: {[string]: any});
// Refrain from using Object.assign, it has to work in ES3 environments.
if (exports) {
for (const key: string in exports) {
if (hasOwnProperty.call(exports, key)) {
importedAll[key] = exports[key];
}
}
}
importedAll.default = exports;
}
// $FlowFixMe The metroRequire call above will throw if modules[id] is null
return (modules[moduleIdReallyIsNumber].importedAll = importedAll);
}
metroRequire.importAll = metroImportAll;
// The `require.context()` syntax is never executed in the runtime because it is converted
// to `require()` in `metro/src/ModuleGraph/worker/collectDependencies.js` after collecting
// dependencies. If the feature flag is not enabled then the conversion never takes place and this error is thrown (development only).
metroRequire.context = function fallbackRequireContext() {
if (__DEV__) {
throw new Error(
'The experimental Metro feature `require.context` is not enabled in your project.\nThis can be enabled by setting the `transformer.unstable_allowRequireContext` property to `true` in your Metro configuration.',
);
}
throw new Error(
'The experimental Metro feature `require.context` is not enabled in your project.',
);
};
// `require.resolveWeak()` is a compile-time primitive (see collectDependencies.js)
metroRequire.resolveWeak = function fallbackRequireResolveWeak() {
if (__DEV__) {
throw new Error(
'require.resolveWeak cannot be called dynamically. Ensure you are using the same version of `metro` and `metro-runtime`.',
);
}
throw new Error('require.resolveWeak cannot be called dynamically.');
};
let inGuard = false;
function guardedLoadModule(
moduleId: ModuleID,
module: ?ModuleDefinition,
): Exports {
if (!inGuard && global.ErrorUtils) {
inGuard = true;
let returnValue;
try {
returnValue = loadModuleImplementation(moduleId, module);
} catch (e) {
// TODO: (moti) T48204692 Type this use of ErrorUtils.
global.ErrorUtils.reportFatalError(e);
}
inGuard = false;
return returnValue;
} else {
return loadModuleImplementation(moduleId, module);
}
}
const ID_MASK_SHIFT = 16;
const LOCAL_ID_MASK = ~0 >>> ID_MASK_SHIFT;
function unpackModuleId(moduleId: ModuleID): {
localId: number,
segmentId: number,
...
} {
const segmentId = moduleId >>> ID_MASK_SHIFT;
const localId = moduleId & LOCAL_ID_MASK;
return {segmentId, localId};
}
metroRequire.unpackModuleId = unpackModuleId;
function packModuleId(value: {
localId: number,
segmentId: number,
...
}): ModuleID {
return (value.segmentId << ID_MASK_SHIFT) + value.localId;
}
metroRequire.packModuleId = packModuleId;
const moduleDefinersBySegmentID: Array<?ModuleDefiner> = [];
const definingSegmentByModuleID: Map<ModuleID, number> = new Map();
function registerSegment(
segmentId: number,
moduleDefiner: ModuleDefiner,
moduleIds: ?$ReadOnlyArray<ModuleID>,
): void {
moduleDefinersBySegmentID[segmentId] = moduleDefiner;
if (__DEV__) {
if (segmentId === 0 && moduleIds) {
throw new Error(
'registerSegment: Expected moduleIds to be null for main segment',
);
}
if (segmentId !== 0 && !moduleIds) {
throw new Error(
'registerSegment: Expected moduleIds to be passed for segment #' +
segmentId,
);
}
}
if (moduleIds) {
moduleIds.forEach(moduleId => {
if (!modules[moduleId] && !definingSegmentByModuleID.has(moduleId)) {
definingSegmentByModuleID.set(moduleId, segmentId);
}
});
}
}
function loadModuleImplementation(
moduleId: ModuleID,
module: ?ModuleDefinition,
): Exports {
if (!module && moduleDefinersBySegmentID.length > 0) {
const segmentId = definingSegmentByModuleID.get(moduleId) ?? 0;
const definer = moduleDefinersBySegmentID[segmentId];
if (definer != null) {
definer(moduleId);
module = modules[moduleId];
definingSegmentByModuleID.delete(moduleId);
}
}
const nativeRequire = global.nativeRequire;
if (!module && nativeRequire) {
const {segmentId, localId} = unpackModuleId(moduleId);
nativeRequire(localId, segmentId);
module = modules[moduleId];
}
if (!module) {
throw unknownModuleError(moduleId);
}
if (module.hasError) {
throw module.error;
}
if (__DEV__) {
var Systrace = requireSystrace();
var Refresh = requireRefresh();
}
// We must optimistically mark module as initialized before running the
// factory to keep any require cycles inside the factory from causing an
// infinite require loop.
module.isInitialized = true;
const {factory, dependencyMap} = module;
if (__DEV__) {
initializingModuleIds.push(moduleId);
}
try {
if (__DEV__) {
// $FlowIgnore: we know that __DEV__ is const and `Systrace` exists
Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId));
}
const moduleObject: Module = module.publicModule;
if (__DEV__) {
moduleObject.hot = module.hot;
var prevRefreshReg = global.$RefreshReg$;
var prevRefreshSig = global.$RefreshSig$;
if (Refresh != null) {
const RefreshRuntime = Refresh;
global.$RefreshReg$ = (type, id) => {
RefreshRuntime.register(type, moduleId + ' ' + id);
};
global.$RefreshSig$ =
RefreshRuntime.createSignatureFunctionForTransform;
}
}
moduleObject.id = moduleId;
// keep args in sync with with defineModuleCode in
// metro/src/Resolver/index.js
// and metro/src/ModuleGraph/worker.js
factory(
global,
metroRequire,
metroImportDefault,
metroImportAll,
moduleObject,
moduleObject.exports,
dependencyMap,
);
// avoid removing factory in DEV mode as it breaks HMR
if (!__DEV__) {
// $FlowFixMe: This is only sound because we never access `factory` again
module.factory = undefined;
module.dependencyMap = undefined;
}
if (__DEV__) {
// $FlowIgnore: we know that __DEV__ is const and `Systrace` exists
Systrace.endEvent();
if (Refresh != null) {
registerExportsForReactRefresh(Refresh, moduleObject.exports, moduleId);
}
}
return moduleObject.exports;
} catch (e) {
module.hasError = true;
module.error = e;
module.isInitialized = false;
module.publicModule.exports = undefined;
throw e;
} finally {
if (__DEV__) {
if (initializingModuleIds.pop() !== moduleId) {
throw new Error(
'initializingModuleIds is corrupt; something is terribly wrong',
);
}
global.$RefreshReg$ = prevRefreshReg;
global.$RefreshSig$ = prevRefreshSig;
}
}
}
function unknownModuleError(id: ModuleID): Error {
let message = 'Requiring unknown module "' + id + '".';
if (__DEV__) {
message +=
' If you are sure the module exists, try restarting Metro. ' +
'You may also want to run `yarn` or `npm install`.';
}
return Error(message);
}
if (__DEV__) {
// $FlowFixMe[prop-missing]
metroRequire.Systrace = {
beginEvent: (): void => {},
endEvent: (): void => {},
};
// $FlowFixMe[prop-missing]
metroRequire.getModules = (): ModuleList => {
return modules;
};
// HOT MODULE RELOADING
var createHotReloadingObject = function () {
const hot: HotModuleReloadingData = {
_acceptCallback: null,
_disposeCallback: null,
_didAccept: false,
accept: (callback?: HotModuleReloadingCallback): void => {
hot._didAccept = true;
hot._acceptCallback = callback;
},
dispose: (callback?: HotModuleReloadingCallback): void => {
hot._disposeCallback = callback;
},
};
return hot;
};
let reactRefreshTimeout: null | TimeoutID = null;
const metroHotUpdateModule = function (
id: ModuleID,
factory: FactoryFn,
dependencyMap: DependencyMap,
inverseDependencies: InverseDependencyMap,
) {
const mod = modules[id];
if (!mod) {
if (factory) {
// New modules are going to be handled by the define() method.
return;
}
throw unknownModuleError(id);
}
if (!mod.hasError && !mod.isInitialized) {
// The module hasn't actually been executed yet,
// so we can always safely replace it.
mod.factory = factory;
mod.dependencyMap = dependencyMap;
return;
}
const Refresh = requireRefresh();
const refreshBoundaryIDs = new Set<ModuleID>();
// In this loop, we will traverse the dependency tree upwards from the
// changed module. Updates "bubble" up to the closest accepted parent.
//
// If we reach the module root and nothing along the way accepted the update,
// we know hot reload is going to fail. In that case we return false.
//
// The main purpose of this loop is to figure out whether it's safe to apply
// a hot update. It is only safe when the update was accepted somewhere
// along the way upwards for each of its parent dependency module chains.
//
// We perform a topological sort because we may discover the same
// module more than once in the list of things to re-execute, and
// we want to execute modules before modules that depend on them.
//
// If we didn't have this check, we'd risk re-evaluating modules that
// have side effects and lead to confusing and meaningless crashes.
let didBailOut = false;
let updatedModuleIDs;
try {
updatedModuleIDs = topologicalSort(
[id], // Start with the changed module and go upwards
pendingID => {
const pendingModule = modules[pendingID];
if (pendingModule == null) {
// Nothing to do.
return [];
}
const pendingHot = pendingModule.hot;
if (pendingHot == null) {
throw new Error(
'[Refresh] Expected module.hot to always exist in DEV.',
);
}
// A module can be accepted manually from within itself.
let canAccept = pendingHot._didAccept;
if (!canAccept && Refresh != null) {
// Or React Refresh may mark it accepted based on exports.
const isBoundary = isReactRefreshBoundary(
Refresh,
pendingModule.publicModule.exports,
);
if (isBoundary) {
canAccept = true;
refreshBoundaryIDs.add(pendingID);
}
}
if (canAccept) {
// Don't look at parents.
return [];
}
// If we bubble through the roof, there is no way to do a hot update.
// Bail out altogether. This is the failure case.
const parentIDs = inverseDependencies[pendingID];
if (parentIDs.length === 0) {
// Reload the app because the hot reload can't succeed.
// This should work both on web and React Native.
performFullRefresh('No root boundary', {
source: mod,
failed: pendingModule,
});
didBailOut = true;
return [];
}
// This module can't handle the update but maybe all its parents can?
// Put them all in the queue to run the same set of checks.
return parentIDs;
},
() => didBailOut, // Should we stop?
).reverse();
} catch (e) {
if (e === CYCLE_DETECTED) {
performFullRefresh('Dependency cycle', {
source: mod,
});
return;
}
throw e;
}
if (didBailOut) {
return;
}
// If we reached here, it is likely that hot reload will be successful.
// Run the actual factories.
const seenModuleIDs = new Set<ModuleID>();
for (let i = 0; i < updatedModuleIDs.length; i++) {
const updatedID = updatedModuleIDs[i];
if (seenModuleIDs.has(updatedID)) {
continue;
}
seenModuleIDs.add(updatedID);
const updatedMod = modules[updatedID];
if (updatedMod == null) {
throw new Error('[Refresh] Expected to find the updated module.');
}
const prevExports = updatedMod.publicModule.exports;
const didError = runUpdatedModule(
updatedID,
updatedID === id ? factory : undefined,
updatedID === id ? dependencyMap : undefined,
);
const nextExports = updatedMod.publicModule.exports;
if (didError) {
// The user was shown a redbox about module initialization.
// There's nothing for us to do here until it's fixed.
return;
}
if (refreshBoundaryIDs.has(updatedID)) {
// Since we just executed the code for it, it's possible
// that the new exports make it ineligible for being a boundary.
const isNoLongerABoundary = !isReactRefreshBoundary(
Refresh,
nextExports,
);
// It can also become ineligible if its exports are incompatible
// with the previous exports.
// For example, if you add/remove/change exports, we'll want
// to re-execute the importing modules, and force those components
// to re-render. Similarly, if you convert a class component
// to a function, we want to invalidate the boundary.
const didInvalidate = shouldInvalidateReactRefreshBoundary(
Refresh,
prevExports,
nextExports,
);
if (isNoLongerABoundary || didInvalidate) {
// We'll be conservative. The only case in which we won't do a full
// reload is if all parent modules are also refresh boundaries.
// In that case we'll add them to the current queue.
const parentIDs = inverseDependencies[updatedID];
if (parentIDs.length === 0) {
// Looks like we bubbled to the root. Can't recover from that.
performFullRefresh(
isNoLongerABoundary
? 'No longer a boundary'
: 'Invalidated boundary',
{
source: mod,
failed: updatedMod,
},
);
return;
}
// Schedule all parent refresh boundaries to re-run in this loop.
for (let j = 0; j < parentIDs.length; j++) {
const parentID = parentIDs[j];
const parentMod = modules[parentID];
if (parentMod == null) {
throw new Error('[Refresh] Expected to find parent module.');
}
const canAcceptParent = isReactRefreshBoundary(
Refresh,
parentMod.publicModule.exports,
);
if (canAcceptParent) {
// All parents will have to re-run too.
refreshBoundaryIDs.add(parentID);
updatedModuleIDs.push(parentID);
} else {
performFullRefresh('Invalidated boundary', {
source: mod,
failed: parentMod,
});
return;
}
}
}
}
}
if (Refresh != null) {
// Debounce a little in case there are multiple updates queued up.
// This is also useful because __accept may be called multiple times.
if (reactRefreshTimeout == null) {
reactRefreshTimeout = setTimeout(() => {
reactRefreshTimeout = null;
// Update React components.
Refresh.performReactRefresh();
}, 30);
}
}
};
const topologicalSort = function <T>(
roots: Array<T>,
getEdges: T => Array<T>,
earlyStop: T => boolean,
): Array<T> {
const result = [];
const visited = new Set<mixed>();
const stack = new Set<mixed>();
function traverseDependentNodes(node: T): void {
if (stack.has(node)) {
throw CYCLE_DETECTED;
}
if (visited.has(node)) {
return;
}
visited.add(node);
stack.add(node);
const dependentNodes = getEdges(node);
if (earlyStop(node)) {
stack.delete(node);
return;
}
dependentNodes.forEach(dependent => {
traverseDependentNodes(dependent);
});
stack.delete(node);
result.push(node);
}
roots.forEach(root => {
traverseDependentNodes(root);
});
return result;
};
const runUpdatedModule = function (
id: ModuleID,
factory?: FactoryFn,
dependencyMap?: DependencyMap,
): boolean {
const mod = modules[id];
if (mod == null) {
throw new Error('[Refresh] Expected to find the module.');
}
const {hot} = mod;
if (!hot) {
throw new Error('[Refresh] Expected module.hot to always exist in DEV.');
}
if (hot._disposeCallback) {
try {
hot._disposeCallback();
} catch (error) {
console.error(
`Error while calling dispose handler for module ${id}: `,
error,
);
}
}
if (factory) {
mod.factory = factory;
}
if (dependencyMap) {
mod.dependencyMap = dependencyMap;
}
mod.hasError = false;
mod.error = undefined;
mod.importedAll = EMPTY;
mod.importedDefault = EMPTY;
mod.isInitialized = false;
const prevExports = mod.publicModule.exports;
mod.publicModule.exports = {};
hot._didAccept = false;
hot._acceptCallback = null;
hot._disposeCallback = null;
metroRequire(id);
if (mod.hasError) {
// This error has already been reported via a redbox.
// We know it's likely a typo or some mistake that was just introduced.
// Our goal now is to keep the rest of the application working so that by
// the time user fixes the error, the app isn't completely destroyed
// underneath the redbox. So we'll revert the module object to the last
// successful export and stop propagating this update.
mod.hasError = false;
mod.isInitialized = true;
mod.error = null;
mod.publicModule.exports = prevExports;
// We errored. Stop the update.
return true;
}
if (hot._acceptCallback) {
try {
hot._acceptCallback();
} catch (error) {
console.error(
`Error while calling accept handler for module ${id}: `,
error,
);
}
}
// No error.
return false;
};
const performFullRefresh = (
reason: string,
modules: $ReadOnly<{
source?: ModuleDefinition,
failed?: ModuleDefinition,
}>,
) => {
/* global window */
if (
typeof window !== 'undefined' &&
window.location != null &&
typeof window.location.reload === 'function'
) {
window.location.reload();
} else {
const Refresh = requireRefresh();
if (Refresh != null) {
const sourceName = modules.source?.verboseName ?? 'unknown';
const failedName = modules.failed?.verboseName ?? 'unknown';
Refresh.performFullRefresh(
`Fast Refresh - ${reason} <${sourceName}> <${failedName}>`,
);
} else {
console.warn('Could not reload the application after an edit.');
}
}
};
// Modules that only export components become React Refresh boundaries.
var isReactRefreshBoundary = function (
Refresh: any,
moduleExports: Exports,
): boolean {
if (Refresh.isLikelyComponentType(moduleExports)) {
return true;
}
if (moduleExports == null || typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
return false;
}
let hasExports = false;
let areAllExportsComponents = true;
for (const key in moduleExports) {
hasExports = true;
if (key === '__esModule') {
continue;
}
const desc = Object.getOwnPropertyDescriptor<any>(moduleExports, key);
if (desc && desc.get) {
// Don't invoke getters as they may have side effects.
return false;
}
const exportValue = moduleExports[key];
if (!Refresh.isLikelyComponentType(exportValue)) {
areAllExportsComponents = false;
}
}
return hasExports && areAllExportsComponents;
};
var shouldInvalidateReactRefreshBoundary = (
Refresh: any,
prevExports: Exports,
nextExports: Exports,
) => {
const prevSignature = getRefreshBoundarySignature(Refresh, prevExports);
const nextSignature = getRefreshBoundarySignature(Refresh, nextExports);
if (prevSignature.length !== nextSignature.length) {
return true;
}
for (let i = 0; i < nextSignature.length; i++) {
if (prevSignature[i] !== nextSignature[i]) {
return true;
}
}
return false;
};
// When this signature changes, it's unsafe to stop at this refresh boundary.
var getRefreshBoundarySignature = (
Refresh: any,
moduleExports: Exports,
): Array<mixed> => {
const signature = [];
signature.push(Refresh.getFamilyByType(moduleExports));
if (moduleExports == null || typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
// (This is important for legacy environments.)
return signature;
}
for (const key in moduleExports) {
if (key === '__esModule') {
continue;
}
const desc = Object.getOwnPropertyDescriptor<any>(moduleExports, key);
if (desc && desc.get) {
continue;
}
const exportValue = moduleExports[key];
signature.push(key);
signature.push(Refresh.getFamilyByType(exportValue));
}
return signature;
};
var registerExportsForReactRefresh = (
Refresh: any,
moduleExports: Exports,
moduleID: ModuleID,
) => {
Refresh.register(moduleExports, moduleID + ' %exports%');
if (moduleExports == null || typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
// (This is important for legacy environments.)
return;
}
for (const key in moduleExports) {
const desc = Object.getOwnPropertyDescriptor<any>(moduleExports, key);
if (desc && desc.get) {
// Don't invoke getters as they may have side effects.