loader.js 84 KB

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