loader.js 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  1. /*!-----------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Version: 0.5.2(d49899a916fd99840f6f9178f2dd06e0e7013646)
  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. /*---------------------------------------------------------------------------------------------
  12. *---------------------------------------------------------------------------------------------
  13. *---------------------------------------------------------------------------------------------
  14. *---------------------------------------------------------------------------------------------
  15. *---------------------------------------------------------------------------------------------
  16. * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/
  17. *---------------------------------------------------------------------------------------------
  18. *---------------------------------------------------------------------------------------------
  19. *---------------------------------------------------------------------------------------------
  20. *---------------------------------------------------------------------------------------------
  21. *--------------------------------------------------------------------------------------------*/
  22. 'use strict';
  23. // Limitation: To load jquery through the loader, always require 'jquery' and add a path for it in the loader configuration
  24. var _amdLoaderGlobal = this, define;
  25. var AMDLoader;
  26. (function (AMDLoader) {
  27. // ------------------------------------------------------------------------
  28. // Utilities
  29. function _isWindows() {
  30. if (typeof navigator !== 'undefined') {
  31. if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) {
  32. return true;
  33. }
  34. }
  35. if (typeof process !== 'undefined') {
  36. return (process.platform === 'win32');
  37. }
  38. return false;
  39. }
  40. var isWindows = _isWindows();
  41. var Utilities = (function () {
  42. function Utilities() {
  43. }
  44. /**
  45. * This method does not take care of / vs \
  46. */
  47. Utilities.fileUriToFilePath = function (uri) {
  48. uri = decodeURI(uri);
  49. if (isWindows) {
  50. if (/^file:\/\/\//.test(uri)) {
  51. // This is a URI without a hostname => return only the path segment
  52. return uri.substr(8);
  53. }
  54. if (/^file:\/\//.test(uri)) {
  55. return uri.substr(5);
  56. }
  57. }
  58. else {
  59. if (/^file:\/\//.test(uri)) {
  60. return uri.substr(7);
  61. }
  62. }
  63. // Not sure...
  64. return uri;
  65. };
  66. Utilities.startsWith = function (haystack, needle) {
  67. return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
  68. };
  69. Utilities.endsWith = function (haystack, needle) {
  70. return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle;
  71. };
  72. // only check for "?" before "#" to ensure that there is a real Query-String
  73. Utilities.containsQueryString = function (url) {
  74. return /^[^\#]*\?/gi.test(url);
  75. };
  76. /**
  77. * Does `url` start with http:// or https:// or / ?
  78. */
  79. Utilities.isAbsolutePath = function (url) {
  80. return (Utilities.startsWith(url, 'http://')
  81. || Utilities.startsWith(url, 'https://')
  82. || Utilities.startsWith(url, 'file://')
  83. || Utilities.startsWith(url, '/'));
  84. };
  85. Utilities.forEachProperty = function (obj, callback) {
  86. if (obj) {
  87. var key;
  88. for (key in obj) {
  89. if (obj.hasOwnProperty(key)) {
  90. callback(key, obj[key]);
  91. }
  92. }
  93. }
  94. };
  95. Utilities.isEmpty = function (obj) {
  96. var isEmpty = true;
  97. Utilities.forEachProperty(obj, function () {
  98. isEmpty = false;
  99. });
  100. return isEmpty;
  101. };
  102. Utilities.isArray = function (obj) {
  103. if (Array.isArray) {
  104. return Array.isArray(obj);
  105. }
  106. return Object.prototype.toString.call(obj) === '[object Array]';
  107. };
  108. Utilities.recursiveClone = function (obj) {
  109. if (!obj || typeof obj !== 'object') {
  110. return obj;
  111. }
  112. var result = Utilities.isArray(obj) ? [] : {};
  113. Utilities.forEachProperty(obj, function (key, value) {
  114. if (value && typeof value === 'object') {
  115. result[key] = Utilities.recursiveClone(value);
  116. }
  117. else {
  118. result[key] = value;
  119. }
  120. });
  121. return result;
  122. };
  123. Utilities.generateAnonymousModule = function () {
  124. return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '===';
  125. };
  126. Utilities.isAnonymousModule = function (id) {
  127. return id.indexOf('===anonymous') === 0;
  128. };
  129. Utilities.NEXT_ANONYMOUS_ID = 1;
  130. return Utilities;
  131. }());
  132. AMDLoader.Utilities = Utilities;
  133. var ConfigurationOptionsUtil = (function () {
  134. function ConfigurationOptionsUtil() {
  135. }
  136. /**
  137. * Ensure configuration options make sense
  138. */
  139. ConfigurationOptionsUtil.validateConfigurationOptions = function (options) {
  140. function defaultOnError(err) {
  141. if (err.errorCode === 'load') {
  142. console.error('Loading "' + err.moduleId + '" failed');
  143. console.error('Detail: ', err.detail);
  144. if (err.detail && err.detail.stack) {
  145. console.error(err.detail.stack);
  146. }
  147. console.error('Here are the modules that depend on it:');
  148. console.error(err.neededBy);
  149. return;
  150. }
  151. if (err.errorCode === 'factory') {
  152. console.error('The factory method of "' + err.moduleId + '" has thrown an exception');
  153. console.error(err.detail);
  154. if (err.detail && err.detail.stack) {
  155. console.error(err.detail.stack);
  156. }
  157. return;
  158. }
  159. }
  160. options = options || {};
  161. if (typeof options.baseUrl !== 'string') {
  162. options.baseUrl = '';
  163. }
  164. if (typeof options.isBuild !== 'boolean') {
  165. options.isBuild = false;
  166. }
  167. if (typeof options.paths !== 'object') {
  168. options.paths = {};
  169. }
  170. if (typeof options.bundles !== 'object') {
  171. options.bundles = [];
  172. }
  173. if (typeof options.shim !== 'object') {
  174. options.shim = {};
  175. }
  176. if (typeof options.config !== 'object') {
  177. options.config = {};
  178. }
  179. if (typeof options.catchError === 'undefined') {
  180. // Catch errors by default in web workers, do not catch errors by default in other contexts
  181. options.catchError = isWebWorker;
  182. }
  183. if (typeof options.urlArgs !== 'string') {
  184. options.urlArgs = '';
  185. }
  186. if (typeof options.onError !== 'function') {
  187. options.onError = defaultOnError;
  188. }
  189. if (typeof options.ignoreDuplicateModules !== 'object' || !Utilities.isArray(options.ignoreDuplicateModules)) {
  190. options.ignoreDuplicateModules = [];
  191. }
  192. if (options.baseUrl.length > 0) {
  193. if (!Utilities.endsWith(options.baseUrl, '/')) {
  194. options.baseUrl += '/';
  195. }
  196. }
  197. if (!Array.isArray(options.nodeModules)) {
  198. options.nodeModules = [];
  199. }
  200. return options;
  201. };
  202. ConfigurationOptionsUtil.mergeConfigurationOptions = function (overwrite, base) {
  203. if (overwrite === void 0) { overwrite = null; }
  204. if (base === void 0) { base = null; }
  205. var result = Utilities.recursiveClone(base || {});
  206. // Merge known properties and overwrite the unknown ones
  207. Utilities.forEachProperty(overwrite, function (key, value) {
  208. if (key === 'bundles' && typeof result.bundles !== 'undefined') {
  209. if (Utilities.isArray(value)) {
  210. // Compatibility style
  211. result.bundles = result.bundles.concat(value);
  212. }
  213. else {
  214. // AMD API style
  215. Utilities.forEachProperty(value, function (key, value) {
  216. var bundleConfiguration = {
  217. location: key,
  218. modules: value
  219. };
  220. result.bundles.push(bundleConfiguration);
  221. });
  222. }
  223. }
  224. else if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') {
  225. result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value);
  226. }
  227. else if (key === 'paths' && typeof result.paths !== 'undefined') {
  228. Utilities.forEachProperty(value, function (key2, value2) { return result.paths[key2] = value2; });
  229. }
  230. else if (key === 'shim' && typeof result.shim !== 'undefined') {
  231. Utilities.forEachProperty(value, function (key2, value2) { return result.shim[key2] = value2; });
  232. }
  233. else if (key === 'config' && typeof result.config !== 'undefined') {
  234. Utilities.forEachProperty(value, function (key2, value2) { return result.config[key2] = value2; });
  235. }
  236. else {
  237. result[key] = Utilities.recursiveClone(value);
  238. }
  239. });
  240. return ConfigurationOptionsUtil.validateConfigurationOptions(result);
  241. };
  242. return ConfigurationOptionsUtil;
  243. }());
  244. AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil;
  245. var Configuration = (function () {
  246. function Configuration(options) {
  247. this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options);
  248. this._createIgnoreDuplicateModulesMap();
  249. this._createSortedPathsRules();
  250. this._createShimModules();
  251. this._createOverwriteModuleIdToPath();
  252. if (this.options.baseUrl === '') {
  253. if (isNode && this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename) {
  254. var nodeMain = this.options.nodeRequire.main.filename;
  255. var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
  256. this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
  257. }
  258. if (isNode && this.options.nodeMain) {
  259. var nodeMain = this.options.nodeMain;
  260. var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
  261. this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
  262. }
  263. }
  264. }
  265. Configuration.prototype._createOverwriteModuleIdToPath = function () {
  266. this.overwriteModuleIdToPath = {};
  267. for (var i = 0; i < this.options.bundles.length; i++) {
  268. var bundle = this.options.bundles[i];
  269. var location = bundle.location;
  270. if (bundle.modules) {
  271. for (var j = 0; j < bundle.modules.length; j++) {
  272. this.overwriteModuleIdToPath[bundle.modules[j]] = location;
  273. }
  274. }
  275. }
  276. };
  277. Configuration.prototype._createIgnoreDuplicateModulesMap = function () {
  278. // Build a map out of the ignoreDuplicateModules array
  279. this.ignoreDuplicateModulesMap = {};
  280. for (var i = 0; i < this.options.ignoreDuplicateModules.length; i++) {
  281. this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true;
  282. }
  283. };
  284. Configuration.prototype._createSortedPathsRules = function () {
  285. var _this = this;
  286. // Create an array our of the paths rules, sorted descending by length to
  287. // result in a more specific -> less specific order
  288. this.sortedPathsRules = [];
  289. Utilities.forEachProperty(this.options.paths, function (from, to) {
  290. if (!Utilities.isArray(to)) {
  291. _this.sortedPathsRules.push({
  292. from: from,
  293. to: [to]
  294. });
  295. }
  296. else {
  297. _this.sortedPathsRules.push({
  298. from: from,
  299. to: to
  300. });
  301. }
  302. });
  303. this.sortedPathsRules.sort(function (a, b) {
  304. return b.from.length - a.from.length;
  305. });
  306. };
  307. Configuration.prototype._ensureShimModule1 = function (path, shimMD) {
  308. // Ensure dependencies are also shimmed
  309. for (var i = 0; i < shimMD.length; i++) {
  310. var dependencyId = shimMD[i];
  311. if (!this.shimModules.hasOwnProperty(dependencyId)) {
  312. this._ensureShimModule1(dependencyId, []);
  313. }
  314. }
  315. this.shimModules[path] = {
  316. stack: null,
  317. dependencies: shimMD,
  318. callback: null
  319. };
  320. if (this.options.isBuild) {
  321. this.shimModulesStr[path] = 'null';
  322. }
  323. };
  324. Configuration.prototype._ensureShimModule2 = function (path, shimMD) {
  325. this.shimModules[path] = {
  326. stack: null,
  327. dependencies: shimMD.deps || [],
  328. callback: function () {
  329. var depsValues = [];
  330. for (var _i = 0; _i < arguments.length; _i++) {
  331. depsValues[_i - 0] = arguments[_i];
  332. }
  333. if (typeof shimMD.init === 'function') {
  334. var initReturnValue = shimMD.init.apply(global, depsValues);
  335. if (typeof initReturnValue !== 'undefined') {
  336. return initReturnValue;
  337. }
  338. }
  339. if (typeof shimMD.exports === 'function') {
  340. return shimMD.exports.apply(global, depsValues);
  341. }
  342. if (typeof shimMD.exports === 'string') {
  343. var pieces = shimMD.exports.split('.');
  344. var obj = global;
  345. for (var i = 0; i < pieces.length; i++) {
  346. if (obj) {
  347. obj = obj[pieces[i]];
  348. }
  349. }
  350. return obj;
  351. }
  352. return shimMD.exports || {};
  353. }
  354. };
  355. if (this.options.isBuild) {
  356. if (typeof shimMD.init === 'function') {
  357. this.shimModulesStr[path] = shimMD.init.toString();
  358. }
  359. else if (typeof shimMD.exports === 'function') {
  360. this.shimModulesStr[path] = shimMD.exports.toString();
  361. }
  362. else if (typeof shimMD.exports === 'string') {
  363. this.shimModulesStr[path] = 'function() { return this.' + shimMD.exports + '; }';
  364. }
  365. else {
  366. this.shimModulesStr[path] = JSON.stringify(shimMD.exports);
  367. }
  368. }
  369. };
  370. Configuration.prototype._createShimModules = function () {
  371. var _this = this;
  372. this.shimModules = {};
  373. this.shimModulesStr = {};
  374. Utilities.forEachProperty(this.options.shim, function (path, shimMD) {
  375. if (!shimMD) {
  376. return;
  377. }
  378. if (Utilities.isArray(shimMD)) {
  379. _this._ensureShimModule1(path, shimMD);
  380. return;
  381. }
  382. _this._ensureShimModule2(path, shimMD);
  383. });
  384. };
  385. /**
  386. * Clone current configuration and overwrite options selectively.
  387. * @param options The selective options to overwrite with.
  388. * @result A new configuration
  389. */
  390. Configuration.prototype.cloneAndMerge = function (options) {
  391. return new Configuration(ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options));
  392. };
  393. /**
  394. * Get current options bag. Useful for passing it forward to plugins.
  395. */
  396. Configuration.prototype.getOptionsLiteral = function () {
  397. return this.options;
  398. };
  399. Configuration.prototype._applyPaths = function (moduleId) {
  400. var pathRule;
  401. for (var i = 0, len = this.sortedPathsRules.length; i < len; i++) {
  402. pathRule = this.sortedPathsRules[i];
  403. if (Utilities.startsWith(moduleId, pathRule.from)) {
  404. var result = [];
  405. for (var j = 0, lenJ = pathRule.to.length; j < lenJ; j++) {
  406. result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length));
  407. }
  408. return result;
  409. }
  410. }
  411. return [moduleId];
  412. };
  413. Configuration.prototype._addUrlArgsToUrl = function (url) {
  414. if (Utilities.containsQueryString(url)) {
  415. return url + '&' + this.options.urlArgs;
  416. }
  417. else {
  418. return url + '?' + this.options.urlArgs;
  419. }
  420. };
  421. Configuration.prototype._addUrlArgsIfNecessaryToUrl = function (url) {
  422. if (this.options.urlArgs) {
  423. return this._addUrlArgsToUrl(url);
  424. }
  425. return url;
  426. };
  427. Configuration.prototype._addUrlArgsIfNecessaryToUrls = function (urls) {
  428. if (this.options.urlArgs) {
  429. for (var i = 0, len = urls.length; i < len; i++) {
  430. urls[i] = this._addUrlArgsToUrl(urls[i]);
  431. }
  432. }
  433. return urls;
  434. };
  435. /**
  436. * Transform a module id to a location. Appends .js to module ids
  437. */
  438. Configuration.prototype.moduleIdToPaths = function (moduleId) {
  439. if (this.isBuild() && this.options.nodeModules.indexOf(moduleId) >= 0) {
  440. // This is a node module and we are at build time, drop it
  441. return ['empty:'];
  442. }
  443. var result = moduleId;
  444. if (this.overwriteModuleIdToPath.hasOwnProperty(result)) {
  445. result = this.overwriteModuleIdToPath[result];
  446. }
  447. var results;
  448. if (!Utilities.endsWith(result, '.js') && !Utilities.isAbsolutePath(result)) {
  449. results = this._applyPaths(result);
  450. for (var i = 0, len = results.length; i < len; i++) {
  451. if (this.isBuild() && results[i] === 'empty:') {
  452. continue;
  453. }
  454. if (!Utilities.isAbsolutePath(results[i])) {
  455. results[i] = this.options.baseUrl + results[i];
  456. }
  457. if (!Utilities.endsWith(results[i], '.js') && !Utilities.containsQueryString(results[i])) {
  458. results[i] = results[i] + '.js';
  459. }
  460. }
  461. }
  462. else {
  463. if (!Utilities.endsWith(result, '.js') && !Utilities.containsQueryString(result)) {
  464. result = result + '.js';
  465. }
  466. results = [result];
  467. }
  468. return this._addUrlArgsIfNecessaryToUrls(results);
  469. };
  470. /**
  471. * Transform a module id or url to a location.
  472. */
  473. Configuration.prototype.requireToUrl = function (url) {
  474. var result = url;
  475. if (!Utilities.isAbsolutePath(result)) {
  476. result = this._applyPaths(result)[0];
  477. if (!Utilities.isAbsolutePath(result)) {
  478. result = this.options.baseUrl + result;
  479. }
  480. }
  481. return this._addUrlArgsIfNecessaryToUrl(result);
  482. };
  483. /**
  484. * Test if `moduleId` is shimmed.
  485. */
  486. Configuration.prototype.isShimmed = function (moduleId) {
  487. return this.shimModules.hasOwnProperty(moduleId);
  488. };
  489. /**
  490. * Flag to indicate if current execution is as part of a build.
  491. */
  492. Configuration.prototype.isBuild = function () {
  493. return this.options.isBuild;
  494. };
  495. /**
  496. * Get a normalized shim definition for `moduleId`.
  497. */
  498. Configuration.prototype.getShimmedModuleDefine = function (moduleId) {
  499. return this.shimModules[moduleId];
  500. };
  501. Configuration.prototype.getShimmedModulesStr = function (moduleId) {
  502. return this.shimModulesStr[moduleId];
  503. };
  504. /**
  505. * Test if module `moduleId` is expected to be defined multiple times
  506. */
  507. Configuration.prototype.isDuplicateMessageIgnoredFor = function (moduleId) {
  508. return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId);
  509. };
  510. /**
  511. * Get the configuration settings for the provided module id
  512. */
  513. Configuration.prototype.getConfigForModule = function (moduleId) {
  514. if (this.options.config) {
  515. return this.options.config[moduleId];
  516. }
  517. };
  518. /**
  519. * Should errors be caught when executing module factories?
  520. */
  521. Configuration.prototype.shouldCatchError = function () {
  522. return this.options.catchError;
  523. };
  524. /**
  525. * Should statistics be recorded?
  526. */
  527. Configuration.prototype.shouldRecordStats = function () {
  528. return this.options.recordStats;
  529. };
  530. /**
  531. * Forward an error to the error handler.
  532. */
  533. Configuration.prototype.onError = function (err) {
  534. this.options.onError(err);
  535. };
  536. return Configuration;
  537. }());
  538. AMDLoader.Configuration = Configuration;
  539. // ------------------------------------------------------------------------
  540. // ModuleIdResolver
  541. var ModuleIdResolver = (function () {
  542. function ModuleIdResolver(config, fromModuleId) {
  543. this._config = config;
  544. var lastSlash = fromModuleId.lastIndexOf('/');
  545. if (lastSlash !== -1) {
  546. this.fromModulePath = fromModuleId.substr(0, lastSlash + 1);
  547. }
  548. else {
  549. this.fromModulePath = '';
  550. }
  551. }
  552. ModuleIdResolver.prototype.isBuild = function () {
  553. return this._config.isBuild();
  554. };
  555. /**
  556. * Normalize 'a/../name' to 'name', etc.
  557. */
  558. ModuleIdResolver._normalizeModuleId = function (moduleId) {
  559. var r = moduleId, pattern;
  560. // replace /./ => /
  561. pattern = /\/\.\//;
  562. while (pattern.test(r)) {
  563. r = r.replace(pattern, '/');
  564. }
  565. // replace ^./ => nothing
  566. r = r.replace(/^\.\//g, '');
  567. // replace /aa/../ => / (BUT IGNORE /../../)
  568. pattern = /\/(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//;
  569. while (pattern.test(r)) {
  570. r = r.replace(pattern, '/');
  571. }
  572. // replace ^aa/../ => nothing (BUT IGNORE ../../)
  573. r = r.replace(/^(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//, '');
  574. return r;
  575. };
  576. /**
  577. * Resolve relative module ids
  578. */
  579. ModuleIdResolver.prototype.resolveModule = function (moduleId) {
  580. var result = moduleId;
  581. if (!Utilities.isAbsolutePath(result)) {
  582. if (Utilities.startsWith(result, './') || Utilities.startsWith(result, '../')) {
  583. result = ModuleIdResolver._normalizeModuleId(this.fromModulePath + result);
  584. }
  585. }
  586. return result;
  587. };
  588. /**
  589. * Transform a module id to a location. Appends .js to module ids
  590. */
  591. ModuleIdResolver.prototype.moduleIdToPaths = function (moduleId) {
  592. var r = this._config.moduleIdToPaths(moduleId);
  593. if (isNode && moduleId.indexOf('/') === -1) {
  594. r.push('node|' + this.fromModulePath + '|' + moduleId);
  595. }
  596. return r;
  597. };
  598. /**
  599. * Transform a module id or url to a location.
  600. */
  601. ModuleIdResolver.prototype.requireToUrl = function (url) {
  602. return this._config.requireToUrl(url);
  603. };
  604. /**
  605. * Should errors be caught when executing module factories?
  606. */
  607. ModuleIdResolver.prototype.shouldCatchError = function () {
  608. return this._config.shouldCatchError();
  609. };
  610. /**
  611. * Forward an error to the error handler.
  612. */
  613. ModuleIdResolver.prototype.onError = function (err) {
  614. this._config.onError(err);
  615. };
  616. return ModuleIdResolver;
  617. }());
  618. AMDLoader.ModuleIdResolver = ModuleIdResolver;
  619. // ------------------------------------------------------------------------
  620. // Module
  621. var Module = (function () {
  622. function Module(id, dependencies, callback, errorback, recorder, moduleIdResolver, config, defineCallStack) {
  623. if (defineCallStack === void 0) { defineCallStack = null; }
  624. this._id = id;
  625. this._dependencies = dependencies;
  626. this._dependenciesValues = [];
  627. this._callback = callback;
  628. this._errorback = errorback;
  629. this._recorder = recorder;
  630. this._moduleIdResolver = moduleIdResolver;
  631. this._exports = {};
  632. this._exportsPassedIn = false;
  633. this._config = config;
  634. this._defineCallStack = defineCallStack;
  635. this._digestDependencies();
  636. if (this._unresolvedDependenciesCount === 0) {
  637. this._complete();
  638. }
  639. }
  640. Module.prototype._digestDependencies = function () {
  641. var _this = this;
  642. // Exact count of dependencies
  643. this._unresolvedDependenciesCount = this._dependencies.length;
  644. // Send on to the manager only a subset of dependencies
  645. // For example, 'exports' and 'module' can be fulfilled locally
  646. this._normalizedDependencies = [];
  647. this._managerDependencies = [];
  648. this._managerDependenciesMap = {};
  649. var i, len, d;
  650. for (i = 0, len = this._dependencies.length; i < len; i++) {
  651. d = this._dependencies[i];
  652. if (!d) {
  653. // Most likely, undefined sneaked in to the dependency array
  654. // Also, IE8 interprets ['a', 'b',] as ['a', 'b', undefined]
  655. console.warn('Please check module ' + this._id + ', the dependency list looks broken');
  656. this._normalizedDependencies[i] = d;
  657. this._dependenciesValues[i] = null;
  658. this._unresolvedDependenciesCount--;
  659. continue;
  660. }
  661. if (d === 'exports') {
  662. // Fulfill 'exports' locally and remember that it was passed in
  663. // Later on, we will ignore the return value of the factory method
  664. this._exportsPassedIn = true;
  665. this._normalizedDependencies[i] = d;
  666. this._dependenciesValues[i] = this._exports;
  667. this._unresolvedDependenciesCount--;
  668. }
  669. else if (d === 'module') {
  670. // Fulfill 'module' locally
  671. this._normalizedDependencies[i] = d;
  672. this._dependenciesValues[i] = {
  673. id: this._id,
  674. config: function () { return _this._config; }
  675. };
  676. this._unresolvedDependenciesCount--;
  677. }
  678. else if (d === 'require') {
  679. // Request 'requre' from the manager
  680. this._normalizedDependencies[i] = d;
  681. this.addManagerDependency(d, i);
  682. }
  683. else {
  684. // Normalize dependency and then request it from the manager
  685. var bangIndex = d.indexOf('!');
  686. if (bangIndex >= 0) {
  687. var pluginId = d.substring(0, bangIndex);
  688. var pluginParam = d.substring(bangIndex + 1, d.length);
  689. d = this._moduleIdResolver.resolveModule(pluginId) + '!' + pluginParam;
  690. }
  691. else {
  692. d = this._moduleIdResolver.resolveModule(d);
  693. }
  694. this._normalizedDependencies[i] = d;
  695. this.addManagerDependency(d, i);
  696. }
  697. }
  698. };
  699. Module.prototype.addManagerDependency = function (dependency, index) {
  700. if (this._managerDependenciesMap.hasOwnProperty(dependency)) {
  701. throw new Error('Module ' + this._id + ' contains multiple times a dependency to ' + dependency);
  702. }
  703. this._managerDependencies.push(dependency);
  704. this._managerDependenciesMap[dependency] = index;
  705. };
  706. /**
  707. * Called by the module manager because plugin dependencies can not
  708. * be normalized statically, the part after '!' can only be normalized
  709. * once the plugin has loaded and its normalize logic is plugged in.
  710. */
  711. Module.prototype.renameDependency = function (oldDependencyId, newDependencyId) {
  712. if (!this._managerDependenciesMap.hasOwnProperty(oldDependencyId)) {
  713. throw new Error('Loader: Cannot rename an unknown dependency!');
  714. }
  715. var index = this._managerDependenciesMap[oldDependencyId];
  716. delete this._managerDependenciesMap[oldDependencyId];
  717. this._managerDependenciesMap[newDependencyId] = index;
  718. this._normalizedDependencies[index] = newDependencyId;
  719. };
  720. /**
  721. * Get module's id
  722. */
  723. Module.prototype.getId = function () {
  724. return this._id;
  725. };
  726. /**
  727. * Get the module id resolver associated with this module
  728. */
  729. Module.prototype.getModuleIdResolver = function () {
  730. return this._moduleIdResolver;
  731. };
  732. Module.prototype.isExportsPassedIn = function () {
  733. return this._exportsPassedIn;
  734. };
  735. Module.prototype.getExports = function () {
  736. return this._exports;
  737. };
  738. /**
  739. * Get the initial dependencies (resolved).
  740. * Does not account for any renames
  741. */
  742. Module.prototype.getDependencies = function () {
  743. return this._managerDependencies;
  744. };
  745. Module.prototype.getNormalizedDependencies = function () {
  746. return this._normalizedDependencies;
  747. };
  748. Module.prototype.getDefineCallStack = function () {
  749. return this._defineCallStack;
  750. };
  751. Module.prototype._invokeFactory = function () {
  752. if (this._moduleIdResolver.isBuild() && !Utilities.isAnonymousModule(this._id)) {
  753. return {
  754. returnedValue: null,
  755. producedError: null
  756. };
  757. }
  758. var producedError = null, returnedValue = null;
  759. if (this._moduleIdResolver.shouldCatchError()) {
  760. try {
  761. returnedValue = this._callback.apply(global, this._dependenciesValues);
  762. }
  763. catch (e) {
  764. producedError = e;
  765. }
  766. finally {
  767. }
  768. }
  769. else {
  770. returnedValue = this._callback.apply(global, this._dependenciesValues);
  771. }
  772. return {
  773. returnedValue: returnedValue,
  774. producedError: producedError
  775. };
  776. };
  777. Module.prototype._complete = function () {
  778. var producedError = null;
  779. if (this._callback) {
  780. if (typeof this._callback === 'function') {
  781. this._recorder.record(LoaderEventType.BeginInvokeFactory, this._id);
  782. var r = this._invokeFactory();
  783. producedError = r.producedError;
  784. this._recorder.record(LoaderEventType.EndInvokeFactory, this._id);
  785. if (!producedError && typeof r.returnedValue !== 'undefined' && (!this._exportsPassedIn || Utilities.isEmpty(this._exports))) {
  786. this._exports = r.returnedValue;
  787. }
  788. }
  789. else {
  790. this._exports = this._callback;
  791. }
  792. }
  793. if (producedError) {
  794. this.getModuleIdResolver().onError({
  795. errorCode: 'factory',
  796. moduleId: this._id,
  797. detail: producedError
  798. });
  799. }
  800. };
  801. /**
  802. * Release references used while resolving module
  803. */
  804. Module.prototype.cleanUp = function () {
  805. if (this._moduleIdResolver && !this._moduleIdResolver.isBuild()) {
  806. this._normalizedDependencies = null;
  807. this._moduleIdResolver = null;
  808. }
  809. this._dependencies = null;
  810. this._dependenciesValues = null;
  811. this._callback = null;
  812. this._managerDependencies = null;
  813. this._managerDependenciesMap = null;
  814. };
  815. /**
  816. * One of the direct dependencies or a transitive dependency has failed to load.
  817. */
  818. Module.prototype.onDependencyError = function (err) {
  819. if (this._errorback) {
  820. this._errorback(err);
  821. return true;
  822. }
  823. return false;
  824. };
  825. /**
  826. * Resolve a dependency with a value.
  827. */
  828. Module.prototype.resolveDependency = function (id, value) {
  829. if (!this._managerDependenciesMap.hasOwnProperty(id)) {
  830. throw new Error('Cannot resolve a dependency I do not have!');
  831. }
  832. this._dependenciesValues[this._managerDependenciesMap[id]] = value;
  833. // Prevent resolving the same dependency twice
  834. delete this._managerDependenciesMap[id];
  835. this._unresolvedDependenciesCount--;
  836. if (this._unresolvedDependenciesCount === 0) {
  837. this._complete();
  838. }
  839. };
  840. /**
  841. * Is the current module complete?
  842. */
  843. Module.prototype.isComplete = function () {
  844. return this._unresolvedDependenciesCount === 0;
  845. };
  846. return Module;
  847. }());
  848. AMDLoader.Module = Module;
  849. // ------------------------------------------------------------------------
  850. // LoaderEvent
  851. (function (LoaderEventType) {
  852. LoaderEventType[LoaderEventType["LoaderAvailable"] = 1] = "LoaderAvailable";
  853. LoaderEventType[LoaderEventType["BeginLoadingScript"] = 10] = "BeginLoadingScript";
  854. LoaderEventType[LoaderEventType["EndLoadingScriptOK"] = 11] = "EndLoadingScriptOK";
  855. LoaderEventType[LoaderEventType["EndLoadingScriptError"] = 12] = "EndLoadingScriptError";
  856. LoaderEventType[LoaderEventType["BeginInvokeFactory"] = 21] = "BeginInvokeFactory";
  857. LoaderEventType[LoaderEventType["EndInvokeFactory"] = 22] = "EndInvokeFactory";
  858. LoaderEventType[LoaderEventType["NodeBeginEvaluatingScript"] = 31] = "NodeBeginEvaluatingScript";
  859. LoaderEventType[LoaderEventType["NodeEndEvaluatingScript"] = 32] = "NodeEndEvaluatingScript";
  860. LoaderEventType[LoaderEventType["NodeBeginNativeRequire"] = 33] = "NodeBeginNativeRequire";
  861. LoaderEventType[LoaderEventType["NodeEndNativeRequire"] = 34] = "NodeEndNativeRequire";
  862. })(AMDLoader.LoaderEventType || (AMDLoader.LoaderEventType = {}));
  863. var LoaderEventType = AMDLoader.LoaderEventType;
  864. function getHighPerformanceTimestamp() {
  865. return (hasPerformanceNow ? global.performance.now() : Date.now());
  866. }
  867. var LoaderEvent = (function () {
  868. function LoaderEvent(type, detail, timestamp) {
  869. this.type = type;
  870. this.detail = detail;
  871. this.timestamp = timestamp;
  872. }
  873. return LoaderEvent;
  874. }());
  875. AMDLoader.LoaderEvent = LoaderEvent;
  876. var LoaderEventRecorder = (function () {
  877. function LoaderEventRecorder(loaderAvailableTimestamp) {
  878. this._events = [new LoaderEvent(LoaderEventType.LoaderAvailable, '', loaderAvailableTimestamp)];
  879. }
  880. LoaderEventRecorder.prototype.record = function (type, detail) {
  881. this._events.push(new LoaderEvent(type, detail, getHighPerformanceTimestamp()));
  882. };
  883. LoaderEventRecorder.prototype.getEvents = function () {
  884. return this._events;
  885. };
  886. return LoaderEventRecorder;
  887. }());
  888. AMDLoader.LoaderEventRecorder = LoaderEventRecorder;
  889. var NullLoaderEventRecorder = (function () {
  890. function NullLoaderEventRecorder() {
  891. }
  892. NullLoaderEventRecorder.prototype.record = function (type, detail) {
  893. // Nothing to do
  894. };
  895. NullLoaderEventRecorder.prototype.getEvents = function () {
  896. return [];
  897. };
  898. NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder();
  899. return NullLoaderEventRecorder;
  900. }());
  901. AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder;
  902. var ModuleManager = (function () {
  903. function ModuleManager(scriptLoader) {
  904. this._recorder = null;
  905. this._config = new Configuration();
  906. this._scriptLoader = scriptLoader;
  907. this._modules = {};
  908. this._knownModules = {};
  909. this._inverseDependencies = {};
  910. this._dependencies = {};
  911. this._inversePluginDependencies = {};
  912. this._queuedDefineCalls = [];
  913. this._loadingScriptsCount = 0;
  914. this._resolvedScriptPaths = {};
  915. }
  916. ModuleManager._findRelevantLocationInStack = function (needle, stack) {
  917. var normalize = function (str) { return str.replace(/\\/g, '/'); };
  918. var normalizedPath = normalize(needle);
  919. var stackPieces = stack.split(/\n/);
  920. for (var i = 0; i < stackPieces.length; i++) {
  921. var m = stackPieces[i].match(/(.*):(\d+):(\d+)\)?$/);
  922. if (m) {
  923. var stackPath = m[1];
  924. var stackLine = m[2];
  925. var stackColumn = m[3];
  926. var trimPathOffset = Math.max(stackPath.lastIndexOf(' ') + 1, stackPath.lastIndexOf('(') + 1);
  927. stackPath = stackPath.substr(trimPathOffset);
  928. stackPath = normalize(stackPath);
  929. if (stackPath === normalizedPath) {
  930. var r = {
  931. line: parseInt(stackLine, 10),
  932. col: parseInt(stackColumn, 10)
  933. };
  934. if (r.line === 1) {
  935. r.col -= '(function (require, define, __filename, __dirname) { '.length;
  936. }
  937. return r;
  938. }
  939. }
  940. }
  941. throw new Error('Could not correlate define call site for needle ' + needle);
  942. };
  943. ModuleManager.prototype.getBuildInfo = function () {
  944. var _this = this;
  945. if (!this._config.isBuild()) {
  946. return null;
  947. }
  948. return Object.keys(this._modules).map(function (moduleId) {
  949. var m = _this._modules[moduleId];
  950. var location = _this._resolvedScriptPaths[moduleId] || null;
  951. var defineStack = m.getDefineCallStack();
  952. return {
  953. id: moduleId,
  954. path: location,
  955. defineLocation: (location && defineStack ? ModuleManager._findRelevantLocationInStack(location, defineStack) : null),
  956. dependencies: m.getNormalizedDependencies(),
  957. shim: (_this._config.isShimmed(moduleId) ? _this._config.getShimmedModulesStr(moduleId) : null),
  958. exports: m.getExports()
  959. };
  960. });
  961. };
  962. ModuleManager.prototype.getRecorder = function () {
  963. if (!this._recorder) {
  964. if (this._config.shouldRecordStats()) {
  965. this._recorder = new LoaderEventRecorder(loaderAvailableTimestamp);
  966. }
  967. else {
  968. this._recorder = NullLoaderEventRecorder.INSTANCE;
  969. }
  970. }
  971. return this._recorder;
  972. };
  973. ModuleManager.prototype.getLoaderEvents = function () {
  974. return this.getRecorder().getEvents();
  975. };
  976. /**
  977. * Defines a module.
  978. * @param id @see defineModule
  979. * @param dependencies @see defineModule
  980. * @param callback @see defineModule
  981. */
  982. ModuleManager.prototype.enqueueDefineModule = function (id, dependencies, callback) {
  983. if (this._loadingScriptsCount === 0) {
  984. // There are no scripts currently loading, so no load event will be fired, so the queue will not be consumed
  985. this.defineModule(id, dependencies, callback, null, null);
  986. }
  987. else {
  988. this._queuedDefineCalls.push({
  989. id: id,
  990. stack: null,
  991. dependencies: dependencies,
  992. callback: callback
  993. });
  994. }
  995. };
  996. /**
  997. * Defines an anonymous module (without an id). Its name will be resolved as we receive a callback from the scriptLoader.
  998. * @param dependecies @see defineModule
  999. * @param callback @see defineModule
  1000. */
  1001. ModuleManager.prototype.enqueueDefineAnonymousModule = function (dependencies, callback) {
  1002. var stack = null;
  1003. if (this._config.isBuild()) {
  1004. stack = (new Error('StackLocation')).stack;
  1005. }
  1006. this._queuedDefineCalls.push({
  1007. id: null,
  1008. stack: stack,
  1009. dependencies: dependencies,
  1010. callback: callback
  1011. });
  1012. };
  1013. /**
  1014. * Creates a module and stores it in _modules. The manager will immediately begin resolving its dependencies.
  1015. * @param id An unique and absolute id of the module. This must not collide with another module's id
  1016. * @param dependencies An array with the dependencies of the module. Special keys are: "require", "exports" and "module"
  1017. * @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.
  1018. */
  1019. ModuleManager.prototype.defineModule = function (id, dependencies, callback, errorback, stack, moduleIdResolver) {
  1020. if (moduleIdResolver === void 0) { moduleIdResolver = new ModuleIdResolver(this._config, id); }
  1021. if (this._modules.hasOwnProperty(id)) {
  1022. if (!this._config.isDuplicateMessageIgnoredFor(id)) {
  1023. console.warn('Duplicate definition of module \'' + id + '\'');
  1024. }
  1025. // Super important! Completely ignore duplicate module definition
  1026. return;
  1027. }
  1028. var moduleConfig = this._config.getConfigForModule(id);
  1029. var m = new Module(id, dependencies, callback, errorback, this.getRecorder(), moduleIdResolver, moduleConfig, stack);
  1030. this._modules[id] = m;
  1031. // Resolving of dependencies is immediate (not in a timeout). If there's a need to support a packer that concatenates in an
  1032. // unordered manner, in order to finish processing the file, execute the following method in a timeout
  1033. this._resolve(m);
  1034. };
  1035. ModuleManager.prototype._relativeRequire = function (moduleIdResolver, dependencies, callback, errorback) {
  1036. if (typeof dependencies === 'string') {
  1037. return this.synchronousRequire(dependencies, moduleIdResolver);
  1038. }
  1039. this.defineModule(Utilities.generateAnonymousModule(), dependencies, callback, errorback, null, moduleIdResolver);
  1040. };
  1041. /**
  1042. * Require synchronously a module by its absolute id. If the module is not loaded, an exception will be thrown.
  1043. * @param id The unique and absolute id of the required module
  1044. * @return The exports of module 'id'
  1045. */
  1046. ModuleManager.prototype.synchronousRequire = function (id, moduleIdResolver) {
  1047. if (moduleIdResolver === void 0) { moduleIdResolver = new ModuleIdResolver(this._config, id); }
  1048. var moduleId = moduleIdResolver.resolveModule(id);
  1049. var bangIndex = moduleId.indexOf('!');
  1050. if (bangIndex >= 0) {
  1051. // This is a synchronous require for a plugin dependency, so be sure to normalize the pluginParam (the piece after '!')
  1052. var pluginId = moduleId.substring(0, bangIndex), pluginParam = moduleId.substring(bangIndex + 1, moduleId.length), plugin = {};
  1053. if (this._modules.hasOwnProperty(pluginId)) {
  1054. plugin = this._modules[pluginId];
  1055. }
  1056. // Helper to normalize the part which comes after '!'
  1057. var normalize = function (_arg) {
  1058. return moduleIdResolver.resolveModule(_arg);
  1059. };
  1060. if (typeof plugin.normalize === 'function') {
  1061. pluginParam = plugin.normalize(pluginParam, normalize);
  1062. }
  1063. else {
  1064. pluginParam = normalize(pluginParam);
  1065. }
  1066. moduleId = pluginId + '!' + pluginParam;
  1067. }
  1068. if (!this._modules.hasOwnProperty(moduleId)) {
  1069. throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + moduleId + '\'. This is the first mention of this module!');
  1070. }
  1071. var m = this._modules[moduleId];
  1072. if (!m.isComplete()) {
  1073. throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + moduleId + '\'. This module has not been resolved completely yet.');
  1074. }
  1075. return m.getExports();
  1076. };
  1077. ModuleManager.prototype.configure = function (params, shouldOverwrite) {
  1078. var oldShouldRecordStats = this._config.shouldRecordStats();
  1079. if (shouldOverwrite) {
  1080. this._config = new Configuration(params);
  1081. }
  1082. else {
  1083. this._config = this._config.cloneAndMerge(params);
  1084. }
  1085. if (this._config.shouldRecordStats() && !oldShouldRecordStats) {
  1086. this._recorder = null;
  1087. }
  1088. };
  1089. ModuleManager.prototype.getConfigurationOptions = function () {
  1090. return this._config.getOptionsLiteral();
  1091. };
  1092. /**
  1093. * Callback from the scriptLoader when a module has been loaded.
  1094. * This means its code is available and has been executed.
  1095. */
  1096. ModuleManager.prototype._onLoad = function (id) {
  1097. var defineCall;
  1098. this._loadingScriptsCount--;
  1099. if (this._config.isShimmed(id)) {
  1100. // Do not consume queue, might end up consuming a module that is later expected
  1101. // If a shimmed module has loaded, create a define call for it
  1102. defineCall = this._config.getShimmedModuleDefine(id);
  1103. this.defineModule(id, defineCall.dependencies, defineCall.callback, null, defineCall.stack);
  1104. }
  1105. else {
  1106. if (this._queuedDefineCalls.length === 0) {
  1107. // Loaded a file and it didn't call `define`
  1108. this._loadingScriptsCount++;
  1109. this._onLoadError(id, new Error('No define call received from module ' + id + '.'));
  1110. }
  1111. else {
  1112. // Consume queue until first anonymous define call
  1113. // or until current id is found in the queue
  1114. while (this._queuedDefineCalls.length > 0) {
  1115. defineCall = this._queuedDefineCalls.shift();
  1116. if (defineCall.id === id || defineCall.id === null) {
  1117. // Hit an anonymous define call or its own define call
  1118. defineCall.id = id;
  1119. this.defineModule(defineCall.id, defineCall.dependencies, defineCall.callback, null, defineCall.stack);
  1120. break;
  1121. }
  1122. else {
  1123. // Hit other named define calls
  1124. this.defineModule(defineCall.id, defineCall.dependencies, defineCall.callback, null, defineCall.stack);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. if (this._loadingScriptsCount === 0) {
  1130. // No more on loads will be triggered, so make sure queue is empty
  1131. while (this._queuedDefineCalls.length > 0) {
  1132. defineCall = this._queuedDefineCalls.shift();
  1133. if (defineCall.id === null) {
  1134. console.warn('Found an unmatched anonymous define call in the define queue. Ignoring it!');
  1135. console.warn(defineCall.callback);
  1136. }
  1137. else {
  1138. // Hit other named define calls
  1139. this.defineModule(defineCall.id, defineCall.dependencies, defineCall.callback, null, defineCall.stack);
  1140. }
  1141. }
  1142. }
  1143. };
  1144. /**
  1145. * Callback from the scriptLoader when a module hasn't been loaded.
  1146. * This means that the script was not found (e.g. 404) or there was an error in the script.
  1147. */
  1148. ModuleManager.prototype._onLoadError = function (id, err) {
  1149. this._loadingScriptsCount--;
  1150. var error = {
  1151. errorCode: 'load',
  1152. moduleId: id,
  1153. neededBy: (this._inverseDependencies[id] ? this._inverseDependencies[id].slice(0) : []),
  1154. detail: err
  1155. };
  1156. // Find any 'local' error handlers, walk the entire chain of inverse dependencies if necessary.
  1157. var seenModuleId = {}, queueElement, someoneNotified = false, queue = [];
  1158. queue.push(id);
  1159. seenModuleId[id] = true;
  1160. while (queue.length > 0) {
  1161. queueElement = queue.shift();
  1162. if (this._modules[queueElement]) {
  1163. someoneNotified = this._modules[queueElement].onDependencyError(error) || someoneNotified;
  1164. }
  1165. if (this._inverseDependencies[queueElement]) {
  1166. for (var i = 0, len = this._inverseDependencies[queueElement].length; i < len; i++) {
  1167. if (!seenModuleId.hasOwnProperty(this._inverseDependencies[queueElement][i])) {
  1168. queue.push(this._inverseDependencies[queueElement][i]);
  1169. seenModuleId[this._inverseDependencies[queueElement][i]] = true;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. if (!someoneNotified) {
  1175. this._config.onError(error);
  1176. }
  1177. };
  1178. /**
  1179. * Module id has been loaded completely, its exports are available.
  1180. * @param id module's id
  1181. * @param exports module's exports
  1182. */
  1183. ModuleManager.prototype._onModuleComplete = function (id, exports) {
  1184. var i, len, inverseDependencyId, inverseDependency;
  1185. // Clean up module's dependencies since module is now complete
  1186. delete this._dependencies[id];
  1187. if (this._inverseDependencies.hasOwnProperty(id)) {
  1188. // Fetch and clear inverse dependencies
  1189. var inverseDependencies = this._inverseDependencies[id];
  1190. delete this._inverseDependencies[id];
  1191. // Resolve one inverse dependency at a time, always
  1192. // on the lookout for a completed module.
  1193. for (i = 0, len = inverseDependencies.length; i < len; i++) {
  1194. inverseDependencyId = inverseDependencies[i];
  1195. inverseDependency = this._modules[inverseDependencyId];
  1196. inverseDependency.resolveDependency(id, exports);
  1197. if (inverseDependency.isComplete()) {
  1198. this._onModuleComplete(inverseDependencyId, inverseDependency.getExports());
  1199. }
  1200. }
  1201. }
  1202. if (this._inversePluginDependencies.hasOwnProperty(id)) {
  1203. // This module is used as a plugin at least once
  1204. // Fetch and clear these inverse plugin dependencies
  1205. var inversePluginDependencies = this._inversePluginDependencies[id];
  1206. delete this._inversePluginDependencies[id];
  1207. // Resolve plugin dependencies one at a time
  1208. for (i = 0, len = inversePluginDependencies.length; i < len; i++) {
  1209. var inversePluginDependencyId = inversePluginDependencies[i].moduleId;
  1210. var inversePluginDependency = this._modules[inversePluginDependencyId];
  1211. this._resolvePluginDependencySync(inversePluginDependencyId, inversePluginDependencies[i].dependencyId, exports);
  1212. // Anonymous modules might already be gone at this point
  1213. if (inversePluginDependency.isComplete()) {
  1214. this._onModuleComplete(inversePluginDependencyId, inversePluginDependency.getExports());
  1215. }
  1216. }
  1217. }
  1218. if (Utilities.isAnonymousModule(id)) {
  1219. // Clean up references to anonymous modules, to prevent memory leaks
  1220. delete this._modules[id];
  1221. delete this._dependencies[id];
  1222. }
  1223. else {
  1224. this._modules[id].cleanUp();
  1225. }
  1226. };
  1227. /**
  1228. * Walks (recursively) the dependencies of 'from' in search of 'to'.
  1229. * Returns true if there is such a path or false otherwise.
  1230. * @param from Module id to start at
  1231. * @param to Module id to look for
  1232. */
  1233. ModuleManager.prototype._hasDependencyPath = function (from, to) {
  1234. var i, len, inQueue = {}, queue = [], element, dependencies, dependency;
  1235. // Insert 'from' in queue
  1236. queue.push(from);
  1237. inQueue[from] = true;
  1238. while (queue.length > 0) {
  1239. // Pop first inserted element of queue
  1240. element = queue.shift();
  1241. if (this._dependencies.hasOwnProperty(element)) {
  1242. dependencies = this._dependencies[element];
  1243. // Walk the element's dependencies
  1244. for (i = 0, len = dependencies.length; i < len; i++) {
  1245. dependency = dependencies[i];
  1246. if (dependency === to) {
  1247. // There is a path to 'to'
  1248. return true;
  1249. }
  1250. if (!inQueue.hasOwnProperty(dependency)) {
  1251. // Insert 'dependency' in queue
  1252. inQueue[dependency] = true;
  1253. queue.push(dependency);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. // There is no path to 'to'
  1259. return false;
  1260. };
  1261. /**
  1262. * Walks (recursively) the dependencies of 'from' in search of 'to'.
  1263. * Returns cycle as array.
  1264. * @param from Module id to start at
  1265. * @param to Module id to look for
  1266. */
  1267. ModuleManager.prototype._findCyclePath = function (from, to, depth) {
  1268. if (from === to || depth === 50) {
  1269. return [from];
  1270. }
  1271. if (!this._dependencies.hasOwnProperty(from)) {
  1272. return null;
  1273. }
  1274. var path, dependencies = this._dependencies[from];
  1275. // Walk the element's dependencies
  1276. for (var i = 0, len = dependencies.length; i < len; i++) {
  1277. path = this._findCyclePath(dependencies[i], to, depth + 1);
  1278. if (path !== null) {
  1279. path.push(from);
  1280. return path;
  1281. }
  1282. }
  1283. return null;
  1284. };
  1285. /**
  1286. * Create the local 'require' that is passed into modules
  1287. */
  1288. ModuleManager.prototype._createRequire = function (moduleIdResolver) {
  1289. var _this = this;
  1290. var result = (function (dependencies, callback, errorback) {
  1291. return _this._relativeRequire(moduleIdResolver, dependencies, callback, errorback);
  1292. });
  1293. result.toUrl = function (id) {
  1294. return moduleIdResolver.requireToUrl(moduleIdResolver.resolveModule(id));
  1295. };
  1296. result.getStats = function () {
  1297. return _this.getLoaderEvents();
  1298. };
  1299. result.__$__nodeRequire = global.nodeRequire;
  1300. return result;
  1301. };
  1302. /**
  1303. * Resolve a plugin dependency with the plugin loaded & complete
  1304. * @param moduleId The module that has this dependency
  1305. * @param dependencyId The semi-normalized dependency that appears in the module. e.g. 'vs/css!./mycssfile'. Only the plugin part (before !) is normalized
  1306. * @param plugin The plugin (what the plugin exports)
  1307. */
  1308. ModuleManager.prototype._resolvePluginDependencySync = function (moduleId, dependencyId, plugin) {
  1309. var _this = this;
  1310. var m = this._modules[moduleId], moduleIdResolver = m.getModuleIdResolver(), bangIndex = dependencyId.indexOf('!'), pluginId = dependencyId.substring(0, bangIndex), pluginParam = dependencyId.substring(bangIndex + 1, dependencyId.length);
  1311. // Helper to normalize the part which comes after '!'
  1312. var normalize = function (_arg) {
  1313. return moduleIdResolver.resolveModule(_arg);
  1314. };
  1315. if (typeof plugin.normalize === 'function') {
  1316. pluginParam = plugin.normalize(pluginParam, normalize);
  1317. }
  1318. else {
  1319. pluginParam = normalize(pluginParam);
  1320. }
  1321. if (!plugin.dynamic) {
  1322. // Now normalize the entire dependency
  1323. var oldDependencyId = dependencyId;
  1324. dependencyId = pluginId + '!' + pluginParam;
  1325. // Let the module know that the dependency has been normalized so it can update its internal state
  1326. m.renameDependency(oldDependencyId, dependencyId);
  1327. this._resolveDependency(moduleId, dependencyId, function (moduleId) {
  1328. // Delegate the loading of the resource to the plugin
  1329. var load = (function (value) {
  1330. _this.defineModule(dependencyId, [], value, null, null);
  1331. });
  1332. load.error = function (err) {
  1333. _this._config.onError({
  1334. errorCode: 'load',
  1335. moduleId: dependencyId,
  1336. neededBy: (_this._inverseDependencies[dependencyId] ? _this._inverseDependencies[dependencyId].slice(0) : []),
  1337. detail: err
  1338. });
  1339. };
  1340. plugin.load(pluginParam, _this._createRequire(moduleIdResolver), load, _this._config.getOptionsLiteral());
  1341. });
  1342. }
  1343. else {
  1344. // This plugin is dynamic and does not want the loader to cache anything on its behalf
  1345. // Delegate the loading of the resource to the plugin
  1346. var load = (function (value) {
  1347. m.resolveDependency(dependencyId, value);
  1348. if (m.isComplete()) {
  1349. _this._onModuleComplete(moduleId, m.getExports());
  1350. }
  1351. });
  1352. load.error = function (err) {
  1353. _this._config.onError({
  1354. errorCode: 'load',
  1355. moduleId: dependencyId,
  1356. neededBy: [moduleId],
  1357. detail: err
  1358. });
  1359. };
  1360. plugin.load(pluginParam, this._createRequire(moduleIdResolver), load, this._config.getOptionsLiteral());
  1361. }
  1362. };
  1363. /**
  1364. * Resolve a plugin dependency with the plugin not loaded or not complete yet
  1365. * @param moduleId The module that has this dependency
  1366. * @param dependencyId The semi-normalized dependency that appears in the module. e.g. 'vs/css!./mycssfile'. Only the plugin part (before !) is normalized
  1367. */
  1368. ModuleManager.prototype._resolvePluginDependencyAsync = function (moduleId, dependencyId) {
  1369. var m = this._modules[moduleId], bangIndex = dependencyId.indexOf('!'), pluginId = dependencyId.substring(0, bangIndex);
  1370. // Record dependency for when the plugin gets loaded
  1371. this._inversePluginDependencies[pluginId] = this._inversePluginDependencies[pluginId] || [];
  1372. this._inversePluginDependencies[pluginId].push({
  1373. moduleId: moduleId,
  1374. dependencyId: dependencyId
  1375. });
  1376. if (!this._modules.hasOwnProperty(pluginId) && !this._knownModules.hasOwnProperty(pluginId)) {
  1377. // This is the first mention of module 'pluginId', so load it
  1378. this._knownModules[pluginId] = true;
  1379. this._loadModule(m.getModuleIdResolver(), pluginId);
  1380. }
  1381. };
  1382. /**
  1383. * Resolve a plugin dependency
  1384. * @param moduleId The module that has this dependency
  1385. * @param dependencyId The semi-normalized dependency that appears in the module. e.g. 'vs/css!./mycssfile'. Only the plugin part (before !) is normalized
  1386. */
  1387. ModuleManager.prototype._resolvePluginDependency = function (moduleId, dependencyId) {
  1388. var bangIndex = dependencyId.indexOf('!'), pluginId = dependencyId.substring(0, bangIndex);
  1389. if (this._modules.hasOwnProperty(pluginId) && this._modules[pluginId].isComplete()) {
  1390. // Plugin has already been loaded & resolved
  1391. this._resolvePluginDependencySync(moduleId, dependencyId, this._modules[pluginId].getExports());
  1392. }
  1393. else {
  1394. // Plugin is not loaded or not resolved
  1395. this._resolvePluginDependencyAsync(moduleId, dependencyId);
  1396. }
  1397. };
  1398. /**
  1399. * Resolve a module dependency to a shimmed module and delegate the loading to loadCallback.
  1400. * @param moduleId The module that has this dependency
  1401. * @param dependencyId The normalized dependency that appears in the module -- this module is shimmed
  1402. * @param loadCallback Callback that will be called to trigger the loading of 'dependencyId' if needed
  1403. */
  1404. ModuleManager.prototype._resolveShimmedDependency = function (moduleId, dependencyId, loadCallback) {
  1405. // If a shimmed module has dependencies, we must first load those dependencies
  1406. // and only when those are loaded we can load the shimmed module.
  1407. // To achieve this, we inject a module definition with those dependencies
  1408. // and from its factory method we really load the shimmed module.
  1409. var defineInfo = this._config.getShimmedModuleDefine(dependencyId);
  1410. if (defineInfo.dependencies.length > 0) {
  1411. this.defineModule(Utilities.generateAnonymousModule(), defineInfo.dependencies, function () { return loadCallback(dependencyId); }, null, null, new ModuleIdResolver(this._config, dependencyId));
  1412. }
  1413. else {
  1414. loadCallback(dependencyId);
  1415. }
  1416. };
  1417. /**
  1418. * Resolve a module dependency and delegate the loading to loadCallback
  1419. * @param moduleId The module that has this dependency
  1420. * @param dependencyId The normalized dependency that appears in the module
  1421. * @param loadCallback Callback that will be called to trigger the loading of 'dependencyId' if needed
  1422. */
  1423. ModuleManager.prototype._resolveDependency = function (moduleId, dependencyId, loadCallback) {
  1424. var m = this._modules[moduleId];
  1425. if (this._modules.hasOwnProperty(dependencyId) && this._modules[dependencyId].isComplete()) {
  1426. // Dependency has already been loaded & resolved
  1427. m.resolveDependency(dependencyId, this._modules[dependencyId].getExports());
  1428. }
  1429. else {
  1430. // Dependency is not loaded or not resolved
  1431. // Record dependency
  1432. this._dependencies[moduleId].push(dependencyId);
  1433. if (this._hasDependencyPath(dependencyId, moduleId)) {
  1434. console.warn('There is a dependency cycle between \'' + dependencyId + '\' and \'' + moduleId + '\'. The cyclic path follows:');
  1435. var cyclePath = this._findCyclePath(dependencyId, moduleId, 0);
  1436. cyclePath.reverse();
  1437. cyclePath.push(dependencyId);
  1438. console.warn(cyclePath.join(' => \n'));
  1439. // Break the cycle
  1440. var dependency = this._modules.hasOwnProperty(dependencyId) ? this._modules[dependencyId] : null;
  1441. var dependencyValue;
  1442. if (dependency && dependency.isExportsPassedIn()) {
  1443. // If dependency uses 'exports', then resolve it with that object
  1444. dependencyValue = dependency.getExports();
  1445. }
  1446. // Resolve dependency with undefined or with 'exports' object
  1447. m.resolveDependency(dependencyId, dependencyValue);
  1448. }
  1449. else {
  1450. // Since we are actually waiting for this dependency,
  1451. // record inverse dependency
  1452. this._inverseDependencies[dependencyId] = this._inverseDependencies[dependencyId] || [];
  1453. this._inverseDependencies[dependencyId].push(moduleId);
  1454. if (!this._modules.hasOwnProperty(dependencyId) && !this._knownModules.hasOwnProperty(dependencyId)) {
  1455. // This is the first mention of module 'dependencyId', so load it
  1456. // Mark this module as loaded so we don't hit this case again
  1457. this._knownModules[dependencyId] = true;
  1458. if (this._config.isShimmed(dependencyId)) {
  1459. this._resolveShimmedDependency(moduleId, dependencyId, loadCallback);
  1460. }
  1461. else {
  1462. loadCallback(dependencyId);
  1463. }
  1464. }
  1465. }
  1466. }
  1467. };
  1468. ModuleManager.prototype._loadModule = function (anyModuleIdResolver, moduleId) {
  1469. var _this = this;
  1470. this._loadingScriptsCount++;
  1471. var paths = anyModuleIdResolver.moduleIdToPaths(moduleId);
  1472. var lastPathIndex = -1;
  1473. var loadNextPath = function (err) {
  1474. lastPathIndex++;
  1475. if (lastPathIndex >= paths.length) {
  1476. // No more paths to try
  1477. _this._onLoadError(moduleId, err);
  1478. }
  1479. else {
  1480. var currentPath = paths[lastPathIndex];
  1481. var recorder = _this.getRecorder();
  1482. if (_this._config.isBuild() && currentPath === 'empty:') {
  1483. _this._resolvedScriptPaths[moduleId] = currentPath;
  1484. _this.enqueueDefineModule(moduleId, [], null);
  1485. _this._onLoad(moduleId);
  1486. return;
  1487. }
  1488. recorder.record(LoaderEventType.BeginLoadingScript, currentPath);
  1489. _this._scriptLoader.load(currentPath, function () {
  1490. if (_this._config.isBuild()) {
  1491. _this._resolvedScriptPaths[moduleId] = currentPath;
  1492. }
  1493. recorder.record(LoaderEventType.EndLoadingScriptOK, currentPath);
  1494. _this._onLoad(moduleId);
  1495. }, function (err) {
  1496. recorder.record(LoaderEventType.EndLoadingScriptError, currentPath);
  1497. loadNextPath(err);
  1498. }, recorder);
  1499. }
  1500. };
  1501. loadNextPath(null);
  1502. };
  1503. /**
  1504. * Examine the dependencies of module 'module' and resolve them as needed.
  1505. */
  1506. ModuleManager.prototype._resolve = function (m) {
  1507. var _this = this;
  1508. var i, len, id, dependencies, dependencyId, moduleIdResolver;
  1509. id = m.getId();
  1510. dependencies = m.getDependencies();
  1511. moduleIdResolver = m.getModuleIdResolver();
  1512. this._dependencies[id] = [];
  1513. var loadCallback = function (moduleId) { return _this._loadModule(moduleIdResolver, moduleId); };
  1514. for (i = 0, len = dependencies.length; i < len; i++) {
  1515. dependencyId = dependencies[i];
  1516. if (dependencyId === 'require') {
  1517. m.resolveDependency(dependencyId, this._createRequire(moduleIdResolver));
  1518. continue;
  1519. }
  1520. else {
  1521. if (dependencyId.indexOf('!') >= 0) {
  1522. this._resolvePluginDependency(id, dependencyId);
  1523. }
  1524. else {
  1525. this._resolveDependency(id, dependencyId, loadCallback);
  1526. }
  1527. }
  1528. }
  1529. if (m.isComplete()) {
  1530. // This module was completed as soon as its been seen.
  1531. this._onModuleComplete(id, m.getExports());
  1532. }
  1533. };
  1534. return ModuleManager;
  1535. }());
  1536. AMDLoader.ModuleManager = ModuleManager;
  1537. /**
  1538. * Load `scriptSrc` only once (avoid multiple <script> tags)
  1539. */
  1540. var OnlyOnceScriptLoader = (function () {
  1541. function OnlyOnceScriptLoader(actualScriptLoader) {
  1542. this.actualScriptLoader = actualScriptLoader;
  1543. this.callbackMap = {};
  1544. }
  1545. OnlyOnceScriptLoader.prototype.setModuleManager = function (moduleManager) {
  1546. this.actualScriptLoader.setModuleManager(moduleManager);
  1547. };
  1548. OnlyOnceScriptLoader.prototype.load = function (scriptSrc, callback, errorback, recorder) {
  1549. var _this = this;
  1550. var scriptCallbacks = {
  1551. callback: callback,
  1552. errorback: errorback
  1553. };
  1554. if (this.callbackMap.hasOwnProperty(scriptSrc)) {
  1555. this.callbackMap[scriptSrc].push(scriptCallbacks);
  1556. return;
  1557. }
  1558. this.callbackMap[scriptSrc] = [scriptCallbacks];
  1559. this.actualScriptLoader.load(scriptSrc, function () { return _this.triggerCallback(scriptSrc); }, function (err) { return _this.triggerErrorback(scriptSrc, err); }, recorder);
  1560. };
  1561. OnlyOnceScriptLoader.prototype.triggerCallback = function (scriptSrc) {
  1562. var scriptCallbacks = this.callbackMap[scriptSrc];
  1563. delete this.callbackMap[scriptSrc];
  1564. for (var i = 0; i < scriptCallbacks.length; i++) {
  1565. scriptCallbacks[i].callback();
  1566. }
  1567. };
  1568. OnlyOnceScriptLoader.prototype.triggerErrorback = function (scriptSrc, err) {
  1569. var scriptCallbacks = this.callbackMap[scriptSrc];
  1570. delete this.callbackMap[scriptSrc];
  1571. for (var i = 0; i < scriptCallbacks.length; i++) {
  1572. scriptCallbacks[i].errorback(err);
  1573. }
  1574. };
  1575. return OnlyOnceScriptLoader;
  1576. }());
  1577. var BrowserScriptLoader = (function () {
  1578. function BrowserScriptLoader() {
  1579. }
  1580. /**
  1581. * Attach load / error listeners to a script element and remove them when either one has fired.
  1582. * Implemented for browssers supporting 'onreadystatechange' events, such as IE8 or IE9
  1583. */
  1584. BrowserScriptLoader.prototype.attachListenersV1 = function (script, callback, errorback) {
  1585. var unbind = function () {
  1586. script.detachEvent('onreadystatechange', loadEventListener);
  1587. if (script.addEventListener) {
  1588. script.removeEventListener('error', errorEventListener);
  1589. }
  1590. };
  1591. var loadEventListener = function (e) {
  1592. if (script.readyState === 'loaded' || script.readyState === 'complete') {
  1593. unbind();
  1594. callback();
  1595. }
  1596. };
  1597. var errorEventListener = function (e) {
  1598. unbind();
  1599. errorback(e);
  1600. };
  1601. script.attachEvent('onreadystatechange', loadEventListener);
  1602. if (script.addEventListener) {
  1603. script.addEventListener('error', errorEventListener);
  1604. }
  1605. };
  1606. /**
  1607. * Attach load / error listeners to a script element and remove them when either one has fired.
  1608. * Implemented for browssers supporting HTML5 standard 'load' and 'error' events.
  1609. */
  1610. BrowserScriptLoader.prototype.attachListenersV2 = function (script, callback, errorback) {
  1611. var unbind = function () {
  1612. script.removeEventListener('load', loadEventListener);
  1613. script.removeEventListener('error', errorEventListener);
  1614. };
  1615. var loadEventListener = function (e) {
  1616. unbind();
  1617. callback();
  1618. };
  1619. var errorEventListener = function (e) {
  1620. unbind();
  1621. errorback(e);
  1622. };
  1623. script.addEventListener('load', loadEventListener);
  1624. script.addEventListener('error', errorEventListener);
  1625. };
  1626. BrowserScriptLoader.prototype.setModuleManager = function (moduleManager) {
  1627. /* Intentional empty */
  1628. };
  1629. BrowserScriptLoader.prototype.load = function (scriptSrc, callback, errorback) {
  1630. var script = document.createElement('script');
  1631. script.setAttribute('async', 'async');
  1632. script.setAttribute('type', 'text/javascript');
  1633. if (global.attachEvent) {
  1634. this.attachListenersV1(script, callback, errorback);
  1635. }
  1636. else {
  1637. this.attachListenersV2(script, callback, errorback);
  1638. }
  1639. script.setAttribute('src', scriptSrc);
  1640. document.getElementsByTagName('head')[0].appendChild(script);
  1641. };
  1642. return BrowserScriptLoader;
  1643. }());
  1644. var WorkerScriptLoader = (function () {
  1645. function WorkerScriptLoader() {
  1646. this.loadCalls = [];
  1647. this.loadTimeout = -1;
  1648. }
  1649. WorkerScriptLoader.prototype.setModuleManager = function (moduleManager) {
  1650. /* Intentional empty */
  1651. };
  1652. WorkerScriptLoader.prototype.load = function (scriptSrc, callback, errorback) {
  1653. var _this = this;
  1654. this.loadCalls.push({
  1655. scriptSrc: scriptSrc,
  1656. callback: callback,
  1657. errorback: errorback
  1658. });
  1659. if (navigator.userAgent.indexOf('Firefox') >= 0) {
  1660. // Firefox fails installing the timer every now and then :(
  1661. this._load();
  1662. }
  1663. else {
  1664. if (this.loadTimeout === -1) {
  1665. this.loadTimeout = setTimeout(function () {
  1666. _this.loadTimeout = -1;
  1667. _this._load();
  1668. }, 0);
  1669. }
  1670. }
  1671. };
  1672. WorkerScriptLoader.prototype._load = function () {
  1673. var loadCalls = this.loadCalls;
  1674. this.loadCalls = [];
  1675. var i, len = loadCalls.length, scripts = [];
  1676. for (i = 0; i < len; i++) {
  1677. scripts.push(loadCalls[i].scriptSrc);
  1678. }
  1679. var errorOccured = false;
  1680. try {
  1681. importScripts.apply(null, scripts);
  1682. }
  1683. catch (e) {
  1684. errorOccured = true;
  1685. for (i = 0; i < len; i++) {
  1686. loadCalls[i].errorback(e);
  1687. }
  1688. }
  1689. if (!errorOccured) {
  1690. for (i = 0; i < len; i++) {
  1691. loadCalls[i].callback();
  1692. }
  1693. }
  1694. };
  1695. return WorkerScriptLoader;
  1696. }());
  1697. var NodeScriptLoader = (function () {
  1698. function NodeScriptLoader() {
  1699. this._initialized = false;
  1700. }
  1701. NodeScriptLoader.prototype.setModuleManager = function (moduleManager) {
  1702. this._moduleManager = moduleManager;
  1703. };
  1704. NodeScriptLoader.prototype._init = function (nodeRequire) {
  1705. if (this._initialized) {
  1706. return;
  1707. }
  1708. this._initialized = true;
  1709. this._fs = nodeRequire('fs');
  1710. this._vm = nodeRequire('vm');
  1711. this._path = nodeRequire('path');
  1712. };
  1713. NodeScriptLoader.prototype.load = function (scriptSrc, callback, errorback, recorder) {
  1714. var _this = this;
  1715. var opts = this._moduleManager.getConfigurationOptions();
  1716. var nodeRequire = (opts.nodeRequire || global.nodeRequire);
  1717. var nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; });
  1718. this._init(nodeRequire);
  1719. if (/^node\|/.test(scriptSrc)) {
  1720. var pieces = scriptSrc.split('|');
  1721. var moduleExports = null;
  1722. try {
  1723. recorder.record(LoaderEventType.NodeBeginNativeRequire, pieces[2]);
  1724. moduleExports = nodeRequire(pieces[2]);
  1725. }
  1726. catch (err) {
  1727. recorder.record(LoaderEventType.NodeEndNativeRequire, pieces[2]);
  1728. errorback(err);
  1729. return;
  1730. }
  1731. recorder.record(LoaderEventType.NodeEndNativeRequire, pieces[2]);
  1732. this._moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports; });
  1733. callback();
  1734. }
  1735. else {
  1736. scriptSrc = Utilities.fileUriToFilePath(scriptSrc);
  1737. this._fs.readFile(scriptSrc, { encoding: 'utf8' }, function (err, data) {
  1738. if (err) {
  1739. errorback(err);
  1740. return;
  1741. }
  1742. recorder.record(LoaderEventType.NodeBeginEvaluatingScript, scriptSrc);
  1743. var vmScriptSrc = _this._path.normalize(scriptSrc);
  1744. // Make the script src friendly towards electron
  1745. if (isElectronRenderer) {
  1746. var driveLetterMatch = vmScriptSrc.match(/^([a-z])\:(.*)/);
  1747. if (driveLetterMatch) {
  1748. vmScriptSrc = driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2];
  1749. }
  1750. vmScriptSrc = 'file:///' + vmScriptSrc.replace(/\\/g, '/');
  1751. }
  1752. var contents, prefix = '(function (require, define, __filename, __dirname) { ', suffix = '\n});';
  1753. if (data.charCodeAt(0) === NodeScriptLoader._BOM) {
  1754. contents = prefix + data.substring(1) + suffix;
  1755. }
  1756. else {
  1757. contents = prefix + data + suffix;
  1758. }
  1759. contents = nodeInstrumenter(contents, vmScriptSrc);
  1760. var r;
  1761. if (/^v0\.12/.test(process.version)) {
  1762. r = _this._vm.runInThisContext(contents, { filename: vmScriptSrc });
  1763. }
  1764. else {
  1765. r = _this._vm.runInThisContext(contents, vmScriptSrc);
  1766. }
  1767. r.call(global, RequireFunc, DefineFunc, vmScriptSrc, _this._path.dirname(scriptSrc));
  1768. recorder.record(LoaderEventType.NodeEndEvaluatingScript, scriptSrc);
  1769. callback();
  1770. });
  1771. }
  1772. };
  1773. NodeScriptLoader._BOM = 0xFEFF;
  1774. return NodeScriptLoader;
  1775. }());
  1776. // ------------------------------------------------------------------------
  1777. // ------------------------------------------------------------------------
  1778. // ------------------------------------------------------------------------
  1779. // define
  1780. var DefineFunc = (function () {
  1781. function DefineFunc(id, dependencies, callback) {
  1782. if (typeof id !== 'string') {
  1783. callback = dependencies;
  1784. dependencies = id;
  1785. id = null;
  1786. }
  1787. if (typeof dependencies !== 'object' || !Utilities.isArray(dependencies)) {
  1788. callback = dependencies;
  1789. dependencies = null;
  1790. }
  1791. if (!dependencies) {
  1792. dependencies = ['require', 'exports', 'module'];
  1793. }
  1794. if (id) {
  1795. moduleManager.enqueueDefineModule(id, dependencies, callback);
  1796. }
  1797. else {
  1798. moduleManager.enqueueDefineAnonymousModule(dependencies, callback);
  1799. }
  1800. }
  1801. DefineFunc.amd = {
  1802. jQuery: true
  1803. };
  1804. return DefineFunc;
  1805. }());
  1806. var RequireFunc = (function () {
  1807. function RequireFunc() {
  1808. if (arguments.length === 1) {
  1809. if ((arguments[0] instanceof Object) && !Utilities.isArray(arguments[0])) {
  1810. RequireFunc.config(arguments[0]);
  1811. return;
  1812. }
  1813. if (typeof arguments[0] === 'string') {
  1814. return moduleManager.synchronousRequire(arguments[0]);
  1815. }
  1816. }
  1817. if (arguments.length === 2 || arguments.length === 3) {
  1818. if (Utilities.isArray(arguments[0])) {
  1819. moduleManager.defineModule(Utilities.generateAnonymousModule(), arguments[0], arguments[1], arguments[2], null);
  1820. return;
  1821. }
  1822. }
  1823. throw new Error('Unrecognized require call');
  1824. }
  1825. RequireFunc.config = function (params, shouldOverwrite) {
  1826. if (shouldOverwrite === void 0) { shouldOverwrite = false; }
  1827. moduleManager.configure(params, shouldOverwrite);
  1828. };
  1829. RequireFunc.getConfig = function () {
  1830. return moduleManager.getConfigurationOptions();
  1831. };
  1832. /**
  1833. * Non standard extension to reset completely the loader state. This is used for running amdjs tests
  1834. */
  1835. RequireFunc.reset = function () {
  1836. moduleManager = new ModuleManager(scriptLoader);
  1837. scriptLoader.setModuleManager(moduleManager);
  1838. };
  1839. /**
  1840. * Non standard extension to fetch loader state for building purposes.
  1841. */
  1842. RequireFunc.getBuildInfo = function () {
  1843. return moduleManager.getBuildInfo();
  1844. };
  1845. /**
  1846. * Non standard extension to fetch loader events
  1847. */
  1848. RequireFunc.getStats = function () {
  1849. return moduleManager.getLoaderEvents();
  1850. };
  1851. return RequireFunc;
  1852. }());
  1853. var global = _amdLoaderGlobal, hasPerformanceNow = (global.performance && typeof global.performance.now === 'function'), isWebWorker, isElectronRenderer, isElectronMain, isNode, scriptLoader, moduleManager, loaderAvailableTimestamp;
  1854. function initVars() {
  1855. isWebWorker = (typeof global.importScripts === 'function');
  1856. isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions['electron'] !== 'undefined' && process.type === 'renderer');
  1857. isElectronMain = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions['electron'] !== 'undefined' && process.type === 'browser');
  1858. isNode = (typeof module !== 'undefined' && !!module.exports);
  1859. if (isWebWorker) {
  1860. scriptLoader = new OnlyOnceScriptLoader(new WorkerScriptLoader());
  1861. }
  1862. else if (isNode) {
  1863. scriptLoader = new OnlyOnceScriptLoader(new NodeScriptLoader());
  1864. }
  1865. else {
  1866. scriptLoader = new OnlyOnceScriptLoader(new BrowserScriptLoader());
  1867. }
  1868. moduleManager = new ModuleManager(scriptLoader);
  1869. scriptLoader.setModuleManager(moduleManager);
  1870. }
  1871. function initConsole() {
  1872. // Define used console.* functions, in order to not fail in environments where they are not available
  1873. if (!isNode) {
  1874. if (!global.console) {
  1875. global.console = {};
  1876. }
  1877. if (!global.console.log) {
  1878. global.console.log = function () { };
  1879. }
  1880. if (!global.console.warn) {
  1881. global.console.warn = global.console.log;
  1882. }
  1883. if (!global.console.error) {
  1884. global.console.error = global.console.log;
  1885. }
  1886. }
  1887. }
  1888. function initMainScript() {
  1889. if (!isWebWorker && !isNode) {
  1890. window.onload = function () {
  1891. var i, len, main, scripts = document.getElementsByTagName('script');
  1892. // Look through all the scripts for the data-main attribute
  1893. for (i = 0, len = scripts.length; i < len; i++) {
  1894. main = scripts[i].getAttribute('data-main');
  1895. if (main) {
  1896. break;
  1897. }
  1898. }
  1899. // Load the main script
  1900. if (main) {
  1901. moduleManager.defineModule(Utilities.generateAnonymousModule(), [main], null, null, null, new ModuleIdResolver(new Configuration(), ''));
  1902. }
  1903. };
  1904. }
  1905. }
  1906. function init() {
  1907. initVars();
  1908. initConsole();
  1909. initMainScript();
  1910. if (isNode) {
  1911. var _nodeRequire = (global.require || require);
  1912. var nodeRequire = function (what) {
  1913. moduleManager.getRecorder().record(LoaderEventType.NodeBeginNativeRequire, what);
  1914. var r = _nodeRequire(what);
  1915. moduleManager.getRecorder().record(LoaderEventType.NodeEndNativeRequire, what);
  1916. return r;
  1917. };
  1918. global.nodeRequire = nodeRequire;
  1919. RequireFunc.nodeRequire = nodeRequire;
  1920. }
  1921. if (isNode && !isElectronRenderer) {
  1922. module.exports = RequireFunc;
  1923. // These two defs are fore the local closure defined in node in the case that the loader is concatenated
  1924. define = function () {
  1925. DefineFunc.apply(null, arguments);
  1926. };
  1927. require = RequireFunc;
  1928. }
  1929. else {
  1930. // The global variable require can configure the loader
  1931. if (typeof global.require !== 'undefined' && typeof global.require !== 'function') {
  1932. RequireFunc.config(global.require);
  1933. }
  1934. if (!isElectronRenderer) {
  1935. global.define = DefineFunc;
  1936. }
  1937. else {
  1938. define = function () {
  1939. DefineFunc.apply(null, arguments);
  1940. };
  1941. }
  1942. global.require = RequireFunc;
  1943. global.require.__$__nodeRequire = nodeRequire;
  1944. }
  1945. }
  1946. if (typeof global.define !== 'function' || !global.define.amd) {
  1947. init();
  1948. loaderAvailableTimestamp = getHighPerformanceTimestamp();
  1949. }
  1950. })(AMDLoader || (AMDLoader = {}));
  1951. /*---------------------------------------------------------------------------------------------
  1952. * Copyright (c) Microsoft Corporation. All rights reserved.
  1953. * Licensed under the MIT License. See License.txt in the project root for license information.
  1954. *--------------------------------------------------------------------------------------------*/
  1955. /*---------------------------------------------------------------------------------------------
  1956. *---------------------------------------------------------------------------------------------
  1957. *---------------------------------------------------------------------------------------------
  1958. *---------------------------------------------------------------------------------------------
  1959. *---------------------------------------------------------------------------------------------
  1960. * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/
  1961. *---------------------------------------------------------------------------------------------
  1962. *---------------------------------------------------------------------------------------------
  1963. *---------------------------------------------------------------------------------------------
  1964. *---------------------------------------------------------------------------------------------
  1965. *--------------------------------------------------------------------------------------------*/
  1966. 'use strict';
  1967. var __extends = (this && this.__extends) || function (d, b) {
  1968. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1969. function __() { this.constructor = d; }
  1970. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1971. };
  1972. var _cssPluginGlobal = this;
  1973. var CSSLoaderPlugin;
  1974. (function (CSSLoaderPlugin) {
  1975. var global = _cssPluginGlobal;
  1976. /**
  1977. * Known issue:
  1978. * - In IE there is no way to know if the CSS file loaded successfully or not.
  1979. */
  1980. var BrowserCSSLoader = (function () {
  1981. function BrowserCSSLoader() {
  1982. this._pendingLoads = 0;
  1983. }
  1984. BrowserCSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) {
  1985. var unbind = function () {
  1986. linkNode.removeEventListener('load', loadEventListener);
  1987. linkNode.removeEventListener('error', errorEventListener);
  1988. };
  1989. var loadEventListener = function (e) {
  1990. unbind();
  1991. callback();
  1992. };
  1993. var errorEventListener = function (e) {
  1994. unbind();
  1995. errorback(e);
  1996. };
  1997. linkNode.addEventListener('load', loadEventListener);
  1998. linkNode.addEventListener('error', errorEventListener);
  1999. };
  2000. BrowserCSSLoader.prototype._onLoad = function (name, callback) {
  2001. this._pendingLoads--;
  2002. callback();
  2003. };
  2004. BrowserCSSLoader.prototype._onLoadError = function (name, errorback, err) {
  2005. this._pendingLoads--;
  2006. errorback(err);
  2007. };
  2008. BrowserCSSLoader.prototype._insertLinkNode = function (linkNode) {
  2009. this._pendingLoads++;
  2010. var head = document.head || document.getElementsByTagName('head')[0];
  2011. var other = head.getElementsByTagName('link') || document.head.getElementsByTagName('script');
  2012. if (other.length > 0) {
  2013. head.insertBefore(linkNode, other[other.length - 1]);
  2014. }
  2015. else {
  2016. head.appendChild(linkNode);
  2017. }
  2018. };
  2019. BrowserCSSLoader.prototype.createLinkTag = function (name, cssUrl, externalCallback, externalErrorback) {
  2020. var _this = this;
  2021. var linkNode = document.createElement('link');
  2022. linkNode.setAttribute('rel', 'stylesheet');
  2023. linkNode.setAttribute('type', 'text/css');
  2024. linkNode.setAttribute('data-name', name);
  2025. var callback = function () { return _this._onLoad(name, externalCallback); };
  2026. var errorback = function (err) { return _this._onLoadError(name, externalErrorback, err); };
  2027. this.attachListeners(name, linkNode, callback, errorback);
  2028. linkNode.setAttribute('href', cssUrl);
  2029. return linkNode;
  2030. };
  2031. BrowserCSSLoader.prototype._linkTagExists = function (name, cssUrl) {
  2032. var i, len, nameAttr, hrefAttr, links = document.getElementsByTagName('link');
  2033. for (i = 0, len = links.length; i < len; i++) {
  2034. nameAttr = links[i].getAttribute('data-name');
  2035. hrefAttr = links[i].getAttribute('href');
  2036. if (nameAttr === name || hrefAttr === cssUrl) {
  2037. return true;
  2038. }
  2039. }
  2040. return false;
  2041. };
  2042. BrowserCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) {
  2043. if (this._linkTagExists(name, cssUrl)) {
  2044. externalCallback();
  2045. return;
  2046. }
  2047. var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback);
  2048. this._insertLinkNode(linkNode);
  2049. };
  2050. return BrowserCSSLoader;
  2051. }());
  2052. /**
  2053. * Prior to IE10, IE could not go above 31 stylesheets in a page
  2054. * http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/internet-explorer-stylesheet-rule-selector-import-sheet-limit-maximum.aspx
  2055. *
  2056. * The general strategy here is to not write more than 31 link nodes to the page at the same time
  2057. * When stylesheets get loaded, they will get merged one into another to free up
  2058. * some positions for new link nodes.
  2059. */
  2060. var IE9CSSLoader = (function (_super) {
  2061. __extends(IE9CSSLoader, _super);
  2062. function IE9CSSLoader() {
  2063. _super.call(this);
  2064. this._blockedLoads = [];
  2065. this._mergeStyleSheetsTimeout = -1;
  2066. }
  2067. IE9CSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) {
  2068. if (this._linkTagExists(name, cssUrl)) {
  2069. externalCallback();
  2070. return;
  2071. }
  2072. var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback);
  2073. if (this._styleSheetCount() < 31) {
  2074. this._insertLinkNode(linkNode);
  2075. }
  2076. else {
  2077. this._blockedLoads.push(linkNode);
  2078. this._handleBlocked();
  2079. }
  2080. };
  2081. IE9CSSLoader.prototype._styleSheetCount = function () {
  2082. var linkCount = document.getElementsByTagName('link').length;
  2083. var styleCount = document.getElementsByTagName('style').length;
  2084. return linkCount + styleCount;
  2085. };
  2086. IE9CSSLoader.prototype._onLoad = function (name, callback) {
  2087. _super.prototype._onLoad.call(this, name, callback);
  2088. this._handleBlocked();
  2089. };
  2090. IE9CSSLoader.prototype._onLoadError = function (name, errorback, err) {
  2091. _super.prototype._onLoadError.call(this, name, errorback, err);
  2092. this._handleBlocked();
  2093. };
  2094. IE9CSSLoader.prototype._handleBlocked = function () {
  2095. var _this = this;
  2096. var blockedLoadsCount = this._blockedLoads.length;
  2097. if (blockedLoadsCount > 0 && this._mergeStyleSheetsTimeout === -1) {
  2098. this._mergeStyleSheetsTimeout = window.setTimeout(function () { return _this._mergeStyleSheets(); }, 0);
  2099. }
  2100. };
  2101. IE9CSSLoader.prototype._mergeStyleSheet = function (dstPath, dst, srcPath, src) {
  2102. for (var i = src.rules.length - 1; i >= 0; i--) {
  2103. dst.insertRule(Utilities.rewriteUrls(srcPath, dstPath, src.rules[i].cssText), 0);
  2104. }
  2105. };
  2106. IE9CSSLoader.prototype._asIE9HTMLLinkElement = function (linkElement) {
  2107. return linkElement;
  2108. };
  2109. IE9CSSLoader.prototype._mergeStyleSheets = function () {
  2110. this._mergeStyleSheetsTimeout = -1;
  2111. var blockedLoadsCount = this._blockedLoads.length;
  2112. var i, linkDomNodes = document.getElementsByTagName('link');
  2113. var linkDomNodesCount = linkDomNodes.length;
  2114. var mergeCandidates = [];
  2115. for (i = 0; i < linkDomNodesCount; i++) {
  2116. if (linkDomNodes[i].readyState === 'loaded' || linkDomNodes[i].readyState === 'complete') {
  2117. mergeCandidates.push({
  2118. linkNode: linkDomNodes[i],
  2119. rulesLength: this._asIE9HTMLLinkElement(linkDomNodes[i]).styleSheet.rules.length
  2120. });
  2121. }
  2122. }
  2123. var mergeCandidatesCount = mergeCandidates.length;
  2124. // Just a little legend here :)
  2125. // - linkDomNodesCount: total number of link nodes in the DOM (this should be kept <= 31)
  2126. // - mergeCandidatesCount: loaded (finished) link nodes in the DOM (only these can be merged)
  2127. // - blockedLoadsCount: remaining number of load requests that did not fit in before (because of the <= 31 constraint)
  2128. // Now comes the heuristic part, we don't want to do too much work with the merging of styles,
  2129. // but we do need to merge stylesheets to free up loading slots.
  2130. var mergeCount = Math.min(Math.floor(mergeCandidatesCount / 2), blockedLoadsCount);
  2131. // Sort the merge candidates descending (least rules last)
  2132. mergeCandidates.sort(function (a, b) {
  2133. return b.rulesLength - a.rulesLength;
  2134. });
  2135. var srcIndex, dstIndex;
  2136. for (i = 0; i < mergeCount; i++) {
  2137. srcIndex = mergeCandidates.length - 1 - i;
  2138. dstIndex = i % (mergeCandidates.length - mergeCount);
  2139. // Merge rules of src into dst
  2140. this._mergeStyleSheet(mergeCandidates[dstIndex].linkNode.href, this._asIE9HTMLLinkElement(mergeCandidates[dstIndex].linkNode).styleSheet, mergeCandidates[srcIndex].linkNode.href, this._asIE9HTMLLinkElement(mergeCandidates[srcIndex].linkNode).styleSheet);
  2141. // Remove dom node of src
  2142. mergeCandidates[srcIndex].linkNode.parentNode.removeChild(mergeCandidates[srcIndex].linkNode);
  2143. linkDomNodesCount--;
  2144. }
  2145. var styleSheetCount = this._styleSheetCount();
  2146. while (styleSheetCount < 31 && this._blockedLoads.length > 0) {
  2147. this._insertLinkNode(this._blockedLoads.shift());
  2148. styleSheetCount++;
  2149. }
  2150. };
  2151. return IE9CSSLoader;
  2152. }(BrowserCSSLoader));
  2153. var IE8CSSLoader = (function (_super) {
  2154. __extends(IE8CSSLoader, _super);
  2155. function IE8CSSLoader() {
  2156. _super.call(this);
  2157. }
  2158. IE8CSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) {
  2159. linkNode.onload = function () {
  2160. linkNode.onload = null;
  2161. callback();
  2162. };
  2163. };
  2164. return IE8CSSLoader;
  2165. }(IE9CSSLoader));
  2166. var NodeCSSLoader = (function () {
  2167. function NodeCSSLoader() {
  2168. this.fs = require.nodeRequire('fs');
  2169. }
  2170. NodeCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) {
  2171. var contents = this.fs.readFileSync(cssUrl, 'utf8');
  2172. // Remove BOM
  2173. if (contents.charCodeAt(0) === NodeCSSLoader.BOM_CHAR_CODE) {
  2174. contents = contents.substring(1);
  2175. }
  2176. externalCallback(contents);
  2177. };
  2178. NodeCSSLoader.BOM_CHAR_CODE = 65279;
  2179. return NodeCSSLoader;
  2180. }());
  2181. // ------------------------------ Finally, the plugin
  2182. var CSSPlugin = (function () {
  2183. function CSSPlugin(cssLoader) {
  2184. this.cssLoader = cssLoader;
  2185. }
  2186. CSSPlugin.prototype.load = function (name, req, load, config) {
  2187. config = config || {};
  2188. var myConfig = config['vs/css'] || {};
  2189. if (myConfig.inlineResources) {
  2190. global.inlineResources = true;
  2191. }
  2192. var cssUrl = req.toUrl(name + '.css');
  2193. this.cssLoader.load(name, cssUrl, function (contents) {
  2194. // Contents has the CSS file contents if we are in a build
  2195. if (config.isBuild) {
  2196. CSSPlugin.BUILD_MAP[name] = contents;
  2197. CSSPlugin.BUILD_PATH_MAP[name] = cssUrl;
  2198. }
  2199. load({});
  2200. }, function (err) {
  2201. if (typeof load.error === 'function') {
  2202. load.error('Could not find ' + cssUrl + ' or it was empty');
  2203. }
  2204. });
  2205. };
  2206. CSSPlugin.prototype.write = function (pluginName, moduleName, write) {
  2207. // getEntryPoint is a Monaco extension to r.js
  2208. var entryPoint = write.getEntryPoint();
  2209. // r.js destroys the context of this plugin between calling 'write' and 'writeFile'
  2210. // so the only option at this point is to leak the data to a global
  2211. global.cssPluginEntryPoints = global.cssPluginEntryPoints || {};
  2212. global.cssPluginEntryPoints[entryPoint] = global.cssPluginEntryPoints[entryPoint] || [];
  2213. global.cssPluginEntryPoints[entryPoint].push({
  2214. moduleName: moduleName,
  2215. contents: CSSPlugin.BUILD_MAP[moduleName],
  2216. fsPath: CSSPlugin.BUILD_PATH_MAP[moduleName],
  2217. });
  2218. write.asModule(pluginName + '!' + moduleName, 'define([\'vs/css!' + entryPoint + '\'], {});');
  2219. };
  2220. CSSPlugin.prototype.writeFile = function (pluginName, moduleName, req, write, config) {
  2221. if (global.cssPluginEntryPoints && global.cssPluginEntryPoints.hasOwnProperty(moduleName)) {
  2222. var fileName = req.toUrl(moduleName + '.css');
  2223. var contents = [
  2224. '/*---------------------------------------------------------',
  2225. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  2226. ' *--------------------------------------------------------*/'
  2227. ], entries = global.cssPluginEntryPoints[moduleName];
  2228. for (var i = 0; i < entries.length; i++) {
  2229. if (global.inlineResources) {
  2230. contents.push(Utilities.rewriteOrInlineUrls(entries[i].fsPath, entries[i].moduleName, moduleName, entries[i].contents));
  2231. }
  2232. else {
  2233. contents.push(Utilities.rewriteUrls(entries[i].moduleName, moduleName, entries[i].contents));
  2234. }
  2235. }
  2236. write(fileName, contents.join('\r\n'));
  2237. }
  2238. };
  2239. CSSPlugin.prototype.getInlinedResources = function () {
  2240. return global.cssInlinedResources || [];
  2241. };
  2242. CSSPlugin.BUILD_MAP = {};
  2243. CSSPlugin.BUILD_PATH_MAP = {};
  2244. return CSSPlugin;
  2245. }());
  2246. CSSLoaderPlugin.CSSPlugin = CSSPlugin;
  2247. var Utilities = (function () {
  2248. function Utilities() {
  2249. }
  2250. Utilities.startsWith = function (haystack, needle) {
  2251. return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
  2252. };
  2253. /**
  2254. * Find the path of a file.
  2255. */
  2256. Utilities.pathOf = function (filename) {
  2257. var lastSlash = filename.lastIndexOf('/');
  2258. if (lastSlash !== -1) {
  2259. return filename.substr(0, lastSlash + 1);
  2260. }
  2261. else {
  2262. return '';
  2263. }
  2264. };
  2265. /**
  2266. * A conceptual a + b for paths.
  2267. * Takes into account if `a` contains a protocol.
  2268. * Also normalizes the result: e.g.: a/b/ + ../c => a/c
  2269. */
  2270. Utilities.joinPaths = function (a, b) {
  2271. function findSlashIndexAfterPrefix(haystack, prefix) {
  2272. if (Utilities.startsWith(haystack, prefix)) {
  2273. return Math.max(prefix.length, haystack.indexOf('/', prefix.length));
  2274. }
  2275. return 0;
  2276. }
  2277. var aPathStartIndex = 0;
  2278. aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, '//');
  2279. aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'http://');
  2280. aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'https://');
  2281. function pushPiece(pieces, piece) {
  2282. if (piece === './') {
  2283. // Ignore
  2284. return;
  2285. }
  2286. if (piece === '../') {
  2287. var prevPiece = (pieces.length > 0 ? pieces[pieces.length - 1] : null);
  2288. if (prevPiece && prevPiece === '/') {
  2289. // Ignore
  2290. return;
  2291. }
  2292. if (prevPiece && prevPiece !== '../') {
  2293. // Pop
  2294. pieces.pop();
  2295. return;
  2296. }
  2297. }
  2298. // Push
  2299. pieces.push(piece);
  2300. }
  2301. function push(pieces, path) {
  2302. while (path.length > 0) {
  2303. var slashIndex = path.indexOf('/');
  2304. var piece = (slashIndex >= 0 ? path.substring(0, slashIndex + 1) : path);
  2305. path = (slashIndex >= 0 ? path.substring(slashIndex + 1) : '');
  2306. pushPiece(pieces, piece);
  2307. }
  2308. }
  2309. var pieces = [];
  2310. push(pieces, a.substr(aPathStartIndex));
  2311. if (b.length > 0 && b.charAt(0) === '/') {
  2312. pieces = [];
  2313. }
  2314. push(pieces, b);
  2315. return a.substring(0, aPathStartIndex) + pieces.join('');
  2316. };
  2317. Utilities.commonPrefix = function (str1, str2) {
  2318. var len = Math.min(str1.length, str2.length);
  2319. for (var i = 0; i < len; i++) {
  2320. if (str1.charCodeAt(i) !== str2.charCodeAt(i)) {
  2321. break;
  2322. }
  2323. }
  2324. return str1.substring(0, i);
  2325. };
  2326. Utilities.commonFolderPrefix = function (fromPath, toPath) {
  2327. var prefix = Utilities.commonPrefix(fromPath, toPath);
  2328. var slashIndex = prefix.lastIndexOf('/');
  2329. if (slashIndex === -1) {
  2330. return '';
  2331. }
  2332. return prefix.substring(0, slashIndex + 1);
  2333. };
  2334. Utilities.relativePath = function (fromPath, toPath) {
  2335. if (Utilities.startsWith(toPath, '/') || Utilities.startsWith(toPath, 'http://') || Utilities.startsWith(toPath, 'https://')) {
  2336. return toPath;
  2337. }
  2338. // Ignore common folder prefix
  2339. var prefix = Utilities.commonFolderPrefix(fromPath, toPath);
  2340. fromPath = fromPath.substr(prefix.length);
  2341. toPath = toPath.substr(prefix.length);
  2342. var upCount = fromPath.split('/').length;
  2343. var result = '';
  2344. for (var i = 1; i < upCount; i++) {
  2345. result += '../';
  2346. }
  2347. return result + toPath;
  2348. };
  2349. Utilities._replaceURL = function (contents, replacer) {
  2350. // Use ")" as the terminator as quotes are oftentimes not used at all
  2351. return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, function (_) {
  2352. var matches = [];
  2353. for (var _i = 1; _i < arguments.length; _i++) {
  2354. matches[_i - 1] = arguments[_i];
  2355. }
  2356. var url = matches[0];
  2357. // Eliminate starting quotes (the initial whitespace is not captured)
  2358. if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
  2359. url = url.substring(1);
  2360. }
  2361. // The ending whitespace is captured
  2362. while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
  2363. url = url.substring(0, url.length - 1);
  2364. }
  2365. // Eliminate ending quotes
  2366. if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
  2367. url = url.substring(0, url.length - 1);
  2368. }
  2369. if (!Utilities.startsWith(url, 'data:') && !Utilities.startsWith(url, 'http://') && !Utilities.startsWith(url, 'https://')) {
  2370. url = replacer(url);
  2371. }
  2372. return 'url(' + url + ')';
  2373. });
  2374. };
  2375. Utilities.rewriteUrls = function (originalFile, newFile, contents) {
  2376. return this._replaceURL(contents, function (url) {
  2377. var absoluteUrl = Utilities.joinPaths(Utilities.pathOf(originalFile), url);
  2378. return Utilities.relativePath(newFile, absoluteUrl);
  2379. });
  2380. };
  2381. Utilities.rewriteOrInlineUrls = function (originalFileFSPath, originalFile, newFile, contents) {
  2382. var fs = require.nodeRequire('fs');
  2383. var path = require.nodeRequire('path');
  2384. return this._replaceURL(contents, function (url) {
  2385. if (/\.(svg|png)$/.test(url)) {
  2386. var fsPath = path.join(path.dirname(originalFileFSPath), url);
  2387. var fileContents = fs.readFileSync(fsPath);
  2388. if (fileContents.length < 3000) {
  2389. global.cssInlinedResources = global.cssInlinedResources || [];
  2390. var normalizedFSPath = fsPath.replace(/\\/g, '/');
  2391. if (global.cssInlinedResources.indexOf(normalizedFSPath) >= 0) {
  2392. console.warn('CSS INLINING IMAGE AT ' + fsPath + ' MORE THAN ONCE. CONSIDER CONSOLIDATING CSS RULES');
  2393. }
  2394. global.cssInlinedResources.push(normalizedFSPath);
  2395. var MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
  2396. var DATA = ';base64,' + fileContents.toString('base64');
  2397. if (/\.svg$/.test(url)) {
  2398. // .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
  2399. var newText = fileContents.toString()
  2400. .replace(/"/g, '\'')
  2401. .replace(/</g, '%3C')
  2402. .replace(/>/g, '%3E')
  2403. .replace(/&/g, '%26')
  2404. .replace(/#/g, '%23')
  2405. .replace(/\s+/g, ' ');
  2406. var encodedData = ',' + newText;
  2407. if (encodedData.length < DATA.length) {
  2408. DATA = encodedData;
  2409. }
  2410. }
  2411. return '"data:' + MIME + DATA + '"';
  2412. }
  2413. }
  2414. var absoluteUrl = Utilities.joinPaths(Utilities.pathOf(originalFile), url);
  2415. return Utilities.relativePath(newFile, absoluteUrl);
  2416. });
  2417. };
  2418. return Utilities;
  2419. }());
  2420. CSSLoaderPlugin.Utilities = Utilities;
  2421. (function () {
  2422. var cssLoader = null;
  2423. var isElectron = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions['electron'] !== 'undefined');
  2424. if (typeof process !== 'undefined' && process.versions && !!process.versions.node && !isElectron) {
  2425. cssLoader = new NodeCSSLoader();
  2426. }
  2427. else if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('MSIE 9') >= 0) {
  2428. cssLoader = new IE9CSSLoader();
  2429. }
  2430. else if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('MSIE 8') >= 0) {
  2431. cssLoader = new IE8CSSLoader();
  2432. }
  2433. else {
  2434. cssLoader = new BrowserCSSLoader();
  2435. }
  2436. define('vs/css', new CSSPlugin(cssLoader));
  2437. })();
  2438. })(CSSLoaderPlugin || (CSSLoaderPlugin = {}));
  2439. /*---------------------------------------------------------------------------------------------
  2440. * Copyright (c) Microsoft Corporation. All rights reserved.
  2441. * Licensed under the MIT License. See License.txt in the project root for license information.
  2442. *--------------------------------------------------------------------------------------------*/
  2443. /*---------------------------------------------------------------------------------------------
  2444. *---------------------------------------------------------------------------------------------
  2445. *---------------------------------------------------------------------------------------------
  2446. *---------------------------------------------------------------------------------------------
  2447. *---------------------------------------------------------------------------------------------
  2448. * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/
  2449. *---------------------------------------------------------------------------------------------
  2450. *---------------------------------------------------------------------------------------------
  2451. *---------------------------------------------------------------------------------------------
  2452. *---------------------------------------------------------------------------------------------
  2453. *--------------------------------------------------------------------------------------------*/
  2454. 'use strict';
  2455. var _nlsPluginGlobal = this;
  2456. var NLSLoaderPlugin;
  2457. (function (NLSLoaderPlugin) {
  2458. var global = _nlsPluginGlobal;
  2459. var Resources = global.Plugin && global.Plugin.Resources ? global.Plugin.Resources : undefined;
  2460. var DEFAULT_TAG = 'i-default';
  2461. var IS_PSEUDO = (global && global.document && global.document.location && global.document.location.hash.indexOf('pseudo=true') >= 0);
  2462. var slice = Array.prototype.slice;
  2463. function _format(message, args) {
  2464. var result;
  2465. if (args.length === 0) {
  2466. result = message;
  2467. }
  2468. else {
  2469. result = message.replace(/\{(\d+)\}/g, function (match, rest) {
  2470. var index = rest[0];
  2471. return typeof args[index] !== 'undefined' ? args[index] : match;
  2472. });
  2473. }
  2474. if (IS_PSEUDO) {
  2475. // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
  2476. result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
  2477. }
  2478. return result;
  2479. }
  2480. function findLanguageForModule(config, name) {
  2481. var result = config[name];
  2482. if (result)
  2483. return result;
  2484. result = config['*'];
  2485. if (result)
  2486. return result;
  2487. return null;
  2488. }
  2489. function localize(data, message) {
  2490. var args = [];
  2491. for (var _i = 0; _i < (arguments.length - 2); _i++) {
  2492. args[_i] = arguments[_i + 2];
  2493. }
  2494. return _format(message, args);
  2495. }
  2496. function createScopedLocalize(scope) {
  2497. return function (idx, defaultValue) {
  2498. var restArgs = slice.call(arguments, 2);
  2499. return _format(scope[idx], restArgs);
  2500. };
  2501. }
  2502. var NLSPlugin = (function () {
  2503. function NLSPlugin() {
  2504. this.localize = localize;
  2505. }
  2506. NLSPlugin.prototype.setPseudoTranslation = function (value) {
  2507. IS_PSEUDO = value;
  2508. };
  2509. NLSPlugin.prototype.create = function (key, data) {
  2510. return {
  2511. localize: createScopedLocalize(data[key])
  2512. };
  2513. };
  2514. NLSPlugin.prototype.load = function (name, req, load, config) {
  2515. config = config || {};
  2516. if (!name || name.length === 0) {
  2517. load({
  2518. localize: localize
  2519. });
  2520. }
  2521. else {
  2522. var suffix = void 0;
  2523. if (Resources && Resources.getString) {
  2524. suffix = '.nls.keys';
  2525. req([name + suffix], function (keyMap) {
  2526. load({
  2527. localize: function (moduleKey, index) {
  2528. if (!keyMap[moduleKey])
  2529. return 'NLS error: unknown key ' + moduleKey;
  2530. var mk = keyMap[moduleKey].keys;
  2531. if (index >= mk.length)
  2532. return 'NLS error unknow index ' + index;
  2533. var subKey = mk[index];
  2534. var args = [];
  2535. args[0] = moduleKey + '_' + subKey;
  2536. for (var _i = 0; _i < (arguments.length - 2); _i++) {
  2537. args[_i + 1] = arguments[_i + 2];
  2538. }
  2539. return Resources.getString.apply(Resources, args);
  2540. }
  2541. });
  2542. });
  2543. }
  2544. else {
  2545. if (config.isBuild) {
  2546. req([name + '.nls', name + '.nls.keys'], function (messages, keys) {
  2547. NLSPlugin.BUILD_MAP[name] = messages;
  2548. NLSPlugin.BUILD_MAP_KEYS[name] = keys;
  2549. load(messages);
  2550. });
  2551. }
  2552. else {
  2553. var pluginConfig = config['vs/nls'] || {};
  2554. var language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null;
  2555. suffix = '.nls';
  2556. if (language !== null && language !== DEFAULT_TAG) {
  2557. suffix = suffix + '.' + language;
  2558. }
  2559. req([name + suffix], function (messages) {
  2560. if (Array.isArray(messages)) {
  2561. messages.localize = createScopedLocalize(messages);
  2562. }
  2563. else {
  2564. messages.localize = createScopedLocalize(messages[name]);
  2565. }
  2566. load(messages);
  2567. });
  2568. }
  2569. }
  2570. }
  2571. };
  2572. NLSPlugin.prototype._getEntryPointsMap = function () {
  2573. global.nlsPluginEntryPoints = global.nlsPluginEntryPoints || {};
  2574. return global.nlsPluginEntryPoints;
  2575. };
  2576. NLSPlugin.prototype.write = function (pluginName, moduleName, write) {
  2577. // getEntryPoint is a Monaco extension to r.js
  2578. var entryPoint = write.getEntryPoint();
  2579. // r.js destroys the context of this plugin between calling 'write' and 'writeFile'
  2580. // so the only option at this point is to leak the data to a global
  2581. var entryPointsMap = this._getEntryPointsMap();
  2582. entryPointsMap[entryPoint] = entryPointsMap[entryPoint] || [];
  2583. entryPointsMap[entryPoint].push(moduleName);
  2584. if (moduleName !== entryPoint) {
  2585. write.asModule(pluginName + '!' + moduleName, 'define([\'vs/nls\', \'vs/nls!' + entryPoint + '\'], function(nls, data) { return nls.create("' + moduleName + '", data); });');
  2586. }
  2587. };
  2588. NLSPlugin.prototype.writeFile = function (pluginName, moduleName, req, write, config) {
  2589. var entryPointsMap = this._getEntryPointsMap();
  2590. if (entryPointsMap.hasOwnProperty(moduleName)) {
  2591. var fileName = req.toUrl(moduleName + '.nls.js');
  2592. var contents = [
  2593. '/*---------------------------------------------------------',
  2594. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  2595. ' *--------------------------------------------------------*/'
  2596. ], entries = entryPointsMap[moduleName];
  2597. var data = {};
  2598. for (var i = 0; i < entries.length; i++) {
  2599. data[entries[i]] = NLSPlugin.BUILD_MAP[entries[i]];
  2600. }
  2601. contents.push('define("' + moduleName + '.nls", ' + JSON.stringify(data, null, '\t') + ');');
  2602. write(fileName, contents.join('\r\n'));
  2603. }
  2604. };
  2605. NLSPlugin.prototype.finishBuild = function (write) {
  2606. write('nls.metadata.json', JSON.stringify({
  2607. keys: NLSPlugin.BUILD_MAP_KEYS,
  2608. messages: NLSPlugin.BUILD_MAP,
  2609. bundles: this._getEntryPointsMap()
  2610. }, null, '\t'));
  2611. };
  2612. ;
  2613. NLSPlugin.BUILD_MAP = {};
  2614. NLSPlugin.BUILD_MAP_KEYS = {};
  2615. return NLSPlugin;
  2616. }());
  2617. NLSLoaderPlugin.NLSPlugin = NLSPlugin;
  2618. (function () {
  2619. define('vs/nls', new NLSPlugin());
  2620. })();
  2621. })(NLSLoaderPlugin || (NLSLoaderPlugin = {}));
  2622. //# sourceMappingURL=loader.js.map