loader.js 85 KB

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