forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranspiled-module.ts
More file actions
1202 lines (1052 loc) · 34.8 KB
/
transpiled-module.ts
File metadata and controls
1202 lines (1052 loc) · 34.8 KB
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
// eslint-disable-next-line max-classes-per-file
import { flattenDeep } from 'lodash-es';
import { actions, dispatch } from 'codesandbox-api';
import _debug from '@codesandbox/common/lib/utils/debug';
import hashsum from 'hash-sum';
import * as pathUtils from '@codesandbox/common/lib/utils/path';
import { Module } from './types/module';
import { SourceMap } from './transpilers/utils/get-source-map';
import ModuleError from './errors/module-error';
import ModuleWarning from './errors/module-warning';
import { WarningStructure } from './transpilers/utils/worker-warning-handler';
import resolveDependency from './loaders/dependency-resolver';
import evaluate from './loaders/eval';
import Manager, { HMRStatus } from './manager';
import HMR from './hmr';
import { splitQueryFromPath } from './utils/query-path';
import delay from '../utils/delay';
import { measure, endMeasure } from '../utils/metrics';
declare const BrowserFS: any;
const debug = _debug('cs:compiler:transpiled-module');
export type ChildModule = Module & {
parent: Module;
};
class ModuleSource {
fileName: string;
compiledCode: string;
sourceMap: SourceMap | undefined;
sourceEqualsCompiled: boolean;
constructor(
fileName: string,
compiledCode: string,
sourceMap: SourceMap | undefined,
sourceEqualsCompiled = false
) {
this.fileName = fileName;
this.compiledCode = compiledCode;
this.sourceMap = sourceMap;
this.sourceEqualsCompiled = sourceEqualsCompiled;
}
}
export type SerializedTranspiledModule = {
module: Module;
query: string;
source?: ModuleSource;
sourceEqualsCompiled: boolean;
assets: {
[name: string]: ModuleSource;
};
isEntry: boolean;
isTestFile: boolean;
childModules: Array<string>;
/**
* All extra modules emitted by the loader
*/
emittedAssets: Array<ModuleSource>;
initiators: Array<string>;
dependencies: Array<string>;
asyncDependencies: Array<string>;
transpilationDependencies: Array<string>;
transpilationInitiators: Array<string>;
warnings: WarningStructure[];
hasMissingDependencies: boolean;
};
/* eslint-disable no-use-before-define */
export type LoaderContext = {
emitWarning: (warning: WarningStructure) => void;
emitError: (error: Error) => void;
emitModule: (
title: string,
code: string,
currentPath?: string,
overwrite?: boolean,
isChild?: boolean
) => TranspiledModule;
emitFile: (name: string, content: string, sourceMap: SourceMap) => void;
options: {
context: string;
config?: object;
[key: string]: any;
};
webpack: boolean;
sourceMap: boolean;
target: string;
path: string;
getModules: () => Array<Module>;
addTranspilationDependency: (
depPath: string,
options?: {
isAbsolute?: boolean;
isEntry?: boolean;
}
) => void;
resolveTranspiledModule: (
depPath: string,
options?: {
isAbsolute?: boolean;
ignoredExtensions?: Array<string>;
}
) => TranspiledModule;
resolveTranspiledModuleAsync: (
depPath: string,
options?: {
isAbsolute?: boolean;
ignoredExtensions?: Array<string>;
}
) => Promise<TranspiledModule>;
addDependency: (
depPath: string,
options?: {
isAbsolute?: boolean;
isEntry?: boolean;
}
) => void;
addDependenciesInDirectory: (
depPath: string,
options?: {
isAbsolute?: boolean;
isEntry?: boolean;
}
) => void;
_module: TranspiledModule;
// Remaining loaders after current loader
remainingRequests: string;
template: string;
};
/* eslint-enable */
export type Compilation = {
id: string;
exports: any;
globals: object | undefined;
hot: {
accept: (() => void) | ((arg: string | string[], cb: () => void) => void);
decline: (path: string | Array<string>) => void;
dispose: (cb: () => void) => void;
data: Object;
status: () => HMRStatus;
addStatusHandler: (cb: (status: HMRStatus) => void) => void;
removeStatusHandler: (cb: (status: HMRStatus) => void) => void;
};
};
export default class TranspiledModule {
module: Module;
query: string;
previousSource: ModuleSource | undefined;
source: ModuleSource | undefined;
assets: {
[name: string]: ModuleSource;
};
isEntry: boolean;
childModules: Array<TranspiledModule>;
errors: Array<ModuleError>;
warnings: Array<ModuleWarning>;
/**
* All extra modules emitted by the loader
*/
emittedAssets: Array<ModuleSource>;
compilation: Compilation | undefined;
initiators: Set<TranspiledModule>; // eslint-disable-line no-use-before-define
dependencies: Set<TranspiledModule>; // eslint-disable-line no-use-before-define
asyncDependencies: Array<Promise<TranspiledModule>>; // eslint-disable-line no-use-before-define
transpilationDependencies: Set<TranspiledModule>;
transpilationInitiators: Set<TranspiledModule>;
// Unique identifier
hash: string;
isTestFile: boolean = false;
/**
* Set how this module handles HMR. The default is undefined, which means
* that we handle the HMR like CodeSandbox does.
*/
hmrConfig: HMR | undefined;
hasMissingDependencies: boolean = false;
/**
* Create a new TranspiledModule, a transpiled module is a module that contains
* all info for transpilation and compilation. Note that there can be multiple
* transpiled modules for 1 module, since a same module can have different loaders
* attached using queries.
* @param {*} module
* @param {*} query A webpack query, eg: "url-loader?mimetype=image/png"
*/
constructor(module: Module, query: string = '') {
this.module = module;
this.query = query;
this.errors = [];
this.warnings = [];
this.childModules = [];
this.transpilationDependencies = new Set();
this.dependencies = new Set();
this.asyncDependencies = [];
this.transpilationInitiators = new Set();
this.initiators = new Set();
this.isEntry = false;
this.isTestFile = false;
this.hash = hashsum(`${this.module.path}:${this.query}`);
}
getId(): string {
return `${this.module.path}:${this.query}`;
}
dispose(manager: Manager) {
if (this.hmrConfig) {
// If this is a hot module we fully reload the application, same as Webpack v2.
manager.markHardReload();
}
this.reset();
// Reset parents
this.initiators.forEach(tModule => {
tModule.resetTranspilation();
});
// There are no other modules calling this module, so we run a function on
// all transpilers that clears side effects if there are any. Example:
// Remove CSS styles from the dom.
manager.preset.getLoaders(this.module, this.query).forEach(t => {
if (t.transpiler.cleanModule) {
t.transpiler.cleanModule(this.getLoaderContext(manager, t.options));
}
});
manager.removeTranspiledModule(this);
}
reset() {
// We don't reset the compilation if itself and its parents if HMR is
// accepted for this module. We only mark it as changed so we can properly
// handle the update in the evaluation.
this.childModules.forEach(m => {
m.reset();
});
this.childModules = [];
this.emittedAssets = [];
this.resetTranspilation();
this.setIsEntry(false);
this.setIsTestFile(false);
}
resetTranspilation() {
Array.from(this.transpilationInitiators)
.filter(t => t.source)
.forEach(dep => {
dep.resetTranspilation();
});
this.previousSource = this.source;
this.source = null;
this.errors = [];
this.warnings = [];
Array.from(this.dependencies).forEach(t => {
t.initiators.delete(this);
});
// Don't do it for transpilation dependencies, since those cannot be traced back since we also reset transpilation of them.
this.dependencies.clear();
this.transpilationDependencies.clear();
this.asyncDependencies = [];
}
resetCompilation() {
if (this.hmrConfig && this.hmrConfig.isHot()) {
this.hmrConfig.setDirty(true);
} else {
if (this.compilation) {
this.compilation = null;
}
Array.from(this.initiators)
.filter(t => t.compilation)
.forEach(dep => {
dep.resetCompilation();
});
Array.from(this.transpilationInitiators)
.filter(t => t.compilation)
.forEach(dep => {
dep.resetCompilation();
});
// If this is an entry we want all direct entries to be reset as well.
// Entries generally have side effects
if (this.isEntry) {
Array.from(this.dependencies)
.filter(t => t.compilation && t.isEntry)
.forEach(dep => {
dep.resetCompilation();
});
}
}
}
/**
* Determines if this is a module that should be transpiled if updated. If this
* is a transpilationDependency that's updated then it should not get transpiled, but the parent should.
*/
shouldTranspile(): boolean {
return (
!this.source &&
!this.isTestFile &&
!(this.initiators.size === 0 && this.transpilationInitiators.size > 0)
);
}
async addDependency(
manager: Manager,
depPath: string,
options: {
isAbsolute?: boolean;
isEntry?: boolean;
} = {},
isTranspilationDep: boolean = false
) {
if (depPath.startsWith('codesandbox-api')) {
return;
}
try {
const tModule = await manager.resolveTranspiledModule(
depPath,
options && options.isAbsolute ? '/' : this.module.path
);
if (isTranspilationDep) {
this.transpilationDependencies.add(tModule);
tModule.transpilationInitiators.add(this);
} else {
this.dependencies.add(tModule);
tModule.initiators.add(this);
}
if (options.isEntry) {
tModule.setIsEntry(true);
}
} catch (e) {
if (e.type === 'module-not-found' && e.isDependency) {
const { queryPath } = splitQueryFromPath(depPath);
this.asyncDependencies.push(
manager.downloadDependency(e.path, this, queryPath)
);
} else {
// When a custom file resolver is given to the manager we will try
// to resolve using this file resolver. If that fails we will still
// mark the dependency as having missing deps.
if (manager.fileResolver) {
this.asyncDependencies.push(
// eslint-disable-next-line
new Promise(async resolve => {
try {
const tModule = await manager.resolveTranspiledModule(
depPath,
options && options.isAbsolute ? '/' : this.module.path,
undefined,
true
);
if (isTranspilationDep) {
this.transpilationDependencies.add(tModule);
tModule.transpilationInitiators.add(this);
} else {
this.dependencies.add(tModule);
tModule.initiators.add(this);
}
if (options.isEntry) {
tModule.setIsEntry(true);
}
resolve(tModule);
} catch (err) {
if (process.env.NODE_ENV === 'development') {
console.error(
'Problem while trying to fetch file from custom fileResolver'
);
console.error(err);
}
this.hasMissingDependencies = true;
}
})
);
return;
}
// Don't throw the error, we want to throw this error during evaluation
// so we get the correct line as error
// ... Thank you so much for this younger Ives, you saved me here.
if (process.env.NODE_ENV === 'development') {
console.error(e);
}
this.hasMissingDependencies = true;
}
}
}
update(module: Module): TranspiledModule {
if (this.module.path !== module.path || this.module.code !== module.code) {
this.module = module;
this.resetTranspilation();
}
return this;
}
createSourceForAsset = (
name: string,
content: string,
sourceMap: SourceMap
) => new ModuleSource(name, content, sourceMap);
getLoaderContext(
manager: Manager,
transpilerOptions: Object = {}
): LoaderContext {
return {
emitWarning: warning => {
this.warnings.push(new ModuleWarning(this, warning));
},
emitError: error => {
this.errors.push(new ModuleError(this, error));
},
emitModule: (
path: string,
code: string,
directoryPath: string = pathUtils.dirname(this.module.path),
overwrite = true,
isChild = true
) => {
const queryPath = path.split('!');
// pop() mutates queryPath, queryPath is now just the loaders
const modulePath = queryPath.pop();
const moduleCopy: ChildModule = {
path: pathUtils.join(directoryPath, modulePath),
parent: this.module,
code,
};
let transpiledModule: TranspiledModule;
if (!overwrite) {
try {
transpiledModule = manager.getTranspiledModule(
moduleCopy,
queryPath.join('!')
);
transpiledModule.update(moduleCopy);
} catch (e) {
/* Nothing is here, just continue */
}
}
transpiledModule =
transpiledModule ||
manager.addTranspiledModule(moduleCopy, queryPath.join('!'));
if (isChild) {
this.childModules.push(transpiledModule);
}
this.dependencies.add(transpiledModule);
transpiledModule.initiators.add(this);
return transpiledModule;
},
emitFile: (name: string, content: string, sourceMap: SourceMap) => {
this.assets[name] = this.createSourceForAsset(name, content, sourceMap);
},
// Add an explicit transpilation dependency, this is needed for loaders
// that include the source of another file by themselves, we need to
// force transpilation to rebuild the file
addTranspilationDependency: (depPath: string, options) => {
this.addDependency(manager, depPath, options, true);
},
addDependency: async (depPath: string, options = {}) => {
this.addDependency(manager, depPath, options);
},
addDependenciesInDirectory: (folderPath: string, options = {}) => {
const tModules = manager.resolveTranspiledModulesInDirectory(
folderPath,
options && options.isAbsolute ? '/' : this.module.path
);
tModules.forEach(tModule => {
this.dependencies.add(tModule);
tModule.initiators.add(this);
if (options.isEntry) {
tModule.setIsEntry(true);
}
});
},
resolveTranspiledModule: (depPath: string, options = {}) =>
manager.resolveTranspiledModule(
depPath,
options.isAbsolute ? '/' : this.module.path,
options.ignoredExtensions
),
resolveTranspiledModuleAsync: (depPath: string, options = {}) =>
manager.resolveTranspiledModuleAsync(
depPath,
options.isAbsolute ? null : this,
options.ignoredExtensions
),
getModules: (): Array<Module> => manager.getModules(),
options: {
context: pathUtils.dirname(this.module.path),
configurations: manager.configurations,
...transpilerOptions,
},
webpack: true,
sourceMap: true,
target: 'web',
_module: this,
path: this.module.path,
template: manager.preset.name,
remainingRequests: '', // will be filled during transpilation
};
}
/**
* Mark the transpiled module as entry (or not), this is needed to let the
* cleanup know that this module can have no initiators, but is still required.
* @param {*} isEntry
*/
setIsEntry(isEntry: boolean) {
this.isEntry = isEntry;
}
/**
* Mark if this is a test file. If this is a test file we know that we don't
* need to do any refresh or fixing when an error is thrown by the module. It's
* not a vital module after all.
*/
setIsTestFile(isTestFile: boolean) {
this.isTestFile = isTestFile;
}
/**
* Transpile the module, it takes in all loaders from the default loaders +
* query string and passes the result from loader to loader. During transpilation
* dependencies can be added, these dependencies will be transpiled concurrently
* after the initial transpilation finished.
* @param {*} manager
*/
async doTranspile(manager: Manager) {
this.hasMissingDependencies = false;
// Remove this module from the initiators of old deps, so we can populate a
// fresh cache
this.dependencies.forEach(tModule => {
tModule.initiators.delete(this);
});
this.transpilationDependencies.forEach(tModule => {
tModule.transpilationInitiators.delete(this);
});
this.childModules.forEach(tModule => {
tModule.dispose(manager);
});
this.dependencies.clear();
this.transpilationDependencies.clear();
this.childModules.length = 0;
this.errors = [];
this.warnings = [];
let code = this.module.code || '';
let finalSourceMap = null;
const { requires } = this.module;
if (requires != null && this.query === '') {
// We now know that this has been transpiled on the server, so we shortcut
const loaderContext = this.getLoaderContext(manager, {});
// These are precomputed requires, for npm dependencies
requires.forEach(r => {
if (r.indexOf('glob:') === 0) {
const reGlob = r.replace('glob:', '');
loaderContext.addDependenciesInDirectory(reGlob);
} else {
loaderContext.addDependency(r);
}
});
// eslint-disable-next-line
code = this.module.code;
} else {
const transpilers = manager.preset.getLoaders(this.module, this.query);
for (let i = 0; i < transpilers.length; i += 1) {
const transpilerConfig = transpilers[i];
const loaderContext = this.getLoaderContext(
manager,
transpilerConfig.options || {}
);
loaderContext.remainingRequests = transpilers
.slice(i + 1)
.map(transpiler => transpiler.transpiler.name)
.concat([this.module.path])
.join('!');
const measureKey = `transpile-${
transpilerConfig.transpiler.name
}-${this.getId()}`;
try {
measure(measureKey);
const {
transpiledCode,
sourceMap,
// eslint-disable-next-line no-await-in-loop
} = await transpilerConfig.transpiler.transpile(code, loaderContext);
endMeasure(measureKey, { silent: true });
if (this.errors.length) {
throw this.errors[0];
}
code = transpiledCode;
finalSourceMap = sourceMap;
} catch (e) {
e.fileName = loaderContext.path;
e.tModule = this;
this.resetTranspilation();
// Compilation should also be reset, since the code will be different now
// we don't have a transpilation.
this.resetCompilation();
manager.clearCache();
throw e;
}
}
this.logWarnings();
}
const sourceEqualsCompiled = code === this.module.code;
const sourceURL = `//# sourceURL=${location.origin}${this.module.path}${
this.query ? `?${this.hash}` : ''
}`;
// Add the source of the file by default, this is important for source mapping
// errors back to their origin
code = `${code}\n${sourceURL}`;
this.source = new ModuleSource(
this.module.path,
code,
finalSourceMap,
sourceEqualsCompiled
);
if (
this.previousSource &&
this.previousSource.compiledCode !== this.source.compiledCode
) {
const hasHMR = manager.preset
.getLoaders(this.module, this.query)
.some(t =>
t.transpiler.HMREnabled == null ? true : t.transpiler.HMREnabled
);
if (!hasHMR) {
manager.markHardReload();
} else {
this.resetCompilation();
}
}
await Promise.all(
this.asyncDependencies.map(async p => {
try {
const tModule = await p;
this.dependencies.add(tModule);
tModule.initiators.add(this);
} catch (e) {
/* let this handle at evaluation */
}
})
);
this.asyncDependencies = [];
await Promise.all(
flattenDeep([
...Array.from(this.transpilationInitiators).map(t =>
t.transpile(manager)
),
...Array.from(this.dependencies).map(t => t.transpile(manager)),
])
);
return this;
}
transpile(manager: Manager): Promise<this> {
if (this.source) {
return Promise.resolve(this);
}
const id = this.getId();
if (manager.transpileJobs[id]) {
if (manager.transpileJobs[id] === true) {
// Is currently being transpiled, and the promise hasn't been set yet
// because it is working on executing the promise. This rare case only
// happens when we have a dependency loop, which could result in a
// StackTraceOverflow. Dependency loop: A -> B -> C -> A -> B -> C
return new Promise(async resolve => {
while (!this.source && manager.transpileJobs[id] === true) {
// eslint-disable-next-line
await delay(10);
}
if (manager.transpileJobs[id] && manager.transpileJobs[id] !== true) {
resolve(manager.transpileJobs[id] as Promise<this>);
} else {
resolve(this);
}
});
}
return manager.transpileJobs[id] as Promise<this>;
}
manager.transpileJobs[id] = true;
// eslint-disable-next-line
return (manager.transpileJobs[id] = this.doTranspile(manager)).finally(
() => {
delete manager.transpileJobs[id];
}
);
}
logWarnings = () => {
if (this.warnings.length) {
this.warnings.forEach(warning => {
console.warn(warning.message); // eslint-disable-line no-console
dispatch(
actions.correction.show(warning.message, {
line: warning.lineNumber,
column: warning.columnNumber,
path: warning.path,
source: warning.source,
severity: warning.severity || 'warning',
})
);
});
}
};
isCompilationCached = (globals?: object) => {
if (!this.compilation || !this.compilation.exports) {
return false;
}
if (this.compilation.globals === globals) {
return true;
}
return false;
};
evaluate(
manager: Manager,
{
asUMD = false,
force = false,
globals,
}: { asUMD?: boolean; force?: boolean; globals?: any } = {},
initiator?: TranspiledModule
) {
if (this.source == null) {
if (this.module.path === '/node_modules/empty/index.js') {
return {};
}
if (this.module.path.startsWith('/node_modules')) {
if (process.env.NODE_ENV === 'development') {
console.warn(
`[WARN] Sandpack: loading an untranspiled module: ${this.module.path}`
);
}
// This code is probably required as a dynamic require. Since we can
// assume that node_modules dynamic requires are only done for node
// utilites we will just set the transpiled code according to how
// node handles that.
let code = this.module.path.endsWith('.json')
? `module.exports = JSON.parse(${JSON.stringify(this.module.code)})`
: this.module.code;
code += `\n//# sourceURL=${location.origin}${this.module.path}${
this.query ? `?${this.hash}` : ''
}`;
this.source = new ModuleSource(this.module.path, code, null);
if (initiator) {
initiator.dependencies.add(this);
this.initiators.add(initiator);
}
} else {
// This scenario only happens when we are in an inconsistent state, the quickest way to solve
// this state is to just hard reload everything.
manager.clearCache();
throw new Error(`${this.module.path} hasn't been transpiled yet.`);
}
}
const localModule = this.module;
if (manager.webpackHMR) {
if (!this.compilation) {
const shouldReloadPage = this.hmrConfig
? this.hmrConfig.isDeclined(this.isEntry)
: this.isEntry && !this.isTestFile;
if (shouldReloadPage) {
if (manager.isFirstLoad) {
// We're in a reload loop! Ignore all caches!
manager.clearCache();
manager.deleteAPICache().then(() => {
document.location.reload();
});
} else {
document.location.reload();
}
return {};
}
} else if (
!this.isTestFile &&
(!this.hmrConfig || !this.hmrConfig.isDirty())
) {
return this.compilation.exports;
}
} else if (this.isCompilationCached(globals) && !this.isEntry) {
return this.compilation.exports;
}
if (this.hmrConfig) {
/* eslint-disable no-param-reassign */
manager.setHmrStatus('dispose');
// Call module.hot.dispose handler
// https://webpack.js.org/api/hot-module-replacement/#dispose-or-adddisposehandler-
this.hmrConfig.callDisposeHandler();
manager.setHmrStatus('idle');
/* eslint-enable */
}
const hotData = this.hmrConfig ? this.hmrConfig.data : undefined;
this.compilation = this.compilation || {
id: this.getId(),
exports: {},
globals,
hot: {
accept: (path: string | Array<string>, cb) => {
if (
typeof path === 'undefined' ||
typeof path !== 'string' ||
!Array.isArray(path)
) {
// Self mark hot
this.hmrConfig = this.hmrConfig || new HMR();
if (this.hmrConfig) {
const { hmrConfig } = this;
hmrConfig.setType('accept');
hmrConfig.setSelfAccepted(true);
}
} else {
const paths = typeof path === 'string' ? [path] : path;
paths.forEach(async p => {
const tModule = await manager.resolveTranspiledModule(
p,
this.module.path
);
tModule.hmrConfig = tModule.hmrConfig || new HMR();
const { hmrConfig } = tModule;
hmrConfig.setType('accept');
hmrConfig.setAcceptCallback(cb);
});
}
manager.enableWebpackHMR();
},
decline: (path: string | Array<string>) => {
if (typeof path === 'undefined') {
this.hmrConfig = this.hmrConfig || new HMR();
this.hmrConfig.setType('decline');
this.resetCompilation();
} else {
const paths = typeof path === 'string' ? [path] : path;
paths.forEach(async p => {
const tModule = await manager.resolveTranspiledModule(
p,
this.module.path
);
tModule.hmrConfig = tModule.hmrConfig || new HMR();
tModule.hmrConfig.setType('decline');
tModule.resetCompilation();
});
}
manager.enableWebpackHMR();
},
dispose: (cb: () => void) => {
this.hmrConfig = this.hmrConfig || new HMR();
this.hmrConfig.setDisposeHandler(cb);
},
data: hotData,
status: () => manager.hmrStatus,
addStatusHandler: manager.addStatusHandler,
removeStatusHandler: manager.removeStatusHandler,
},
};
if (this.compilation.hot) {
this.compilation.hot.data = hotData;
}
const transpiledModule = this;
try {
// eslint-disable-next-line no-inner-declarations
function require(path: string) {
if (path === '') {
throw new Error('Cannot import an empty path');
}
const usedPath = manager.getPresetAliasedPath(path);
const bfsModule = BrowserFS.BFSRequire(usedPath);
if (path === 'os') {
const os = require('os-browserify');
os.homedir = () => '/home/sandbox';
return os;
}
if (bfsModule) {
return bfsModule;
}
if (path === 'module') {
return class NodeModule {
filename = undefined;
id = undefined;
loaded = false;
static _resolveFilename(toPath: string, module) {
if (module.filename == null) {
throw new Error('Module has no filename');
}
const m = manager.resolveModule(toPath, module.filename);
return m.path;
}
static _nodeModulePaths() {
return [];
}
};
}
// So it must be a dependency
if (path.startsWith('codesandbox-api')) {
return resolveDependency(path);
}
const requiredTranspiledModule = manager.resolveTranspiledModule(
path,
localModule.path
);
// Check if this module has been evaluated before, if so return the exports