Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/loader.js
3290 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
'use strict';
6
/*---------------------------------------------------------------------------------------------
7
* Copyright (c) Microsoft Corporation. All rights reserved.
8
* Licensed under the MIT License. See License.txt in the project root for license information.
9
*--------------------------------------------------------------------------------------------*/
10
/*---------------------------------------------------------------------------------------------
11
*---------------------------------------------------------------------------------------------
12
*---------------------------------------------------------------------------------------------
13
*---------------------------------------------------------------------------------------------
14
*---------------------------------------------------------------------------------------------
15
* Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/
16
*---------------------------------------------------------------------------------------------
17
*---------------------------------------------------------------------------------------------
18
*---------------------------------------------------------------------------------------------
19
*---------------------------------------------------------------------------------------------
20
*--------------------------------------------------------------------------------------------*/
21
const _amdLoaderGlobal = this;
22
const _commonjsGlobal = typeof global === 'object' ? global : {};
23
var AMDLoader;
24
(function (AMDLoader) {
25
AMDLoader.global = _amdLoaderGlobal;
26
class Environment {
27
get isWindows() {
28
this._detect();
29
return this._isWindows;
30
}
31
get isNode() {
32
this._detect();
33
return this._isNode;
34
}
35
get isElectronRenderer() {
36
this._detect();
37
return this._isElectronRenderer;
38
}
39
get isWebWorker() {
40
this._detect();
41
return this._isWebWorker;
42
}
43
get isElectronNodeIntegrationWebWorker() {
44
this._detect();
45
return this._isElectronNodeIntegrationWebWorker;
46
}
47
constructor() {
48
this._detected = false;
49
this._isWindows = false;
50
this._isNode = false;
51
this._isElectronRenderer = false;
52
this._isWebWorker = false;
53
this._isElectronNodeIntegrationWebWorker = false;
54
}
55
_detect() {
56
if (this._detected) {
57
return;
58
}
59
this._detected = true;
60
this._isWindows = Environment._isWindows();
61
this._isNode = (typeof module !== 'undefined' && !!module.exports);
62
this._isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer');
63
this._isWebWorker = (typeof AMDLoader.global.importScripts === 'function');
64
this._isElectronNodeIntegrationWebWorker = this._isWebWorker && (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'worker');
65
}
66
static _isWindows() {
67
if (typeof navigator !== 'undefined') {
68
if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) {
69
return true;
70
}
71
}
72
if (typeof process !== 'undefined') {
73
return (process.platform === 'win32');
74
}
75
return false;
76
}
77
}
78
AMDLoader.Environment = Environment;
79
})(AMDLoader || (AMDLoader = {}));
80
/*---------------------------------------------------------------------------------------------
81
* Copyright (c) Microsoft Corporation. All rights reserved.
82
* Licensed under the MIT License. See License.txt in the project root for license information.
83
*--------------------------------------------------------------------------------------------*/
84
var AMDLoader;
85
(function (AMDLoader) {
86
class LoaderEvent {
87
constructor(type, detail, timestamp) {
88
this.type = type;
89
this.detail = detail;
90
this.timestamp = timestamp;
91
}
92
}
93
AMDLoader.LoaderEvent = LoaderEvent;
94
class LoaderEventRecorder {
95
constructor(loaderAvailableTimestamp) {
96
this._events = [new LoaderEvent(1 /* LoaderEventType.LoaderAvailable */, '', loaderAvailableTimestamp)];
97
}
98
record(type, detail) {
99
this._events.push(new LoaderEvent(type, detail, AMDLoader.Utilities.getHighPerformanceTimestamp()));
100
}
101
getEvents() {
102
return this._events;
103
}
104
}
105
AMDLoader.LoaderEventRecorder = LoaderEventRecorder;
106
class NullLoaderEventRecorder {
107
record(type, detail) {
108
// Nothing to do
109
}
110
getEvents() {
111
return [];
112
}
113
}
114
NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder();
115
AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder;
116
})(AMDLoader || (AMDLoader = {}));
117
/*---------------------------------------------------------------------------------------------
118
* Copyright (c) Microsoft Corporation. All rights reserved.
119
* Licensed under the MIT License. See License.txt in the project root for license information.
120
*--------------------------------------------------------------------------------------------*/
121
var AMDLoader;
122
(function (AMDLoader) {
123
class Utilities {
124
/**
125
* This method does not take care of / vs \
126
*/
127
static fileUriToFilePath(isWindows, uri) {
128
uri = decodeURI(uri).replace(/%23/g, '#');
129
if (isWindows) {
130
if (/^file:\/\/\//.test(uri)) {
131
// This is a URI without a hostname => return only the path segment
132
return uri.substr(8);
133
}
134
if (/^file:\/\//.test(uri)) {
135
return uri.substr(5);
136
}
137
}
138
else {
139
if (/^file:\/\//.test(uri)) {
140
return uri.substr(7);
141
}
142
}
143
// Not sure...
144
return uri;
145
}
146
static startsWith(haystack, needle) {
147
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
148
}
149
static endsWith(haystack, needle) {
150
return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle;
151
}
152
// only check for "?" before "#" to ensure that there is a real Query-String
153
static containsQueryString(url) {
154
return /^[^\#]*\?/gi.test(url);
155
}
156
/**
157
* Does `url` start with http:// or https:// or file:// or / ?
158
*/
159
static isAbsolutePath(url) {
160
return /^((http:\/\/)|(https:\/\/)|(file:\/\/)|(\/))/.test(url);
161
}
162
static forEachProperty(obj, callback) {
163
if (obj) {
164
let key;
165
for (key in obj) {
166
if (obj.hasOwnProperty(key)) {
167
callback(key, obj[key]);
168
}
169
}
170
}
171
}
172
static isEmpty(obj) {
173
let isEmpty = true;
174
Utilities.forEachProperty(obj, () => {
175
isEmpty = false;
176
});
177
return isEmpty;
178
}
179
static recursiveClone(obj) {
180
if (!obj || typeof obj !== 'object' || obj instanceof RegExp) {
181
return obj;
182
}
183
if (!Array.isArray(obj) && Object.getPrototypeOf(obj) !== Object.prototype) {
184
// only clone "simple" objects
185
return obj;
186
}
187
let result = Array.isArray(obj) ? [] : {};
188
Utilities.forEachProperty(obj, (key, value) => {
189
if (value && typeof value === 'object') {
190
result[key] = Utilities.recursiveClone(value);
191
}
192
else {
193
result[key] = value;
194
}
195
});
196
return result;
197
}
198
static generateAnonymousModule() {
199
return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '===';
200
}
201
static isAnonymousModule(id) {
202
return Utilities.startsWith(id, '===anonymous');
203
}
204
static getHighPerformanceTimestamp() {
205
if (!this.PERFORMANCE_NOW_PROBED) {
206
this.PERFORMANCE_NOW_PROBED = true;
207
this.HAS_PERFORMANCE_NOW = (AMDLoader.global.performance && typeof AMDLoader.global.performance.now === 'function');
208
}
209
return (this.HAS_PERFORMANCE_NOW ? AMDLoader.global.performance.now() : Date.now());
210
}
211
}
212
Utilities.NEXT_ANONYMOUS_ID = 1;
213
Utilities.PERFORMANCE_NOW_PROBED = false;
214
Utilities.HAS_PERFORMANCE_NOW = false;
215
AMDLoader.Utilities = Utilities;
216
})(AMDLoader || (AMDLoader = {}));
217
/*---------------------------------------------------------------------------------------------
218
* Copyright (c) Microsoft Corporation. All rights reserved.
219
* Licensed under the MIT License. See License.txt in the project root for license information.
220
*--------------------------------------------------------------------------------------------*/
221
var AMDLoader;
222
(function (AMDLoader) {
223
function ensureError(err) {
224
if (err instanceof Error) {
225
return err;
226
}
227
const result = new Error(err.message || String(err) || 'Unknown Error');
228
if (err.stack) {
229
result.stack = err.stack;
230
}
231
return result;
232
}
233
AMDLoader.ensureError = ensureError;
234
;
235
class ConfigurationOptionsUtil {
236
/**
237
* Ensure configuration options make sense
238
*/
239
static validateConfigurationOptions(options) {
240
function defaultOnError(err) {
241
if (err.phase === 'loading') {
242
console.error('Loading "' + err.moduleId + '" failed');
243
console.error(err);
244
console.error('Here are the modules that depend on it:');
245
console.error(err.neededBy);
246
return;
247
}
248
if (err.phase === 'factory') {
249
console.error('The factory function of "' + err.moduleId + '" has thrown an exception');
250
console.error(err);
251
console.error('Here are the modules that depend on it:');
252
console.error(err.neededBy);
253
return;
254
}
255
}
256
options = options || {};
257
if (typeof options.baseUrl !== 'string') {
258
options.baseUrl = '';
259
}
260
if (typeof options.isBuild !== 'boolean') {
261
options.isBuild = false;
262
}
263
if (typeof options.paths !== 'object') {
264
options.paths = {};
265
}
266
if (typeof options.config !== 'object') {
267
options.config = {};
268
}
269
if (typeof options.catchError === 'undefined') {
270
options.catchError = false;
271
}
272
if (typeof options.recordStats === 'undefined') {
273
options.recordStats = false;
274
}
275
if (typeof options.urlArgs !== 'string') {
276
options.urlArgs = '';
277
}
278
if (typeof options.onError !== 'function') {
279
options.onError = defaultOnError;
280
}
281
if (!Array.isArray(options.ignoreDuplicateModules)) {
282
options.ignoreDuplicateModules = [];
283
}
284
if (options.baseUrl.length > 0) {
285
if (!AMDLoader.Utilities.endsWith(options.baseUrl, '/')) {
286
options.baseUrl += '/';
287
}
288
}
289
if (typeof options.cspNonce !== 'string') {
290
options.cspNonce = '';
291
}
292
if (typeof options.preferScriptTags === 'undefined') {
293
options.preferScriptTags = false;
294
}
295
if (options.nodeCachedData && typeof options.nodeCachedData === 'object') {
296
if (typeof options.nodeCachedData.seed !== 'string') {
297
options.nodeCachedData.seed = 'seed';
298
}
299
if (typeof options.nodeCachedData.writeDelay !== 'number' || options.nodeCachedData.writeDelay < 0) {
300
options.nodeCachedData.writeDelay = 1000 * 7;
301
}
302
if (!options.nodeCachedData.path || typeof options.nodeCachedData.path !== 'string') {
303
const err = ensureError(new Error('INVALID cached data configuration, \'path\' MUST be set'));
304
err.phase = 'configuration';
305
options.onError(err);
306
options.nodeCachedData = undefined;
307
}
308
}
309
return options;
310
}
311
static mergeConfigurationOptions(overwrite = null, base = null) {
312
let result = AMDLoader.Utilities.recursiveClone(base || {});
313
// Merge known properties and overwrite the unknown ones
314
AMDLoader.Utilities.forEachProperty(overwrite, (key, value) => {
315
if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') {
316
result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value);
317
}
318
else if (key === 'paths' && typeof result.paths !== 'undefined') {
319
AMDLoader.Utilities.forEachProperty(value, (key2, value2) => result.paths[key2] = value2);
320
}
321
else if (key === 'config' && typeof result.config !== 'undefined') {
322
AMDLoader.Utilities.forEachProperty(value, (key2, value2) => result.config[key2] = value2);
323
}
324
else {
325
result[key] = AMDLoader.Utilities.recursiveClone(value);
326
}
327
});
328
return ConfigurationOptionsUtil.validateConfigurationOptions(result);
329
}
330
}
331
AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil;
332
class Configuration {
333
constructor(env, options) {
334
this._env = env;
335
this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options);
336
this._createIgnoreDuplicateModulesMap();
337
this._createSortedPathsRules();
338
if (this.options.baseUrl === '') {
339
if (this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename && this._env.isNode) {
340
let nodeMain = this.options.nodeRequire.main.filename;
341
let dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
342
this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
343
}
344
}
345
}
346
_createIgnoreDuplicateModulesMap() {
347
// Build a map out of the ignoreDuplicateModules array
348
this.ignoreDuplicateModulesMap = {};
349
for (let i = 0; i < this.options.ignoreDuplicateModules.length; i++) {
350
this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true;
351
}
352
}
353
_createSortedPathsRules() {
354
// Create an array our of the paths rules, sorted descending by length to
355
// result in a more specific -> less specific order
356
this.sortedPathsRules = [];
357
AMDLoader.Utilities.forEachProperty(this.options.paths, (from, to) => {
358
if (!Array.isArray(to)) {
359
this.sortedPathsRules.push({
360
from: from,
361
to: [to]
362
});
363
}
364
else {
365
this.sortedPathsRules.push({
366
from: from,
367
to: to
368
});
369
}
370
});
371
this.sortedPathsRules.sort((a, b) => {
372
return b.from.length - a.from.length;
373
});
374
}
375
/**
376
* Clone current configuration and overwrite options selectively.
377
* @param options The selective options to overwrite with.
378
* @result A new configuration
379
*/
380
cloneAndMerge(options) {
381
return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options));
382
}
383
/**
384
* Get current options bag. Useful for passing it forward to plugins.
385
*/
386
getOptionsLiteral() {
387
return this.options;
388
}
389
_applyPaths(moduleId) {
390
let pathRule;
391
for (let i = 0, len = this.sortedPathsRules.length; i < len; i++) {
392
pathRule = this.sortedPathsRules[i];
393
if (AMDLoader.Utilities.startsWith(moduleId, pathRule.from)) {
394
let result = [];
395
for (let j = 0, lenJ = pathRule.to.length; j < lenJ; j++) {
396
result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length));
397
}
398
return result;
399
}
400
}
401
return [moduleId];
402
}
403
_addUrlArgsToUrl(url) {
404
if (AMDLoader.Utilities.containsQueryString(url)) {
405
return url + '&' + this.options.urlArgs;
406
}
407
else {
408
return url + '?' + this.options.urlArgs;
409
}
410
}
411
_addUrlArgsIfNecessaryToUrl(url) {
412
if (this.options.urlArgs) {
413
return this._addUrlArgsToUrl(url);
414
}
415
return url;
416
}
417
_addUrlArgsIfNecessaryToUrls(urls) {
418
if (this.options.urlArgs) {
419
for (let i = 0, len = urls.length; i < len; i++) {
420
urls[i] = this._addUrlArgsToUrl(urls[i]);
421
}
422
}
423
return urls;
424
}
425
/**
426
* Transform a module id to a location. Appends .js to module ids
427
*/
428
moduleIdToPaths(moduleId) {
429
if (this._env.isNode) {
430
const isNodeModule = (this.options.amdModulesPattern instanceof RegExp
431
&& !this.options.amdModulesPattern.test(moduleId));
432
if (isNodeModule) {
433
// This is a node module...
434
if (this.isBuild()) {
435
// ...and we are at build time, drop it
436
return ['empty:'];
437
}
438
else {
439
// ...and at runtime we create a `shortcut`-path
440
return ['node|' + moduleId];
441
}
442
}
443
}
444
let result = moduleId;
445
let results;
446
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.isAbsolutePath(result)) {
447
results = this._applyPaths(result);
448
for (let i = 0, len = results.length; i < len; i++) {
449
if (this.isBuild() && results[i] === 'empty:') {
450
continue;
451
}
452
if (!AMDLoader.Utilities.isAbsolutePath(results[i])) {
453
results[i] = this.options.baseUrl + results[i];
454
}
455
if (!AMDLoader.Utilities.endsWith(results[i], '.js') && !AMDLoader.Utilities.containsQueryString(results[i])) {
456
results[i] = results[i] + '.js';
457
}
458
}
459
}
460
else {
461
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.containsQueryString(result)) {
462
result = result + '.js';
463
}
464
results = [result];
465
}
466
return this._addUrlArgsIfNecessaryToUrls(results);
467
}
468
/**
469
* Transform a module id or url to a location.
470
*/
471
requireToUrl(url) {
472
let result = url;
473
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
474
result = this._applyPaths(result)[0];
475
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
476
result = this.options.baseUrl + result;
477
}
478
}
479
return this._addUrlArgsIfNecessaryToUrl(result);
480
}
481
/**
482
* Flag to indicate if current execution is as part of a build.
483
*/
484
isBuild() {
485
return this.options.isBuild;
486
}
487
shouldInvokeFactory(strModuleId) {
488
if (!this.options.isBuild) {
489
// outside of a build, all factories should be invoked
490
return true;
491
}
492
// during a build, only explicitly marked or anonymous modules get their factories invoked
493
if (AMDLoader.Utilities.isAnonymousModule(strModuleId)) {
494
return true;
495
}
496
if (this.options.buildForceInvokeFactory && this.options.buildForceInvokeFactory[strModuleId]) {
497
return true;
498
}
499
return false;
500
}
501
/**
502
* Test if module `moduleId` is expected to be defined multiple times
503
*/
504
isDuplicateMessageIgnoredFor(moduleId) {
505
return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId);
506
}
507
/**
508
* Get the configuration settings for the provided module id
509
*/
510
getConfigForModule(moduleId) {
511
if (this.options.config) {
512
return this.options.config[moduleId];
513
}
514
}
515
/**
516
* Should errors be caught when executing module factories?
517
*/
518
shouldCatchError() {
519
return this.options.catchError;
520
}
521
/**
522
* Should statistics be recorded?
523
*/
524
shouldRecordStats() {
525
return this.options.recordStats;
526
}
527
/**
528
* Forward an error to the error handler.
529
*/
530
onError(err) {
531
this.options.onError(err);
532
}
533
}
534
AMDLoader.Configuration = Configuration;
535
})(AMDLoader || (AMDLoader = {}));
536
/*---------------------------------------------------------------------------------------------
537
* Copyright (c) Microsoft Corporation. All rights reserved.
538
* Licensed under the MIT License. See License.txt in the project root for license information.
539
*--------------------------------------------------------------------------------------------*/
540
var AMDLoader;
541
(function (AMDLoader) {
542
/**
543
* Load `scriptSrc` only once (avoid multiple <script> tags)
544
*/
545
class OnlyOnceScriptLoader {
546
constructor(env) {
547
this._env = env;
548
this._scriptLoader = null;
549
this._callbackMap = {};
550
}
551
load(moduleManager, scriptSrc, callback, errorback) {
552
if (!this._scriptLoader) {
553
if (this._env.isWebWorker) {
554
this._scriptLoader = new WorkerScriptLoader();
555
}
556
else if (this._env.isElectronRenderer) {
557
const { preferScriptTags } = moduleManager.getConfig().getOptionsLiteral();
558
if (preferScriptTags) {
559
this._scriptLoader = new BrowserScriptLoader();
560
}
561
else {
562
this._scriptLoader = new NodeScriptLoader(this._env);
563
}
564
}
565
else if (this._env.isNode) {
566
this._scriptLoader = new NodeScriptLoader(this._env);
567
}
568
else {
569
this._scriptLoader = new BrowserScriptLoader();
570
}
571
}
572
let scriptCallbacks = {
573
callback: callback,
574
errorback: errorback
575
};
576
if (this._callbackMap.hasOwnProperty(scriptSrc)) {
577
this._callbackMap[scriptSrc].push(scriptCallbacks);
578
return;
579
}
580
this._callbackMap[scriptSrc] = [scriptCallbacks];
581
this._scriptLoader.load(moduleManager, scriptSrc, () => this.triggerCallback(scriptSrc), (err) => this.triggerErrorback(scriptSrc, err));
582
}
583
triggerCallback(scriptSrc) {
584
let scriptCallbacks = this._callbackMap[scriptSrc];
585
delete this._callbackMap[scriptSrc];
586
for (let i = 0; i < scriptCallbacks.length; i++) {
587
scriptCallbacks[i].callback();
588
}
589
}
590
triggerErrorback(scriptSrc, err) {
591
let scriptCallbacks = this._callbackMap[scriptSrc];
592
delete this._callbackMap[scriptSrc];
593
for (let i = 0; i < scriptCallbacks.length; i++) {
594
scriptCallbacks[i].errorback(err);
595
}
596
}
597
}
598
class BrowserScriptLoader {
599
/**
600
* Attach load / error listeners to a script element and remove them when either one has fired.
601
* Implemented for browsers supporting HTML5 standard 'load' and 'error' events.
602
*/
603
attachListeners(script, callback, errorback) {
604
let unbind = () => {
605
script.removeEventListener('load', loadEventListener);
606
script.removeEventListener('error', errorEventListener);
607
};
608
let loadEventListener = (e) => {
609
unbind();
610
callback();
611
};
612
let errorEventListener = (e) => {
613
unbind();
614
errorback(e);
615
};
616
script.addEventListener('load', loadEventListener);
617
script.addEventListener('error', errorEventListener);
618
}
619
load(moduleManager, scriptSrc, callback, errorback) {
620
if (/^node\|/.test(scriptSrc)) {
621
let opts = moduleManager.getConfig().getOptionsLiteral();
622
let nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
623
let pieces = scriptSrc.split('|');
624
let moduleExports = null;
625
try {
626
moduleExports = nodeRequire(pieces[1]);
627
}
628
catch (err) {
629
errorback(err);
630
return;
631
}
632
moduleManager.enqueueDefineAnonymousModule([], () => moduleExports);
633
callback();
634
}
635
else {
636
let script = document.createElement('script');
637
script.setAttribute('async', 'async');
638
script.setAttribute('type', 'text/javascript');
639
this.attachListeners(script, callback, errorback);
640
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
641
if (trustedTypesPolicy) {
642
scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc);
643
}
644
script.setAttribute('src', scriptSrc);
645
// Propagate CSP nonce to dynamically created script tag.
646
const { cspNonce } = moduleManager.getConfig().getOptionsLiteral();
647
if (cspNonce) {
648
script.setAttribute('nonce', cspNonce);
649
}
650
document.getElementsByTagName('head')[0].appendChild(script);
651
}
652
}
653
}
654
function canUseEval(moduleManager) {
655
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
656
try {
657
const func = (trustedTypesPolicy
658
? self.eval(trustedTypesPolicy.createScript('', 'true')) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
659
: new Function('true') // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
660
);
661
func.call(self);
662
return true;
663
}
664
catch (err) {
665
return false;
666
}
667
}
668
class WorkerScriptLoader {
669
constructor() {
670
this._cachedCanUseEval = null;
671
}
672
_canUseEval(moduleManager) {
673
if (this._cachedCanUseEval === null) {
674
this._cachedCanUseEval = canUseEval(moduleManager);
675
}
676
return this._cachedCanUseEval;
677
}
678
load(moduleManager, scriptSrc, callback, errorback) {
679
if (/^node\|/.test(scriptSrc)) {
680
const opts = moduleManager.getConfig().getOptionsLiteral();
681
const nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
682
const pieces = scriptSrc.split('|');
683
let moduleExports = null;
684
try {
685
moduleExports = nodeRequire(pieces[1]);
686
}
687
catch (err) {
688
errorback(err);
689
return;
690
}
691
moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports; });
692
callback();
693
}
694
else {
695
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
696
const isCrossOrigin = (/^((http:)|(https:)|(file:))/.test(scriptSrc) && scriptSrc.substring(0, self.origin.length) !== self.origin);
697
if (!isCrossOrigin && this._canUseEval(moduleManager)) {
698
// use `fetch` if possible because `importScripts`
699
// is synchronous and can lead to deadlocks on Safari
700
fetch(scriptSrc).then((response) => {
701
if (response.status !== 200) {
702
throw new Error(response.statusText);
703
}
704
return response.text();
705
}).then((text) => {
706
text = `${text}\n//# sourceURL=${scriptSrc}`;
707
const func = (trustedTypesPolicy
708
? self.eval(trustedTypesPolicy.createScript('', text)) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
709
: new Function(text) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
710
);
711
func.call(self);
712
callback();
713
}).then(undefined, errorback);
714
return;
715
}
716
try {
717
if (trustedTypesPolicy) {
718
scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc);
719
}
720
importScripts(scriptSrc);
721
callback();
722
}
723
catch (e) {
724
errorback(e);
725
}
726
}
727
}
728
}
729
class NodeScriptLoader {
730
constructor(env) {
731
this._env = env;
732
this._didInitialize = false;
733
this._didPatchNodeRequire = false;
734
}
735
_init(nodeRequire) {
736
if (this._didInitialize) {
737
return;
738
}
739
this._didInitialize = true;
740
// capture node modules
741
this._fs = nodeRequire('fs');
742
this._vm = nodeRequire('vm');
743
this._path = nodeRequire('path');
744
this._crypto = nodeRequire('crypto');
745
}
746
// patch require-function of nodejs such that we can manually create a script
747
// from cached data. this is done by overriding the `Module._compile` function
748
_initNodeRequire(nodeRequire, moduleManager) {
749
// It is important to check for `nodeCachedData` first and then set `_didPatchNodeRequire`.
750
// That's because `nodeCachedData` is set _after_ calling this for the first time...
751
const { nodeCachedData } = moduleManager.getConfig().getOptionsLiteral();
752
if (!nodeCachedData) {
753
return;
754
}
755
if (this._didPatchNodeRequire) {
756
return;
757
}
758
this._didPatchNodeRequire = true;
759
const that = this;
760
const Module = nodeRequire('module');
761
function makeRequireFunction(mod) {
762
const Module = mod.constructor;
763
let require = function require(path) {
764
try {
765
return mod.require(path);
766
}
767
finally {
768
// nothing
769
}
770
};
771
require.resolve = function resolve(request, options) {
772
return Module._resolveFilename(request, mod, false, options);
773
};
774
require.resolve.paths = function paths(request) {
775
return Module._resolveLookupPaths(request, mod);
776
};
777
require.main = process.mainModule;
778
require.extensions = Module._extensions;
779
require.cache = Module._cache;
780
return require;
781
}
782
Module.prototype._compile = function (content, filename) {
783
// remove shebang and create wrapper function
784
const scriptSource = Module.wrap(content.replace(/^#!.*/, ''));
785
// create script
786
const recorder = moduleManager.getRecorder();
787
const cachedDataPath = that._getCachedDataPath(nodeCachedData, filename);
788
const options = { filename };
789
let hashData;
790
try {
791
const data = that._fs.readFileSync(cachedDataPath);
792
hashData = data.slice(0, 16);
793
options.cachedData = data.slice(16);
794
recorder.record(60 /* LoaderEventType.CachedDataFound */, cachedDataPath);
795
}
796
catch (_e) {
797
recorder.record(61 /* LoaderEventType.CachedDataMissed */, cachedDataPath);
798
}
799
const script = new that._vm.Script(scriptSource, options);
800
const compileWrapper = script.runInThisContext(options);
801
// run script
802
const dirname = that._path.dirname(filename);
803
const require = makeRequireFunction(this);
804
const args = [this.exports, require, this, filename, dirname, process, _commonjsGlobal, Buffer];
805
const result = compileWrapper.apply(this.exports, args);
806
// cached data aftermath
807
that._handleCachedData(script, scriptSource, cachedDataPath, !options.cachedData, moduleManager);
808
that._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager);
809
return result;
810
};
811
}
812
load(moduleManager, scriptSrc, callback, errorback) {
813
const opts = moduleManager.getConfig().getOptionsLiteral();
814
const nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
815
const nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; });
816
this._init(nodeRequire);
817
this._initNodeRequire(nodeRequire, moduleManager);
818
let recorder = moduleManager.getRecorder();
819
if (/^node\|/.test(scriptSrc)) {
820
let pieces = scriptSrc.split('|');
821
let moduleExports = null;
822
try {
823
moduleExports = nodeRequire(pieces[1]);
824
}
825
catch (err) {
826
errorback(err);
827
return;
828
}
829
moduleManager.enqueueDefineAnonymousModule([], () => moduleExports);
830
callback();
831
}
832
else {
833
scriptSrc = AMDLoader.Utilities.fileUriToFilePath(this._env.isWindows, scriptSrc);
834
const normalizedScriptSrc = this._path.normalize(scriptSrc);
835
const vmScriptPathOrUri = this._getElectronRendererScriptPathOrUri(normalizedScriptSrc);
836
const wantsCachedData = Boolean(opts.nodeCachedData);
837
const cachedDataPath = wantsCachedData ? this._getCachedDataPath(opts.nodeCachedData, scriptSrc) : undefined;
838
this._readSourceAndCachedData(normalizedScriptSrc, cachedDataPath, recorder, (err, data, cachedData, hashData) => {
839
if (err) {
840
errorback(err);
841
return;
842
}
843
let scriptSource;
844
if (data.charCodeAt(0) === NodeScriptLoader._BOM) {
845
scriptSource = NodeScriptLoader._PREFIX + data.substring(1) + NodeScriptLoader._SUFFIX;
846
}
847
else {
848
scriptSource = NodeScriptLoader._PREFIX + data + NodeScriptLoader._SUFFIX;
849
}
850
scriptSource = nodeInstrumenter(scriptSource, normalizedScriptSrc);
851
const scriptOpts = { filename: vmScriptPathOrUri, cachedData };
852
const script = this._createAndEvalScript(moduleManager, scriptSource, scriptOpts, callback, errorback);
853
this._handleCachedData(script, scriptSource, cachedDataPath, wantsCachedData && !cachedData, moduleManager);
854
this._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager);
855
});
856
}
857
}
858
_createAndEvalScript(moduleManager, contents, options, callback, errorback) {
859
const recorder = moduleManager.getRecorder();
860
recorder.record(31 /* LoaderEventType.NodeBeginEvaluatingScript */, options.filename);
861
const script = new this._vm.Script(contents, options);
862
const ret = script.runInThisContext(options);
863
const globalDefineFunc = moduleManager.getGlobalAMDDefineFunc();
864
let receivedDefineCall = false;
865
const localDefineFunc = function () {
866
receivedDefineCall = true;
867
return globalDefineFunc.apply(null, arguments);
868
};
869
localDefineFunc.amd = globalDefineFunc.amd;
870
ret.call(AMDLoader.global, moduleManager.getGlobalAMDRequireFunc(), localDefineFunc, options.filename, this._path.dirname(options.filename));
871
recorder.record(32 /* LoaderEventType.NodeEndEvaluatingScript */, options.filename);
872
if (receivedDefineCall) {
873
callback();
874
}
875
else {
876
errorback(new Error(`Didn't receive define call in ${options.filename}!`));
877
}
878
return script;
879
}
880
_getElectronRendererScriptPathOrUri(path) {
881
if (!this._env.isElectronRenderer) {
882
return path;
883
}
884
let driveLetterMatch = path.match(/^([a-z])\:(.*)/i);
885
if (driveLetterMatch) {
886
// windows
887
return `file:///${(driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2]).replace(/\\/g, '/')}`;
888
}
889
else {
890
// nix
891
return `file://${path}`;
892
}
893
}
894
_getCachedDataPath(config, filename) {
895
const hash = this._crypto.createHash('md5').update(filename, 'utf8').update(config.seed, 'utf8').update(process.arch, '').digest('hex');
896
const basename = this._path.basename(filename).replace(/\.js$/, '');
897
return this._path.join(config.path, `${basename}-${hash}.code`);
898
}
899
_handleCachedData(script, scriptSource, cachedDataPath, createCachedData, moduleManager) {
900
if (script.cachedDataRejected) {
901
// cached data got rejected -> delete and re-create
902
this._fs.unlink(cachedDataPath, err => {
903
moduleManager.getRecorder().record(62 /* LoaderEventType.CachedDataRejected */, cachedDataPath);
904
this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
905
if (err) {
906
moduleManager.getConfig().onError(err);
907
}
908
});
909
}
910
else if (createCachedData) {
911
// no cached data, but wanted
912
this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
913
}
914
}
915
// Cached data format: | SOURCE_HASH | V8_CACHED_DATA |
916
// -SOURCE_HASH is the md5 hash of the JS source (always 16 bytes)
917
// -V8_CACHED_DATA is what v8 produces
918
_createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager) {
919
let timeout = Math.ceil(moduleManager.getConfig().getOptionsLiteral().nodeCachedData.writeDelay * (1 + Math.random()));
920
let lastSize = -1;
921
let iteration = 0;
922
let hashData = undefined;
923
const createLoop = () => {
924
setTimeout(() => {
925
if (!hashData) {
926
hashData = this._crypto.createHash('md5').update(scriptSource, 'utf8').digest();
927
}
928
const cachedData = script.createCachedData();
929
if (cachedData.length === 0 || cachedData.length === lastSize || iteration >= 5) {
930
// done
931
return;
932
}
933
if (cachedData.length < lastSize) {
934
// less data than before: skip, try again next round
935
createLoop();
936
return;
937
}
938
lastSize = cachedData.length;
939
this._fs.writeFile(cachedDataPath, Buffer.concat([hashData, cachedData]), err => {
940
if (err) {
941
moduleManager.getConfig().onError(err);
942
}
943
moduleManager.getRecorder().record(63 /* LoaderEventType.CachedDataCreated */, cachedDataPath);
944
createLoop();
945
});
946
}, timeout * (Math.pow(4, iteration++)));
947
};
948
// with some delay (`timeout`) create cached data
949
// and repeat that (with backoff delay) until the
950
// data seems to be not changing anymore
951
createLoop();
952
}
953
_readSourceAndCachedData(sourcePath, cachedDataPath, recorder, callback) {
954
if (!cachedDataPath) {
955
// no cached data case
956
this._fs.readFile(sourcePath, { encoding: 'utf8' }, callback);
957
}
958
else {
959
// cached data case: read both files in parallel
960
let source = undefined;
961
let cachedData = undefined;
962
let hashData = undefined;
963
let steps = 2;
964
const step = (err) => {
965
if (err) {
966
callback(err);
967
}
968
else if (--steps === 0) {
969
callback(undefined, source, cachedData, hashData);
970
}
971
};
972
this._fs.readFile(sourcePath, { encoding: 'utf8' }, (err, data) => {
973
source = data;
974
step(err);
975
});
976
this._fs.readFile(cachedDataPath, (err, data) => {
977
if (!err && data && data.length > 0) {
978
hashData = data.slice(0, 16);
979
cachedData = data.slice(16);
980
recorder.record(60 /* LoaderEventType.CachedDataFound */, cachedDataPath);
981
}
982
else {
983
recorder.record(61 /* LoaderEventType.CachedDataMissed */, cachedDataPath);
984
}
985
step(); // ignored: cached data is optional
986
});
987
}
988
}
989
_verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager) {
990
if (!hashData) {
991
// nothing to do
992
return;
993
}
994
if (script.cachedDataRejected) {
995
// invalid anyways
996
return;
997
}
998
setTimeout(() => {
999
// check source hash - the contract is that file paths change when file content
1000
// change (e.g use the commit or version id as cache path). this check is
1001
// for violations of this contract.
1002
const hashDataNow = this._crypto.createHash('md5').update(scriptSource, 'utf8').digest();
1003
if (!hashData.equals(hashDataNow)) {
1004
moduleManager.getConfig().onError(new Error(`FAILED TO VERIFY CACHED DATA, deleting stale '${cachedDataPath}' now, but a RESTART IS REQUIRED`));
1005
this._fs.unlink(cachedDataPath, err => {
1006
if (err) {
1007
moduleManager.getConfig().onError(err);
1008
}
1009
});
1010
}
1011
}, Math.ceil(5000 * (1 + Math.random())));
1012
}
1013
}
1014
NodeScriptLoader._BOM = 0xFEFF;
1015
NodeScriptLoader._PREFIX = '(function (require, define, __filename, __dirname) { ';
1016
NodeScriptLoader._SUFFIX = '\n});';
1017
function ensureRecordedNodeRequire(recorder, _nodeRequire) {
1018
if (_nodeRequire.__$__isRecorded) {
1019
// it is already recorded
1020
return _nodeRequire;
1021
}
1022
const nodeRequire = function nodeRequire(what) {
1023
recorder.record(33 /* LoaderEventType.NodeBeginNativeRequire */, what);
1024
try {
1025
return _nodeRequire(what);
1026
}
1027
finally {
1028
recorder.record(34 /* LoaderEventType.NodeEndNativeRequire */, what);
1029
}
1030
};
1031
nodeRequire.__$__isRecorded = true;
1032
return nodeRequire;
1033
}
1034
AMDLoader.ensureRecordedNodeRequire = ensureRecordedNodeRequire;
1035
function createScriptLoader(env) {
1036
return new OnlyOnceScriptLoader(env);
1037
}
1038
AMDLoader.createScriptLoader = createScriptLoader;
1039
})(AMDLoader || (AMDLoader = {}));
1040
/*---------------------------------------------------------------------------------------------
1041
* Copyright (c) Microsoft Corporation. All rights reserved.
1042
* Licensed under the MIT License. See License.txt in the project root for license information.
1043
*--------------------------------------------------------------------------------------------*/
1044
var AMDLoader;
1045
(function (AMDLoader) {
1046
// ------------------------------------------------------------------------
1047
// ModuleIdResolver
1048
class ModuleIdResolver {
1049
constructor(fromModuleId) {
1050
let lastSlash = fromModuleId.lastIndexOf('/');
1051
if (lastSlash !== -1) {
1052
this.fromModulePath = fromModuleId.substr(0, lastSlash + 1);
1053
}
1054
else {
1055
this.fromModulePath = '';
1056
}
1057
}
1058
/**
1059
* Normalize 'a/../name' to 'name', etc.
1060
*/
1061
static _normalizeModuleId(moduleId) {
1062
let r = moduleId, pattern;
1063
// replace /./ => /
1064
pattern = /\/\.\//;
1065
while (pattern.test(r)) {
1066
r = r.replace(pattern, '/');
1067
}
1068
// replace ^./ => nothing
1069
r = r.replace(/^\.\//g, '');
1070
// replace /aa/../ => / (BUT IGNORE /../../)
1071
pattern = /\/(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//;
1072
while (pattern.test(r)) {
1073
r = r.replace(pattern, '/');
1074
}
1075
// replace ^aa/../ => nothing (BUT IGNORE ../../)
1076
r = r.replace(/^(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//, '');
1077
return r;
1078
}
1079
/**
1080
* Resolve relative module ids
1081
*/
1082
resolveModule(moduleId) {
1083
let result = moduleId;
1084
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
1085
if (AMDLoader.Utilities.startsWith(result, './') || AMDLoader.Utilities.startsWith(result, '../')) {
1086
result = ModuleIdResolver._normalizeModuleId(this.fromModulePath + result);
1087
}
1088
}
1089
return result;
1090
}
1091
}
1092
ModuleIdResolver.ROOT = new ModuleIdResolver('');
1093
AMDLoader.ModuleIdResolver = ModuleIdResolver;
1094
// ------------------------------------------------------------------------
1095
// Module
1096
class Module {
1097
constructor(id, strId, dependencies, callback, errorback, moduleIdResolver) {
1098
this.id = id;
1099
this.strId = strId;
1100
this.dependencies = dependencies;
1101
this._callback = callback;
1102
this._errorback = errorback;
1103
this.moduleIdResolver = moduleIdResolver;
1104
this.exports = {};
1105
this.error = null;
1106
this.exportsPassedIn = false;
1107
this.unresolvedDependenciesCount = this.dependencies.length;
1108
this._isComplete = false;
1109
}
1110
static _safeInvokeFunction(callback, args) {
1111
try {
1112
return {
1113
returnedValue: callback.apply(AMDLoader.global, args),
1114
producedError: null
1115
};
1116
}
1117
catch (e) {
1118
return {
1119
returnedValue: null,
1120
producedError: e
1121
};
1122
}
1123
}
1124
static _invokeFactory(config, strModuleId, callback, dependenciesValues) {
1125
if (!config.shouldInvokeFactory(strModuleId)) {
1126
return {
1127
returnedValue: null,
1128
producedError: null
1129
};
1130
}
1131
if (config.shouldCatchError()) {
1132
return this._safeInvokeFunction(callback, dependenciesValues);
1133
}
1134
return {
1135
returnedValue: callback.apply(AMDLoader.global, dependenciesValues),
1136
producedError: null
1137
};
1138
}
1139
complete(recorder, config, dependenciesValues, inversedependenciesProvider) {
1140
this._isComplete = true;
1141
let producedError = null;
1142
if (this._callback) {
1143
if (typeof this._callback === 'function') {
1144
recorder.record(21 /* LoaderEventType.BeginInvokeFactory */, this.strId);
1145
let r = Module._invokeFactory(config, this.strId, this._callback, dependenciesValues);
1146
producedError = r.producedError;
1147
recorder.record(22 /* LoaderEventType.EndInvokeFactory */, this.strId);
1148
if (!producedError && typeof r.returnedValue !== 'undefined' && (!this.exportsPassedIn || AMDLoader.Utilities.isEmpty(this.exports))) {
1149
this.exports = r.returnedValue;
1150
}
1151
}
1152
else {
1153
this.exports = this._callback;
1154
}
1155
}
1156
if (producedError) {
1157
let err = AMDLoader.ensureError(producedError);
1158
err.phase = 'factory';
1159
err.moduleId = this.strId;
1160
err.neededBy = inversedependenciesProvider(this.id);
1161
this.error = err;
1162
config.onError(err);
1163
}
1164
this.dependencies = null;
1165
this._callback = null;
1166
this._errorback = null;
1167
this.moduleIdResolver = null;
1168
}
1169
/**
1170
* One of the direct dependencies or a transitive dependency has failed to load.
1171
*/
1172
onDependencyError(err) {
1173
this._isComplete = true;
1174
this.error = err;
1175
if (this._errorback) {
1176
this._errorback(err);
1177
return true;
1178
}
1179
return false;
1180
}
1181
/**
1182
* Is the current module complete?
1183
*/
1184
isComplete() {
1185
return this._isComplete;
1186
}
1187
}
1188
AMDLoader.Module = Module;
1189
class ModuleIdProvider {
1190
constructor() {
1191
this._nextId = 0;
1192
this._strModuleIdToIntModuleId = new Map();
1193
this._intModuleIdToStrModuleId = [];
1194
// Ensure values 0, 1, 2 are assigned accordingly with ModuleId
1195
this.getModuleId('exports');
1196
this.getModuleId('module');
1197
this.getModuleId('require');
1198
}
1199
getMaxModuleId() {
1200
return this._nextId;
1201
}
1202
getModuleId(strModuleId) {
1203
let id = this._strModuleIdToIntModuleId.get(strModuleId);
1204
if (typeof id === 'undefined') {
1205
id = this._nextId++;
1206
this._strModuleIdToIntModuleId.set(strModuleId, id);
1207
this._intModuleIdToStrModuleId[id] = strModuleId;
1208
}
1209
return id;
1210
}
1211
getStrModuleId(moduleId) {
1212
return this._intModuleIdToStrModuleId[moduleId];
1213
}
1214
}
1215
class RegularDependency {
1216
constructor(id) {
1217
this.id = id;
1218
}
1219
}
1220
RegularDependency.EXPORTS = new RegularDependency(0 /* ModuleId.EXPORTS */);
1221
RegularDependency.MODULE = new RegularDependency(1 /* ModuleId.MODULE */);
1222
RegularDependency.REQUIRE = new RegularDependency(2 /* ModuleId.REQUIRE */);
1223
AMDLoader.RegularDependency = RegularDependency;
1224
class PluginDependency {
1225
constructor(id, pluginId, pluginParam) {
1226
this.id = id;
1227
this.pluginId = pluginId;
1228
this.pluginParam = pluginParam;
1229
}
1230
}
1231
AMDLoader.PluginDependency = PluginDependency;
1232
class ModuleManager {
1233
constructor(env, scriptLoader, defineFunc, requireFunc, loaderAvailableTimestamp = 0) {
1234
this._env = env;
1235
this._scriptLoader = scriptLoader;
1236
this._loaderAvailableTimestamp = loaderAvailableTimestamp;
1237
this._defineFunc = defineFunc;
1238
this._requireFunc = requireFunc;
1239
this._moduleIdProvider = new ModuleIdProvider();
1240
this._config = new AMDLoader.Configuration(this._env);
1241
this._hasDependencyCycle = false;
1242
this._modules2 = [];
1243
this._knownModules2 = [];
1244
this._inverseDependencies2 = [];
1245
this._inversePluginDependencies2 = new Map();
1246
this._currentAnonymousDefineCall = null;
1247
this._recorder = null;
1248
this._buildInfoPath = [];
1249
this._buildInfoDefineStack = [];
1250
this._buildInfoDependencies = [];
1251
this._requireFunc.moduleManager = this;
1252
}
1253
reset() {
1254
return new ModuleManager(this._env, this._scriptLoader, this._defineFunc, this._requireFunc, this._loaderAvailableTimestamp);
1255
}
1256
getGlobalAMDDefineFunc() {
1257
return this._defineFunc;
1258
}
1259
getGlobalAMDRequireFunc() {
1260
return this._requireFunc;
1261
}
1262
static _findRelevantLocationInStack(needle, stack) {
1263
let normalize = (str) => str.replace(/\\/g, '/');
1264
let normalizedPath = normalize(needle);
1265
let stackPieces = stack.split(/\n/);
1266
for (let i = 0; i < stackPieces.length; i++) {
1267
let m = stackPieces[i].match(/(.*):(\d+):(\d+)\)?$/);
1268
if (m) {
1269
let stackPath = m[1];
1270
let stackLine = m[2];
1271
let stackColumn = m[3];
1272
let trimPathOffset = Math.max(stackPath.lastIndexOf(' ') + 1, stackPath.lastIndexOf('(') + 1);
1273
stackPath = stackPath.substr(trimPathOffset);
1274
stackPath = normalize(stackPath);
1275
if (stackPath === normalizedPath) {
1276
let r = {
1277
line: parseInt(stackLine, 10),
1278
col: parseInt(stackColumn, 10)
1279
};
1280
if (r.line === 1) {
1281
r.col -= '(function (require, define, __filename, __dirname) { '.length;
1282
}
1283
return r;
1284
}
1285
}
1286
}
1287
throw new Error('Could not correlate define call site for needle ' + needle);
1288
}
1289
getBuildInfo() {
1290
if (!this._config.isBuild()) {
1291
return null;
1292
}
1293
let result = [], resultLen = 0;
1294
for (let i = 0, len = this._modules2.length; i < len; i++) {
1295
let m = this._modules2[i];
1296
if (!m) {
1297
continue;
1298
}
1299
let location = this._buildInfoPath[m.id] || null;
1300
let defineStack = this._buildInfoDefineStack[m.id] || null;
1301
let dependencies = this._buildInfoDependencies[m.id];
1302
result[resultLen++] = {
1303
id: m.strId,
1304
path: location,
1305
defineLocation: (location && defineStack ? ModuleManager._findRelevantLocationInStack(location, defineStack) : null),
1306
dependencies: dependencies,
1307
shim: null,
1308
exports: m.exports
1309
};
1310
}
1311
return result;
1312
}
1313
getRecorder() {
1314
if (!this._recorder) {
1315
if (this._config.shouldRecordStats()) {
1316
this._recorder = new AMDLoader.LoaderEventRecorder(this._loaderAvailableTimestamp);
1317
}
1318
else {
1319
this._recorder = AMDLoader.NullLoaderEventRecorder.INSTANCE;
1320
}
1321
}
1322
return this._recorder;
1323
}
1324
getLoaderEvents() {
1325
return this.getRecorder().getEvents();
1326
}
1327
/**
1328
* Defines an anonymous module (without an id). Its name will be resolved as we receive a callback from the scriptLoader.
1329
* @param dependencies @see defineModule
1330
* @param callback @see defineModule
1331
*/
1332
enqueueDefineAnonymousModule(dependencies, callback) {
1333
if (this._currentAnonymousDefineCall !== null) {
1334
throw new Error('Can only have one anonymous define call per script file');
1335
}
1336
let stack = null;
1337
if (this._config.isBuild()) {
1338
stack = new Error('StackLocation').stack || null;
1339
}
1340
this._currentAnonymousDefineCall = {
1341
stack: stack,
1342
dependencies: dependencies,
1343
callback: callback
1344
};
1345
}
1346
/**
1347
* Creates a module and stores it in _modules. The manager will immediately begin resolving its dependencies.
1348
* @param strModuleId An unique and absolute id of the module. This must not collide with another module's id
1349
* @param dependencies An array with the dependencies of the module. Special keys are: "require", "exports" and "module"
1350
* @param callback if callback is a function, it will be called with the resolved dependencies. if callback is an object, it will be considered as the exports of the module.
1351
*/
1352
defineModule(strModuleId, dependencies, callback, errorback, stack, moduleIdResolver = new ModuleIdResolver(strModuleId)) {
1353
let moduleId = this._moduleIdProvider.getModuleId(strModuleId);
1354
if (this._modules2[moduleId]) {
1355
if (!this._config.isDuplicateMessageIgnoredFor(strModuleId)) {
1356
console.warn('Duplicate definition of module \'' + strModuleId + '\'');
1357
}
1358
// Super important! Completely ignore duplicate module definition
1359
return;
1360
}
1361
let m = new Module(moduleId, strModuleId, this._normalizeDependencies(dependencies, moduleIdResolver), callback, errorback, moduleIdResolver);
1362
this._modules2[moduleId] = m;
1363
if (this._config.isBuild()) {
1364
this._buildInfoDefineStack[moduleId] = stack;
1365
this._buildInfoDependencies[moduleId] = (m.dependencies || []).map(dep => this._moduleIdProvider.getStrModuleId(dep.id));
1366
}
1367
// Resolving of dependencies is immediate (not in a timeout). If there's a need to support a packer that concatenates in an
1368
// unordered manner, in order to finish processing the file, execute the following method in a timeout
1369
this._resolve(m);
1370
}
1371
_normalizeDependency(dependency, moduleIdResolver) {
1372
if (dependency === 'exports') {
1373
return RegularDependency.EXPORTS;
1374
}
1375
if (dependency === 'module') {
1376
return RegularDependency.MODULE;
1377
}
1378
if (dependency === 'require') {
1379
return RegularDependency.REQUIRE;
1380
}
1381
// Normalize dependency and then request it from the manager
1382
let bangIndex = dependency.indexOf('!');
1383
if (bangIndex >= 0) {
1384
let strPluginId = moduleIdResolver.resolveModule(dependency.substr(0, bangIndex));
1385
let pluginParam = moduleIdResolver.resolveModule(dependency.substr(bangIndex + 1));
1386
let dependencyId = this._moduleIdProvider.getModuleId(strPluginId + '!' + pluginParam);
1387
let pluginId = this._moduleIdProvider.getModuleId(strPluginId);
1388
return new PluginDependency(dependencyId, pluginId, pluginParam);
1389
}
1390
return new RegularDependency(this._moduleIdProvider.getModuleId(moduleIdResolver.resolveModule(dependency)));
1391
}
1392
_normalizeDependencies(dependencies, moduleIdResolver) {
1393
let result = [], resultLen = 0;
1394
for (let i = 0, len = dependencies.length; i < len; i++) {
1395
result[resultLen++] = this._normalizeDependency(dependencies[i], moduleIdResolver);
1396
}
1397
return result;
1398
}
1399
_relativeRequire(moduleIdResolver, dependencies, callback, errorback) {
1400
if (typeof dependencies === 'string') {
1401
return this.synchronousRequire(dependencies, moduleIdResolver);
1402
}
1403
this.defineModule(AMDLoader.Utilities.generateAnonymousModule(), dependencies, callback, errorback, null, moduleIdResolver);
1404
}
1405
/**
1406
* Require synchronously a module by its absolute id. If the module is not loaded, an exception will be thrown.
1407
* @param id The unique and absolute id of the required module
1408
* @return The exports of module 'id'
1409
*/
1410
synchronousRequire(_strModuleId, moduleIdResolver = new ModuleIdResolver(_strModuleId)) {
1411
let dependency = this._normalizeDependency(_strModuleId, moduleIdResolver);
1412
let m = this._modules2[dependency.id];
1413
if (!m) {
1414
throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + _strModuleId + '\'. This is the first mention of this module!');
1415
}
1416
if (!m.isComplete()) {
1417
throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + _strModuleId + '\'. This module has not been resolved completely yet.');
1418
}
1419
if (m.error) {
1420
throw m.error;
1421
}
1422
return m.exports;
1423
}
1424
configure(params, shouldOverwrite) {
1425
let oldShouldRecordStats = this._config.shouldRecordStats();
1426
if (shouldOverwrite) {
1427
this._config = new AMDLoader.Configuration(this._env, params);
1428
}
1429
else {
1430
this._config = this._config.cloneAndMerge(params);
1431
}
1432
if (this._config.shouldRecordStats() && !oldShouldRecordStats) {
1433
this._recorder = null;
1434
}
1435
}
1436
getConfig() {
1437
return this._config;
1438
}
1439
/**
1440
* Callback from the scriptLoader when a module has been loaded.
1441
* This means its code is available and has been executed.
1442
*/
1443
_onLoad(moduleId) {
1444
if (this._currentAnonymousDefineCall !== null) {
1445
let defineCall = this._currentAnonymousDefineCall;
1446
this._currentAnonymousDefineCall = null;
1447
// Hit an anonymous define call
1448
this.defineModule(this._moduleIdProvider.getStrModuleId(moduleId), defineCall.dependencies, defineCall.callback, null, defineCall.stack);
1449
}
1450
}
1451
_createLoadError(moduleId, _err) {
1452
let strModuleId = this._moduleIdProvider.getStrModuleId(moduleId);
1453
let neededBy = (this._inverseDependencies2[moduleId] || []).map((intModuleId) => this._moduleIdProvider.getStrModuleId(intModuleId));
1454
const err = AMDLoader.ensureError(_err);
1455
err.phase = 'loading';
1456
err.moduleId = strModuleId;
1457
err.neededBy = neededBy;
1458
return err;
1459
}
1460
/**
1461
* Callback from the scriptLoader when a module hasn't been loaded.
1462
* This means that the script was not found (e.g. 404) or there was an error in the script.
1463
*/
1464
_onLoadError(moduleId, err) {
1465
const error = this._createLoadError(moduleId, err);
1466
if (!this._modules2[moduleId]) {
1467
this._modules2[moduleId] = new Module(moduleId, this._moduleIdProvider.getStrModuleId(moduleId), [], () => { }, null, null);
1468
}
1469
// Find any 'local' error handlers, walk the entire chain of inverse dependencies if necessary.
1470
let seenModuleId = [];
1471
for (let i = 0, len = this._moduleIdProvider.getMaxModuleId(); i < len; i++) {
1472
seenModuleId[i] = false;
1473
}
1474
let someoneNotified = false;
1475
let queue = [];
1476
queue.push(moduleId);
1477
seenModuleId[moduleId] = true;
1478
while (queue.length > 0) {
1479
let queueElement = queue.shift();
1480
let m = this._modules2[queueElement];
1481
if (m) {
1482
someoneNotified = m.onDependencyError(error) || someoneNotified;
1483
}
1484
let inverseDeps = this._inverseDependencies2[queueElement];
1485
if (inverseDeps) {
1486
for (let i = 0, len = inverseDeps.length; i < len; i++) {
1487
let inverseDep = inverseDeps[i];
1488
if (!seenModuleId[inverseDep]) {
1489
queue.push(inverseDep);
1490
seenModuleId[inverseDep] = true;
1491
}
1492
}
1493
}
1494
}
1495
if (!someoneNotified) {
1496
this._config.onError(error);
1497
}
1498
}
1499
/**
1500
* Walks (recursively) the dependencies of 'from' in search of 'to'.
1501
* Returns true if there is such a path or false otherwise.
1502
* @param from Module id to start at
1503
* @param to Module id to look for
1504
*/
1505
_hasDependencyPath(fromId, toId) {
1506
let from = this._modules2[fromId];
1507
if (!from) {
1508
return false;
1509
}
1510
let inQueue = [];
1511
for (let i = 0, len = this._moduleIdProvider.getMaxModuleId(); i < len; i++) {
1512
inQueue[i] = false;
1513
}
1514
let queue = [];
1515
// Insert 'from' in queue
1516
queue.push(from);
1517
inQueue[fromId] = true;
1518
while (queue.length > 0) {
1519
// Pop first inserted element of queue
1520
let element = queue.shift();
1521
let dependencies = element.dependencies;
1522
if (dependencies) {
1523
// Walk the element's dependencies
1524
for (let i = 0, len = dependencies.length; i < len; i++) {
1525
let dependency = dependencies[i];
1526
if (dependency.id === toId) {
1527
// There is a path to 'to'
1528
return true;
1529
}
1530
let dependencyModule = this._modules2[dependency.id];
1531
if (dependencyModule && !inQueue[dependency.id]) {
1532
// Insert 'dependency' in queue
1533
inQueue[dependency.id] = true;
1534
queue.push(dependencyModule);
1535
}
1536
}
1537
}
1538
}
1539
// There is no path to 'to'
1540
return false;
1541
}
1542
/**
1543
* Walks (recursively) the dependencies of 'from' in search of 'to'.
1544
* Returns cycle as array.
1545
* @param from Module id to start at
1546
* @param to Module id to look for
1547
*/
1548
_findCyclePath(fromId, toId, depth) {
1549
if (fromId === toId || depth === 50) {
1550
return [fromId];
1551
}
1552
let from = this._modules2[fromId];
1553
if (!from) {
1554
return null;
1555
}
1556
// Walk the element's dependencies
1557
let dependencies = from.dependencies;
1558
if (dependencies) {
1559
for (let i = 0, len = dependencies.length; i < len; i++) {
1560
let path = this._findCyclePath(dependencies[i].id, toId, depth + 1);
1561
if (path !== null) {
1562
path.push(fromId);
1563
return path;
1564
}
1565
}
1566
}
1567
return null;
1568
}
1569
/**
1570
* Create the local 'require' that is passed into modules
1571
*/
1572
_createRequire(moduleIdResolver) {
1573
let result = ((dependencies, callback, errorback) => {
1574
return this._relativeRequire(moduleIdResolver, dependencies, callback, errorback);
1575
});
1576
result.toUrl = (id) => {
1577
return this._config.requireToUrl(moduleIdResolver.resolveModule(id));
1578
};
1579
result.getStats = () => {
1580
return this.getLoaderEvents();
1581
};
1582
result.hasDependencyCycle = () => {
1583
return this._hasDependencyCycle;
1584
};
1585
result.config = (params, shouldOverwrite = false) => {
1586
this.configure(params, shouldOverwrite);
1587
};
1588
result.__$__nodeRequire = AMDLoader.global.nodeRequire;
1589
return result;
1590
}
1591
_loadModule(moduleId) {
1592
if (this._modules2[moduleId] || this._knownModules2[moduleId]) {
1593
// known module
1594
return;
1595
}
1596
this._knownModules2[moduleId] = true;
1597
let strModuleId = this._moduleIdProvider.getStrModuleId(moduleId);
1598
let paths = this._config.moduleIdToPaths(strModuleId);
1599
let scopedPackageRegex = /^@[^\/]+\/[^\/]+$/; // matches @scope/package-name
1600
if (this._env.isNode && (strModuleId.indexOf('/') === -1 || scopedPackageRegex.test(strModuleId))) {
1601
paths.push('node|' + strModuleId);
1602
}
1603
let lastPathIndex = -1;
1604
let loadNextPath = (err) => {
1605
lastPathIndex++;
1606
if (lastPathIndex >= paths.length) {
1607
// No more paths to try
1608
this._onLoadError(moduleId, err);
1609
}
1610
else {
1611
let currentPath = paths[lastPathIndex];
1612
let recorder = this.getRecorder();
1613
if (this._config.isBuild() && currentPath === 'empty:') {
1614
this._buildInfoPath[moduleId] = currentPath;
1615
this.defineModule(this._moduleIdProvider.getStrModuleId(moduleId), [], null, null, null);
1616
this._onLoad(moduleId);
1617
return;
1618
}
1619
recorder.record(10 /* LoaderEventType.BeginLoadingScript */, currentPath);
1620
this._scriptLoader.load(this, currentPath, () => {
1621
if (this._config.isBuild()) {
1622
this._buildInfoPath[moduleId] = currentPath;
1623
}
1624
recorder.record(11 /* LoaderEventType.EndLoadingScriptOK */, currentPath);
1625
this._onLoad(moduleId);
1626
}, (err) => {
1627
recorder.record(12 /* LoaderEventType.EndLoadingScriptError */, currentPath);
1628
loadNextPath(err);
1629
});
1630
}
1631
};
1632
loadNextPath(null);
1633
}
1634
/**
1635
* Resolve a plugin dependency with the plugin loaded & complete
1636
* @param module The module that has this dependency
1637
* @param pluginDependency The semi-normalized dependency that appears in the module. e.g. 'vs/css!./mycssfile'. Only the plugin part (before !) is normalized
1638
* @param plugin The plugin (what the plugin exports)
1639
*/
1640
_loadPluginDependency(plugin, pluginDependency) {
1641
if (this._modules2[pluginDependency.id] || this._knownModules2[pluginDependency.id]) {
1642
// known module
1643
return;
1644
}
1645
this._knownModules2[pluginDependency.id] = true;
1646
// Delegate the loading of the resource to the plugin
1647
let load = ((value) => {
1648
this.defineModule(this._moduleIdProvider.getStrModuleId(pluginDependency.id), [], value, null, null);
1649
});
1650
load.error = (err) => {
1651
this._config.onError(this._createLoadError(pluginDependency.id, err));
1652
};
1653
plugin.load(pluginDependency.pluginParam, this._createRequire(ModuleIdResolver.ROOT), load, this._config.getOptionsLiteral());
1654
}
1655
/**
1656
* Examine the dependencies of module 'module' and resolve them as needed.
1657
*/
1658
_resolve(module) {
1659
let dependencies = module.dependencies;
1660
if (dependencies) {
1661
for (let i = 0, len = dependencies.length; i < len; i++) {
1662
let dependency = dependencies[i];
1663
if (dependency === RegularDependency.EXPORTS) {
1664
module.exportsPassedIn = true;
1665
module.unresolvedDependenciesCount--;
1666
continue;
1667
}
1668
if (dependency === RegularDependency.MODULE) {
1669
module.unresolvedDependenciesCount--;
1670
continue;
1671
}
1672
if (dependency === RegularDependency.REQUIRE) {
1673
module.unresolvedDependenciesCount--;
1674
continue;
1675
}
1676
let dependencyModule = this._modules2[dependency.id];
1677
if (dependencyModule && dependencyModule.isComplete()) {
1678
if (dependencyModule.error) {
1679
module.onDependencyError(dependencyModule.error);
1680
return;
1681
}
1682
module.unresolvedDependenciesCount--;
1683
continue;
1684
}
1685
if (this._hasDependencyPath(dependency.id, module.id)) {
1686
this._hasDependencyCycle = true;
1687
console.warn('There is a dependency cycle between \'' + this._moduleIdProvider.getStrModuleId(dependency.id) + '\' and \'' + this._moduleIdProvider.getStrModuleId(module.id) + '\'. The cyclic path follows:');
1688
let cyclePath = this._findCyclePath(dependency.id, module.id, 0) || [];
1689
cyclePath.reverse();
1690
cyclePath.push(dependency.id);
1691
console.warn(cyclePath.map(id => this._moduleIdProvider.getStrModuleId(id)).join(' => \n'));
1692
// Break the cycle
1693
module.unresolvedDependenciesCount--;
1694
continue;
1695
}
1696
// record inverse dependency
1697
this._inverseDependencies2[dependency.id] = this._inverseDependencies2[dependency.id] || [];
1698
this._inverseDependencies2[dependency.id].push(module.id);
1699
if (dependency instanceof PluginDependency) {
1700
let plugin = this._modules2[dependency.pluginId];
1701
if (plugin && plugin.isComplete()) {
1702
this._loadPluginDependency(plugin.exports, dependency);
1703
continue;
1704
}
1705
// Record dependency for when the plugin gets loaded
1706
let inversePluginDeps = this._inversePluginDependencies2.get(dependency.pluginId);
1707
if (!inversePluginDeps) {
1708
inversePluginDeps = [];
1709
this._inversePluginDependencies2.set(dependency.pluginId, inversePluginDeps);
1710
}
1711
inversePluginDeps.push(dependency);
1712
this._loadModule(dependency.pluginId);
1713
continue;
1714
}
1715
this._loadModule(dependency.id);
1716
}
1717
}
1718
if (module.unresolvedDependenciesCount === 0) {
1719
this._onModuleComplete(module);
1720
}
1721
}
1722
_onModuleComplete(module) {
1723
let recorder = this.getRecorder();
1724
if (module.isComplete()) {
1725
// already done
1726
return;
1727
}
1728
let dependencies = module.dependencies;
1729
let dependenciesValues = [];
1730
if (dependencies) {
1731
for (let i = 0, len = dependencies.length; i < len; i++) {
1732
let dependency = dependencies[i];
1733
if (dependency === RegularDependency.EXPORTS) {
1734
dependenciesValues[i] = module.exports;
1735
continue;
1736
}
1737
if (dependency === RegularDependency.MODULE) {
1738
dependenciesValues[i] = {
1739
id: module.strId,
1740
config: () => {
1741
return this._config.getConfigForModule(module.strId);
1742
}
1743
};
1744
continue;
1745
}
1746
if (dependency === RegularDependency.REQUIRE) {
1747
dependenciesValues[i] = this._createRequire(module.moduleIdResolver);
1748
continue;
1749
}
1750
let dependencyModule = this._modules2[dependency.id];
1751
if (dependencyModule) {
1752
dependenciesValues[i] = dependencyModule.exports;
1753
continue;
1754
}
1755
dependenciesValues[i] = null;
1756
}
1757
}
1758
const inversedependenciesProvider = (moduleId) => {
1759
return (this._inverseDependencies2[moduleId] || []).map((intModuleId) => this._moduleIdProvider.getStrModuleId(intModuleId));
1760
};
1761
module.complete(recorder, this._config, dependenciesValues, inversedependenciesProvider);
1762
// Fetch and clear inverse dependencies
1763
let inverseDeps = this._inverseDependencies2[module.id];
1764
this._inverseDependencies2[module.id] = null;
1765
if (inverseDeps) {
1766
// Resolve one inverse dependency at a time, always
1767
// on the lookout for a completed module.
1768
for (let i = 0, len = inverseDeps.length; i < len; i++) {
1769
let inverseDependencyId = inverseDeps[i];
1770
let inverseDependency = this._modules2[inverseDependencyId];
1771
inverseDependency.unresolvedDependenciesCount--;
1772
if (inverseDependency.unresolvedDependenciesCount === 0) {
1773
this._onModuleComplete(inverseDependency);
1774
}
1775
}
1776
}
1777
let inversePluginDeps = this._inversePluginDependencies2.get(module.id);
1778
if (inversePluginDeps) {
1779
// This module is used as a plugin at least once
1780
// Fetch and clear these inverse plugin dependencies
1781
this._inversePluginDependencies2.delete(module.id);
1782
// Resolve plugin dependencies one at a time
1783
for (let i = 0, len = inversePluginDeps.length; i < len; i++) {
1784
this._loadPluginDependency(module.exports, inversePluginDeps[i]);
1785
}
1786
}
1787
}
1788
}
1789
AMDLoader.ModuleManager = ModuleManager;
1790
})(AMDLoader || (AMDLoader = {}));
1791
var define;
1792
var AMDLoader;
1793
(function (AMDLoader) {
1794
const env = new AMDLoader.Environment();
1795
let moduleManager = null;
1796
const DefineFunc = function (id, dependencies, callback) {
1797
if (typeof id !== 'string') {
1798
callback = dependencies;
1799
dependencies = id;
1800
id = null;
1801
}
1802
if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) {
1803
callback = dependencies;
1804
dependencies = null;
1805
}
1806
if (!dependencies) {
1807
dependencies = ['require', 'exports', 'module'];
1808
}
1809
if (id) {
1810
moduleManager.defineModule(id, dependencies, callback, null, null);
1811
}
1812
else {
1813
moduleManager.enqueueDefineAnonymousModule(dependencies, callback);
1814
}
1815
};
1816
DefineFunc.amd = {
1817
jQuery: true
1818
};
1819
const _requireFunc_config = function (params, shouldOverwrite = false) {
1820
moduleManager.configure(params, shouldOverwrite);
1821
};
1822
const RequireFunc = function () {
1823
if (arguments.length === 1) {
1824
if ((arguments[0] instanceof Object) && !Array.isArray(arguments[0])) {
1825
_requireFunc_config(arguments[0]);
1826
return;
1827
}
1828
if (typeof arguments[0] === 'string') {
1829
return moduleManager.synchronousRequire(arguments[0]);
1830
}
1831
}
1832
if (arguments.length === 2 || arguments.length === 3) {
1833
if (Array.isArray(arguments[0])) {
1834
moduleManager.defineModule(AMDLoader.Utilities.generateAnonymousModule(), arguments[0], arguments[1], arguments[2], null);
1835
return;
1836
}
1837
}
1838
throw new Error('Unrecognized require call');
1839
};
1840
RequireFunc.config = _requireFunc_config;
1841
RequireFunc.getConfig = function () {
1842
return moduleManager.getConfig().getOptionsLiteral();
1843
};
1844
RequireFunc.reset = function () {
1845
moduleManager = moduleManager.reset();
1846
};
1847
RequireFunc.getBuildInfo = function () {
1848
return moduleManager.getBuildInfo();
1849
};
1850
RequireFunc.getStats = function () {
1851
return moduleManager.getLoaderEvents();
1852
};
1853
RequireFunc.define = DefineFunc;
1854
function init() {
1855
if (typeof AMDLoader.global.require !== 'undefined' || typeof require !== 'undefined') {
1856
const _nodeRequire = (AMDLoader.global.require || require);
1857
if (typeof _nodeRequire === 'function' && typeof _nodeRequire.resolve === 'function') {
1858
// re-expose node's require function
1859
const nodeRequire = AMDLoader.ensureRecordedNodeRequire(moduleManager.getRecorder(), _nodeRequire);
1860
AMDLoader.global.nodeRequire = nodeRequire;
1861
RequireFunc.nodeRequire = nodeRequire;
1862
RequireFunc.__$__nodeRequire = nodeRequire;
1863
}
1864
}
1865
if (env.isNode && !env.isElectronRenderer && !env.isElectronNodeIntegrationWebWorker) {
1866
module.exports = RequireFunc;
1867
}
1868
else {
1869
if (!env.isElectronRenderer) {
1870
AMDLoader.global.define = DefineFunc;
1871
}
1872
AMDLoader.global.require = RequireFunc;
1873
}
1874
}
1875
AMDLoader.init = init;
1876
if (typeof AMDLoader.global.define !== 'function' || !AMDLoader.global.define.amd) {
1877
moduleManager = new AMDLoader.ModuleManager(env, AMDLoader.createScriptLoader(env), DefineFunc, RequireFunc, AMDLoader.Utilities.getHighPerformanceTimestamp());
1878
// The global variable require can configure the loader
1879
if (typeof AMDLoader.global.require !== 'undefined' && typeof AMDLoader.global.require !== 'function') {
1880
RequireFunc.config(AMDLoader.global.require);
1881
}
1882
// This define is for the local closure defined in node in the case that the loader is concatenated
1883
define = function () {
1884
return DefineFunc.apply(null, arguments);
1885
};
1886
define.amd = DefineFunc.amd;
1887
if (typeof doNotInitLoader === 'undefined') {
1888
init();
1889
}
1890
}
1891
})(AMDLoader || (AMDLoader = {}));
1892
1893