a zip code crypto-currency system good for red ONLY

Compilation.js 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("async");
  7. const crypto = require("crypto");
  8. const Tapable = require("tapable");
  9. const EntryModuleNotFoundError = require("./EntryModuleNotFoundError");
  10. const ModuleNotFoundError = require("./ModuleNotFoundError");
  11. const ModuleDependencyWarning = require("./ModuleDependencyWarning");
  12. const ModuleDependencyError = require("./ModuleDependencyError");
  13. const Module = require("./Module");
  14. const Chunk = require("./Chunk");
  15. const Entrypoint = require("./Entrypoint");
  16. const MainTemplate = require("./MainTemplate");
  17. const ChunkTemplate = require("./ChunkTemplate");
  18. const HotUpdateChunkTemplate = require("./HotUpdateChunkTemplate");
  19. const ModuleTemplate = require("./ModuleTemplate");
  20. const Dependency = require("./Dependency");
  21. const ChunkRenderError = require("./ChunkRenderError");
  22. const AsyncDependencyToInitialChunkWarning = require("./AsyncDependencyToInitialChunkWarning");
  23. const CachedSource = require("webpack-sources").CachedSource;
  24. const Stats = require("./Stats");
  25. const Semaphore = require("./util/Semaphore");
  26. const Queue = require("./util/Queue");
  27. function byId(a, b) {
  28. if(a.id < b.id) return -1;
  29. if(a.id > b.id) return 1;
  30. return 0;
  31. }
  32. function iterationBlockVariable(variables, fn) {
  33. for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) {
  34. let varDep = variables[indexVariable].dependencies;
  35. for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) {
  36. fn(varDep[indexVDep]);
  37. }
  38. }
  39. }
  40. function iterationOfArrayCallback(arr, fn) {
  41. for(let index = 0; index < arr.length; index++) {
  42. fn(arr[index]);
  43. }
  44. }
  45. class Compilation extends Tapable {
  46. constructor(compiler) {
  47. super();
  48. this.compiler = compiler;
  49. this.resolvers = compiler.resolvers;
  50. this.inputFileSystem = compiler.inputFileSystem;
  51. const options = this.options = compiler.options;
  52. this.outputOptions = options && options.output;
  53. this.bail = options && options.bail;
  54. this.profile = options && options.profile;
  55. this.performance = options && options.performance;
  56. this.mainTemplate = new MainTemplate(this.outputOptions);
  57. this.chunkTemplate = new ChunkTemplate(this.outputOptions);
  58. this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate(this.outputOptions);
  59. this.moduleTemplate = new ModuleTemplate(this.outputOptions);
  60. this.semaphore = new Semaphore(options.parallelism || 100);
  61. this.entries = [];
  62. this.preparedChunks = [];
  63. this.entrypoints = {};
  64. this.chunks = [];
  65. this.namedChunks = {};
  66. this.modules = [];
  67. this._modules = {};
  68. this.cache = null;
  69. this.records = null;
  70. this.nextFreeModuleIndex = undefined;
  71. this.nextFreeModuleIndex2 = undefined;
  72. this.additionalChunkAssets = [];
  73. this.assets = {};
  74. this.errors = [];
  75. this.warnings = [];
  76. this.children = [];
  77. this.dependencyFactories = new Map();
  78. this.dependencyTemplates = new Map();
  79. this.dependencyTemplates.set("hash", "");
  80. this.childrenCounters = {};
  81. }
  82. getStats() {
  83. return new Stats(this);
  84. }
  85. templatesPlugin(name, fn) {
  86. this.mainTemplate.plugin(name, fn);
  87. this.chunkTemplate.plugin(name, fn);
  88. }
  89. addModule(module, cacheGroup) {
  90. const identifier = module.identifier();
  91. if(this._modules[identifier]) {
  92. return false;
  93. }
  94. const cacheName = (cacheGroup || "m") + identifier;
  95. if(this.cache && this.cache[cacheName]) {
  96. const cacheModule = this.cache[cacheName];
  97. let rebuild = true;
  98. if(!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) {
  99. rebuild = cacheModule.needRebuild(this.fileTimestamps, this.contextTimestamps);
  100. }
  101. if(!rebuild) {
  102. cacheModule.disconnect();
  103. this._modules[identifier] = cacheModule;
  104. this.modules.push(cacheModule);
  105. cacheModule.errors.forEach(err => this.errors.push(err), this);
  106. cacheModule.warnings.forEach(err => this.warnings.push(err), this);
  107. return cacheModule;
  108. }
  109. }
  110. module.unbuild();
  111. this._modules[identifier] = module;
  112. if(this.cache) {
  113. this.cache[cacheName] = module;
  114. }
  115. this.modules.push(module);
  116. return true;
  117. }
  118. getModule(module) {
  119. const identifier = module.identifier();
  120. return this._modules[identifier];
  121. }
  122. findModule(identifier) {
  123. return this._modules[identifier];
  124. }
  125. buildModule(module, optional, origin, dependencies, thisCallback) {
  126. this.applyPlugins1("build-module", module);
  127. if(module.building) return module.building.push(thisCallback);
  128. const building = module.building = [thisCallback];
  129. function callback(err) {
  130. module.building = undefined;
  131. building.forEach(cb => cb(err));
  132. }
  133. module.build(this.options, this, this.resolvers.normal, this.inputFileSystem, (error) => {
  134. const errors = module.errors;
  135. for(let indexError = 0; indexError < errors.length; indexError++) {
  136. const err = errors[indexError];
  137. err.origin = origin;
  138. err.dependencies = dependencies;
  139. if(optional)
  140. this.warnings.push(err);
  141. else
  142. this.errors.push(err);
  143. }
  144. const warnings = module.warnings;
  145. for(let indexWarning = 0; indexWarning < warnings.length; indexWarning++) {
  146. const war = warnings[indexWarning];
  147. war.origin = origin;
  148. war.dependencies = dependencies;
  149. this.warnings.push(war);
  150. }
  151. module.dependencies.sort(Dependency.compare);
  152. if(error) {
  153. this.applyPlugins2("failed-module", module, error);
  154. return callback(error);
  155. }
  156. this.applyPlugins1("succeed-module", module);
  157. return callback();
  158. });
  159. }
  160. processModuleDependencies(module, callback) {
  161. const dependencies = [];
  162. function addDependency(dep) {
  163. for(let i = 0; i < dependencies.length; i++) {
  164. if(dep.isEqualResource(dependencies[i][0])) {
  165. return dependencies[i].push(dep);
  166. }
  167. }
  168. dependencies.push([dep]);
  169. }
  170. function addDependenciesBlock(block) {
  171. if(block.dependencies) {
  172. iterationOfArrayCallback(block.dependencies, addDependency);
  173. }
  174. if(block.blocks) {
  175. iterationOfArrayCallback(block.blocks, addDependenciesBlock);
  176. }
  177. if(block.variables) {
  178. iterationBlockVariable(block.variables, addDependency);
  179. }
  180. }
  181. addDependenciesBlock(module);
  182. this.addModuleDependencies(module, dependencies, this.bail, null, true, callback);
  183. }
  184. addModuleDependencies(module, dependencies, bail, cacheGroup, recursive, callback) {
  185. let _this = this;
  186. const start = _this.profile && Date.now();
  187. const factories = [];
  188. for(let i = 0; i < dependencies.length; i++) {
  189. const factory = _this.dependencyFactories.get(dependencies[i][0].constructor);
  190. if(!factory) {
  191. return callback(new Error(`No module factory available for dependency type: ${dependencies[i][0].constructor.name}`));
  192. }
  193. factories[i] = [factory, dependencies[i]];
  194. }
  195. asyncLib.forEach(factories, function iteratorFactory(item, callback) {
  196. const dependencies = item[1];
  197. const errorAndCallback = function errorAndCallback(err) {
  198. err.origin = module;
  199. _this.errors.push(err);
  200. if(bail) {
  201. callback(err);
  202. } else {
  203. callback();
  204. }
  205. };
  206. const warningAndCallback = function warningAndCallback(err) {
  207. err.origin = module;
  208. _this.warnings.push(err);
  209. callback();
  210. };
  211. const semaphore = _this.semaphore;
  212. semaphore.acquire(() => {
  213. if(_this === null) return semaphore.release();
  214. const factory = item[0];
  215. factory.create({
  216. contextInfo: {
  217. issuer: module.nameForCondition && module.nameForCondition(),
  218. compiler: _this.compiler.name
  219. },
  220. context: module.context,
  221. dependencies: dependencies
  222. }, function factoryCallback(err, dependentModule) {
  223. if(_this === null) return semaphore.release();
  224. let afterFactory;
  225. function isOptional() {
  226. return dependencies.filter(d => !d.optional).length === 0;
  227. }
  228. function errorOrWarningAndCallback(err) {
  229. if(isOptional()) {
  230. return warningAndCallback(err);
  231. } else {
  232. return errorAndCallback(err);
  233. }
  234. }
  235. function iterationDependencies(depend) {
  236. for(let index = 0; index < depend.length; index++) {
  237. const dep = depend[index];
  238. dep.module = dependentModule;
  239. dependentModule.addReason(module, dep);
  240. }
  241. }
  242. if(err) {
  243. semaphore.release();
  244. return errorOrWarningAndCallback(new ModuleNotFoundError(module, err, dependencies));
  245. }
  246. if(!dependentModule) {
  247. semaphore.release();
  248. return process.nextTick(callback);
  249. }
  250. if(_this.profile) {
  251. if(!dependentModule.profile) {
  252. dependentModule.profile = {};
  253. }
  254. afterFactory = Date.now();
  255. dependentModule.profile.factory = afterFactory - start;
  256. }
  257. dependentModule.issuer = module;
  258. const newModule = _this.addModule(dependentModule, cacheGroup);
  259. if(!newModule) { // from cache
  260. dependentModule = _this.getModule(dependentModule);
  261. if(dependentModule.optional) {
  262. dependentModule.optional = isOptional();
  263. }
  264. iterationDependencies(dependencies);
  265. if(_this.profile) {
  266. if(!module.profile) {
  267. module.profile = {};
  268. }
  269. const time = Date.now() - start;
  270. if(!module.profile.dependencies || time > module.profile.dependencies) {
  271. module.profile.dependencies = time;
  272. }
  273. }
  274. semaphore.release();
  275. return process.nextTick(callback);
  276. }
  277. if(newModule instanceof Module) {
  278. if(_this.profile) {
  279. newModule.profile = dependentModule.profile;
  280. }
  281. newModule.optional = isOptional();
  282. newModule.issuer = dependentModule.issuer;
  283. dependentModule = newModule;
  284. iterationDependencies(dependencies);
  285. if(_this.profile) {
  286. const afterBuilding = Date.now();
  287. module.profile.building = afterBuilding - afterFactory;
  288. }
  289. semaphore.release();
  290. if(recursive) {
  291. return process.nextTick(_this.processModuleDependencies.bind(_this, dependentModule, callback));
  292. } else {
  293. return process.nextTick(callback);
  294. }
  295. }
  296. dependentModule.optional = isOptional();
  297. iterationDependencies(dependencies);
  298. _this.buildModule(dependentModule, isOptional(), module, dependencies, err => {
  299. if(_this === null) return semaphore.release();
  300. if(err) {
  301. semaphore.release();
  302. return errorOrWarningAndCallback(err);
  303. }
  304. if(_this.profile) {
  305. const afterBuilding = Date.now();
  306. dependentModule.profile.building = afterBuilding - afterFactory;
  307. }
  308. semaphore.release();
  309. if(recursive) {
  310. _this.processModuleDependencies(dependentModule, callback);
  311. } else {
  312. return callback();
  313. }
  314. });
  315. });
  316. });
  317. }, function finalCallbackAddModuleDependencies(err) {
  318. // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
  319. // errors are created inside closures that keep a reference to the Compilation, so errors are
  320. // leaking the Compilation object. Setting _this to null workarounds the following issue in V8.
  321. // https://bugs.chromium.org/p/chromium/issues/detail?id=612191
  322. _this = null;
  323. if(err) {
  324. return callback(err);
  325. }
  326. return process.nextTick(callback);
  327. });
  328. }
  329. _addModuleChain(context, dependency, onModule, callback) {
  330. const start = this.profile && Date.now();
  331. const errorAndCallback = this.bail ? (err) => {
  332. callback(err);
  333. } : (err) => {
  334. err.dependencies = [dependency];
  335. this.errors.push(err);
  336. callback();
  337. };
  338. if(typeof dependency !== "object" || dependency === null || !dependency.constructor) {
  339. throw new Error("Parameter 'dependency' must be a Dependency");
  340. }
  341. const moduleFactory = this.dependencyFactories.get(dependency.constructor);
  342. if(!moduleFactory) {
  343. throw new Error(`No dependency factory available for this dependency type: ${dependency.constructor.name}`);
  344. }
  345. this.semaphore.acquire(() => {
  346. moduleFactory.create({
  347. contextInfo: {
  348. issuer: "",
  349. compiler: this.compiler.name
  350. },
  351. context: context,
  352. dependencies: [dependency]
  353. }, (err, module) => {
  354. if(err) {
  355. this.semaphore.release();
  356. return errorAndCallback(new EntryModuleNotFoundError(err));
  357. }
  358. let afterFactory;
  359. if(this.profile) {
  360. if(!module.profile) {
  361. module.profile = {};
  362. }
  363. afterFactory = Date.now();
  364. module.profile.factory = afterFactory - start;
  365. }
  366. const result = this.addModule(module);
  367. if(!result) {
  368. module = this.getModule(module);
  369. onModule(module);
  370. if(this.profile) {
  371. const afterBuilding = Date.now();
  372. module.profile.building = afterBuilding - afterFactory;
  373. }
  374. this.semaphore.release();
  375. return callback(null, module);
  376. }
  377. if(result instanceof Module) {
  378. if(this.profile) {
  379. result.profile = module.profile;
  380. }
  381. module = result;
  382. onModule(module);
  383. moduleReady.call(this);
  384. return;
  385. }
  386. onModule(module);
  387. this.buildModule(module, false, null, null, (err) => {
  388. if(err) {
  389. this.semaphore.release();
  390. return errorAndCallback(err);
  391. }
  392. if(this.profile) {
  393. const afterBuilding = Date.now();
  394. module.profile.building = afterBuilding - afterFactory;
  395. }
  396. moduleReady.call(this);
  397. });
  398. function moduleReady() {
  399. this.semaphore.release();
  400. this.processModuleDependencies(module, err => {
  401. if(err) {
  402. return callback(err);
  403. }
  404. return callback(null, module);
  405. });
  406. }
  407. });
  408. });
  409. }
  410. addEntry(context, entry, name, callback) {
  411. const slot = {
  412. name: name,
  413. module: null
  414. };
  415. this.preparedChunks.push(slot);
  416. this._addModuleChain(context, entry, (module) => {
  417. entry.module = module;
  418. this.entries.push(module);
  419. module.issuer = null;
  420. }, (err, module) => {
  421. if(err) {
  422. return callback(err);
  423. }
  424. if(module) {
  425. slot.module = module;
  426. } else {
  427. const idx = this.preparedChunks.indexOf(slot);
  428. this.preparedChunks.splice(idx, 1);
  429. }
  430. return callback(null, module);
  431. });
  432. }
  433. prefetch(context, dependency, callback) {
  434. this._addModuleChain(context, dependency, module => {
  435. module.prefetched = true;
  436. module.issuer = null;
  437. }, callback);
  438. }
  439. rebuildModule(module, thisCallback) {
  440. if(module.variables.length || module.blocks.length)
  441. throw new Error("Cannot rebuild a complex module with variables or blocks");
  442. if(module.rebuilding) {
  443. return module.rebuilding.push(thisCallback);
  444. }
  445. const rebuilding = module.rebuilding = [thisCallback];
  446. function callback(err) {
  447. module.rebuilding = undefined;
  448. rebuilding.forEach(cb => cb(err));
  449. }
  450. const deps = module.dependencies.slice();
  451. this.buildModule(module, false, module, null, (err) => {
  452. if(err) return callback(err);
  453. this.processModuleDependencies(module, (err) => {
  454. if(err) return callback(err);
  455. deps.forEach(d => {
  456. if(d.module && d.module.removeReason(module, d)) {
  457. module.forEachChunk(chunk => {
  458. if(!d.module.hasReasonForChunk(chunk)) {
  459. if(d.module.removeChunk(chunk)) {
  460. this.removeChunkFromDependencies(d.module, chunk);
  461. }
  462. }
  463. });
  464. }
  465. });
  466. callback();
  467. });
  468. });
  469. }
  470. finish() {
  471. const modules = this.modules;
  472. this.applyPlugins1("finish-modules", modules);
  473. for(let index = 0; index < modules.length; index++) {
  474. const module = modules[index];
  475. this.reportDependencyErrorsAndWarnings(module, [module]);
  476. }
  477. }
  478. unseal() {
  479. this.applyPlugins0("unseal");
  480. this.chunks.length = 0;
  481. this.namedChunks = {};
  482. this.additionalChunkAssets.length = 0;
  483. this.assets = {};
  484. this.modules.forEach(module => module.unseal());
  485. }
  486. seal(callback) {
  487. const self = this;
  488. self.applyPlugins0("seal");
  489. self.nextFreeModuleIndex = 0;
  490. self.nextFreeModuleIndex2 = 0;
  491. self.preparedChunks.forEach(preparedChunk => {
  492. const module = preparedChunk.module;
  493. const chunk = self.addChunk(preparedChunk.name, module);
  494. const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name);
  495. entrypoint.unshiftChunk(chunk);
  496. chunk.addModule(module);
  497. module.addChunk(chunk);
  498. chunk.entryModule = module;
  499. self.assignIndex(module);
  500. self.assignDepth(module);
  501. });
  502. self.processDependenciesBlocksForChunks(self.chunks.slice());
  503. self.sortModules(self.modules);
  504. self.applyPlugins0("optimize");
  505. while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) ||
  506. self.applyPluginsBailResult1("optimize-modules", self.modules) ||
  507. self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)) { /* empty */ }
  508. self.applyPlugins1("after-optimize-modules", self.modules);
  509. while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) ||
  510. self.applyPluginsBailResult1("optimize-chunks", self.chunks) ||
  511. self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)) { /* empty */ }
  512. self.applyPlugins1("after-optimize-chunks", self.chunks);
  513. self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) {
  514. if(err) {
  515. return callback(err);
  516. }
  517. self.applyPlugins2("after-optimize-tree", self.chunks, self.modules);
  518. while(self.applyPluginsBailResult("optimize-chunk-modules-basic", self.chunks, self.modules) ||
  519. self.applyPluginsBailResult("optimize-chunk-modules", self.chunks, self.modules) ||
  520. self.applyPluginsBailResult("optimize-chunk-modules-advanced", self.chunks, self.modules)) { /* empty */ }
  521. self.applyPlugins2("after-optimize-chunk-modules", self.chunks, self.modules);
  522. const shouldRecord = self.applyPluginsBailResult("should-record") !== false;
  523. self.applyPlugins2("revive-modules", self.modules, self.records);
  524. self.applyPlugins1("optimize-module-order", self.modules);
  525. self.applyPlugins1("advanced-optimize-module-order", self.modules);
  526. self.applyPlugins1("before-module-ids", self.modules);
  527. self.applyPlugins1("module-ids", self.modules);
  528. self.applyModuleIds();
  529. self.applyPlugins1("optimize-module-ids", self.modules);
  530. self.applyPlugins1("after-optimize-module-ids", self.modules);
  531. self.sortItemsWithModuleIds();
  532. self.applyPlugins2("revive-chunks", self.chunks, self.records);
  533. self.applyPlugins1("optimize-chunk-order", self.chunks);
  534. self.applyPlugins1("before-chunk-ids", self.chunks);
  535. self.applyChunkIds();
  536. self.applyPlugins1("optimize-chunk-ids", self.chunks);
  537. self.applyPlugins1("after-optimize-chunk-ids", self.chunks);
  538. self.sortItemsWithChunkIds();
  539. if(shouldRecord)
  540. self.applyPlugins2("record-modules", self.modules, self.records);
  541. if(shouldRecord)
  542. self.applyPlugins2("record-chunks", self.chunks, self.records);
  543. self.applyPlugins0("before-hash");
  544. self.createHash();
  545. self.applyPlugins0("after-hash");
  546. if(shouldRecord)
  547. self.applyPlugins1("record-hash", self.records);
  548. self.applyPlugins0("before-module-assets");
  549. self.createModuleAssets();
  550. if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
  551. self.applyPlugins0("before-chunk-assets");
  552. self.createChunkAssets();
  553. }
  554. self.applyPlugins1("additional-chunk-assets", self.chunks);
  555. self.summarizeDependencies();
  556. if(shouldRecord)
  557. self.applyPlugins2("record", self, self.records);
  558. self.applyPluginsAsync("additional-assets", err => {
  559. if(err) {
  560. return callback(err);
  561. }
  562. self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => {
  563. if(err) {
  564. return callback(err);
  565. }
  566. self.applyPlugins1("after-optimize-chunk-assets", self.chunks);
  567. self.applyPluginsAsync("optimize-assets", self.assets, err => {
  568. if(err) {
  569. return callback(err);
  570. }
  571. self.applyPlugins1("after-optimize-assets", self.assets);
  572. if(self.applyPluginsBailResult("need-additional-seal")) {
  573. self.unseal();
  574. return self.seal(callback);
  575. }
  576. return self.applyPluginsAsync("after-seal", callback);
  577. });
  578. });
  579. });
  580. });
  581. }
  582. sortModules(modules) {
  583. modules.sort((a, b) => {
  584. if(a.index < b.index) return -1;
  585. if(a.index > b.index) return 1;
  586. return 0;
  587. });
  588. }
  589. reportDependencyErrorsAndWarnings(module, blocks) {
  590. for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) {
  591. const block = blocks[indexBlock];
  592. const dependencies = block.dependencies;
  593. for(let indexDep = 0; indexDep < dependencies.length; indexDep++) {
  594. const d = dependencies[indexDep];
  595. const warnings = d.getWarnings();
  596. if(warnings) {
  597. for(let indexWar = 0; indexWar < warnings.length; indexWar++) {
  598. const w = warnings[indexWar];
  599. const warning = new ModuleDependencyWarning(module, w, d.loc);
  600. this.warnings.push(warning);
  601. }
  602. }
  603. const errors = d.getErrors();
  604. if(errors) {
  605. for(let indexErr = 0; indexErr < errors.length; indexErr++) {
  606. const e = errors[indexErr];
  607. const error = new ModuleDependencyError(module, e, d.loc);
  608. this.errors.push(error);
  609. }
  610. }
  611. }
  612. this.reportDependencyErrorsAndWarnings(module, block.blocks);
  613. }
  614. }
  615. addChunk(name, module, loc) {
  616. if(name) {
  617. if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) {
  618. const chunk = this.namedChunks[name];
  619. if(module) {
  620. chunk.addOrigin(module, loc);
  621. }
  622. return chunk;
  623. }
  624. }
  625. const chunk = new Chunk(name, module, loc);
  626. this.chunks.push(chunk);
  627. if(name) {
  628. this.namedChunks[name] = chunk;
  629. }
  630. return chunk;
  631. }
  632. assignIndex(module) {
  633. const _this = this;
  634. const queue = [() => {
  635. assignIndexToModule(module);
  636. }];
  637. const iteratorAllDependencies = d => {
  638. queue.push(() => assignIndexToDependency(d));
  639. };
  640. function assignIndexToModule(module) {
  641. // enter module
  642. if(typeof module.index !== "number") {
  643. module.index = _this.nextFreeModuleIndex++;
  644. // leave module
  645. queue.push(() => module.index2 = _this.nextFreeModuleIndex2++);
  646. // enter it as block
  647. assignIndexToDependencyBlock(module);
  648. }
  649. }
  650. function assignIndexToDependency(dependency) {
  651. if(dependency.module) {
  652. queue.push(() => assignIndexToModule(dependency.module));
  653. }
  654. }
  655. function assignIndexToDependencyBlock(block) {
  656. let allDependencies = [];
  657. function iteratorDependency(d) {
  658. allDependencies.push(d);
  659. }
  660. function iteratorBlock(b) {
  661. queue.push(() => assignIndexToDependencyBlock(b));
  662. }
  663. if(block.variables) {
  664. iterationBlockVariable(block.variables, iteratorDependency);
  665. }
  666. if(block.dependencies) {
  667. iterationOfArrayCallback(block.dependencies, iteratorDependency);
  668. }
  669. if(block.blocks) {
  670. const blocks = block.blocks;
  671. let indexBlock = blocks.length;
  672. while(indexBlock--) {
  673. iteratorBlock(blocks[indexBlock]);
  674. }
  675. }
  676. let indexAll = allDependencies.length;
  677. while(indexAll--) {
  678. iteratorAllDependencies(allDependencies[indexAll]);
  679. }
  680. }
  681. while(queue.length) {
  682. queue.pop()();
  683. }
  684. }
  685. assignDepth(module) {
  686. function assignDepthToModule(module, depth) {
  687. // enter module
  688. if(typeof module.depth === "number" && module.depth <= depth) return;
  689. module.depth = depth;
  690. // enter it as block
  691. assignDepthToDependencyBlock(module, depth + 1);
  692. }
  693. function assignDepthToDependency(dependency, depth) {
  694. if(dependency.module) {
  695. queue.push(() => assignDepthToModule(dependency.module, depth));
  696. }
  697. }
  698. function assignDepthToDependencyBlock(block, depth) {
  699. function iteratorDependency(d) {
  700. assignDepthToDependency(d, depth);
  701. }
  702. function iteratorBlock(b) {
  703. assignDepthToDependencyBlock(b, depth);
  704. }
  705. if(block.variables) {
  706. iterationBlockVariable(block.variables, iteratorDependency);
  707. }
  708. if(block.dependencies) {
  709. iterationOfArrayCallback(block.dependencies, iteratorDependency);
  710. }
  711. if(block.blocks) {
  712. iterationOfArrayCallback(block.blocks, iteratorBlock);
  713. }
  714. }
  715. const queue = [() => {
  716. assignDepthToModule(module, 0);
  717. }];
  718. while(queue.length) {
  719. queue.pop()();
  720. }
  721. }
  722. // This method creates the Chunk graph from the Module graph
  723. processDependenciesBlocksForChunks(inputChunks) {
  724. // Process is splitting into two parts:
  725. // Part one traverse the module graph and builds a very basic chunks graph
  726. // in chunkDependencies.
  727. // Part two traverse every possible way through the basic chunk graph and
  728. // tracks the available modules. While traversing it connects chunks with
  729. // eachother and Blocks with Chunks. It stops traversing when all modules
  730. // for a chunk are already available. So it doesn't connect unneeded chunks.
  731. const chunkDependencies = new Map(); // Map<Chunk, Array<{Module, Chunk}>>
  732. const allCreatedChunks = new Set();
  733. // PART ONE
  734. const blockChunks = new Map();
  735. // Start with the provided modules/chunks
  736. const queue = inputChunks.map(chunk => ({
  737. block: chunk.entryModule,
  738. chunk: chunk
  739. }));
  740. let block, chunk;
  741. // For each async Block in graph
  742. const iteratorBlock = b => {
  743. // 1. We create a chunk for this Block
  744. // but only once (blockChunks map)
  745. let c = blockChunks.get(b);
  746. if(c === undefined) {
  747. c = this.namedChunks[b.chunkName];
  748. if(c && c.isInitial()) {
  749. // TODO webpack 4: convert this to an error
  750. this.warnings.push(new AsyncDependencyToInitialChunkWarning(b.chunkName, b.module, b.loc));
  751. c = chunk;
  752. } else {
  753. c = this.addChunk(b.chunkName, b.module, b.loc);
  754. blockChunks.set(b, c);
  755. allCreatedChunks.add(c);
  756. // We initialize the chunks property
  757. // this is later filled with the chunk when needed
  758. b.chunks = [];
  759. }
  760. }
  761. // 2. We store the Block+Chunk mapping as dependency for the chunk
  762. let deps = chunkDependencies.get(chunk);
  763. if(!deps) chunkDependencies.set(chunk, deps = []);
  764. deps.push({
  765. block: b,
  766. chunk: c
  767. });
  768. // 3. We enqueue the DependenciesBlock for traversal
  769. queue.push({
  770. block: b,
  771. chunk: c
  772. });
  773. };
  774. // For each Dependency in the graph
  775. const iteratorDependency = d => {
  776. // We skip Dependencies without Module pointer
  777. if(!d.module) {
  778. return;
  779. }
  780. // We skip weak Dependencies
  781. if(d.weak) {
  782. return;
  783. }
  784. // We connect Module and Chunk when not already done
  785. if(chunk.addModule(d.module)) {
  786. d.module.addChunk(chunk);
  787. // And enqueue the Module for traversal
  788. queue.push({
  789. block: d.module,
  790. chunk
  791. });
  792. }
  793. };
  794. // Iterative traversal of the Module graph
  795. // Recursive would be simpler to write but could result in Stack Overflows
  796. while(queue.length) {
  797. const queueItem = queue.pop();
  798. block = queueItem.block;
  799. chunk = queueItem.chunk;
  800. // Traverse all variables, Dependencies and Blocks
  801. if(block.variables) {
  802. iterationBlockVariable(block.variables, iteratorDependency);
  803. }
  804. if(block.dependencies) {
  805. iterationOfArrayCallback(block.dependencies, iteratorDependency);
  806. }
  807. if(block.blocks) {
  808. iterationOfArrayCallback(block.blocks, iteratorBlock);
  809. }
  810. }
  811. // PART TWO
  812. let availableModules;
  813. let newAvailableModules;
  814. const queue2 = new Queue(inputChunks.map(chunk => ({
  815. chunk,
  816. availableModules: new Set()
  817. })));
  818. // Helper function to check if all modules of a chunk are available
  819. const areModulesAvailable = (chunk, availableModules) => {
  820. for(const module of chunk.modulesIterable) {
  821. if(!availableModules.has(module))
  822. return false;
  823. }
  824. return true;
  825. };
  826. // For each edge in the basic chunk graph
  827. const filterFn = dep => {
  828. // Filter egdes that are not needed because all modules are already available
  829. // This also filters circular dependencies in the chunks graph
  830. const depChunk = dep.chunk;
  831. if(areModulesAvailable(depChunk, newAvailableModules))
  832. return false; // break all modules are already available
  833. return true;
  834. };
  835. const minAvailableModulesMap = new Map();
  836. // Iterative traversing of the basic chunk graph
  837. while(queue2.length) {
  838. const queueItem = queue2.dequeue();
  839. chunk = queueItem.chunk;
  840. availableModules = queueItem.availableModules;
  841. // 1. Get minimal available modules
  842. // It doesn't make sense to traverse a chunk again with more available modules.
  843. // This step calculates the minimal available modules and skips traversal when
  844. // the list didn't shrink.
  845. let minAvailableModules = minAvailableModulesMap.get(chunk);
  846. if(minAvailableModules === undefined) {
  847. minAvailableModulesMap.set(chunk, new Set(availableModules));
  848. } else {
  849. let deletedModules = false;
  850. for(const m of minAvailableModules) {
  851. if(!availableModules.has(m)) {
  852. minAvailableModules.delete(m);
  853. deletedModules = true;
  854. }
  855. }
  856. if(!deletedModules)
  857. continue;
  858. availableModules = minAvailableModules;
  859. }
  860. // 2. Get the edges at this point of the graph
  861. const deps = chunkDependencies.get(chunk);
  862. if(!deps) continue;
  863. if(deps.length === 0) continue;
  864. // 3. Create a new Set of available modules at this points
  865. newAvailableModules = new Set(availableModules);
  866. for(const m of chunk.modulesIterable)
  867. newAvailableModules.add(m);
  868. // 4. Filter edges with available modules
  869. const filteredDeps = deps.filter(filterFn);
  870. // 5. Foreach remaining edge
  871. const nextChunks = new Set();
  872. for(let i = 0; i < filteredDeps.length; i++) {
  873. const dep = filteredDeps[i];
  874. const depChunk = dep.chunk;
  875. const depBlock = dep.block;
  876. // 6. Connnect block with chunk
  877. if(depChunk.addBlock(depBlock)) {
  878. depBlock.chunks.push(depChunk);
  879. }
  880. // 7. Connect chunk with parent
  881. if(chunk.addChunk(depChunk)) {
  882. depChunk.addParent(chunk);
  883. }
  884. nextChunks.add(depChunk);
  885. }
  886. // 8. Enqueue further traversal
  887. for(const nextChunk of nextChunks) {
  888. queue2.enqueue({
  889. chunk: nextChunk,
  890. availableModules: newAvailableModules
  891. });
  892. }
  893. }
  894. // Remove all unconnected chunks
  895. for(const chunk of allCreatedChunks) {
  896. if(chunk.parents.length === 0)
  897. chunk.remove("unconnected");
  898. }
  899. }
  900. removeChunkFromDependencies(block, chunk) {
  901. const iteratorDependency = d => {
  902. if(!d.module) {
  903. return;
  904. }
  905. if(!d.module.hasReasonForChunk(chunk)) {
  906. if(d.module.removeChunk(chunk)) {
  907. this.removeChunkFromDependencies(d.module, chunk);
  908. }
  909. }
  910. };
  911. const blocks = block.blocks;
  912. for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) {
  913. const chunks = blocks[indexBlock].chunks;
  914. for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
  915. const blockChunk = chunks[indexChunk];
  916. chunk.removeChunk(blockChunk);
  917. blockChunk.removeParent(chunk);
  918. this.removeChunkFromDependencies(chunks, blockChunk);
  919. }
  920. }
  921. if(block.dependencies) {
  922. iterationOfArrayCallback(block.dependencies, iteratorDependency);
  923. }
  924. if(block.variables) {
  925. iterationBlockVariable(block.variables, iteratorDependency);
  926. }
  927. }
  928. applyModuleIds() {
  929. let unusedIds = [];
  930. let nextFreeModuleId = 0;
  931. let usedIds = [];
  932. // TODO consider Map when performance has improved https://gist.github.com/sokra/234c077e1299b7369461f1708519c392
  933. const usedIdMap = Object.create(null);
  934. if(this.usedModuleIds) {
  935. Object.keys(this.usedModuleIds).forEach(key => {
  936. const id = this.usedModuleIds[key];
  937. if(!usedIdMap[id]) {
  938. usedIds.push(id);
  939. usedIdMap[id] = true;
  940. }
  941. });
  942. }
  943. const modules1 = this.modules;
  944. for(let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) {
  945. const module1 = modules1[indexModule1];
  946. if(module1.id && !usedIdMap[module1.id]) {
  947. usedIds.push(module1.id);
  948. usedIdMap[module1.id] = true;
  949. }
  950. }
  951. if(usedIds.length > 0) {
  952. let usedIdMax = -1;
  953. for(let index = 0; index < usedIds.length; index++) {
  954. const usedIdKey = usedIds[index];
  955. if(typeof usedIdKey !== "number") {
  956. continue;
  957. }
  958. usedIdMax = Math.max(usedIdMax, usedIdKey);
  959. }
  960. let lengthFreeModules = nextFreeModuleId = usedIdMax + 1;
  961. while(lengthFreeModules--) {
  962. if(!usedIdMap[lengthFreeModules]) {
  963. unusedIds.push(lengthFreeModules);
  964. }
  965. }
  966. }
  967. const modules2 = this.modules;
  968. for(let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) {
  969. const module2 = modules2[indexModule2];
  970. if(module2.id === null) {
  971. if(unusedIds.length > 0)
  972. module2.id = unusedIds.pop();
  973. else
  974. module2.id = nextFreeModuleId++;
  975. }
  976. }
  977. }
  978. applyChunkIds() {
  979. const unusedIds = [];
  980. let nextFreeChunkId = 0;
  981. function getNextFreeChunkId(usedChunkIds) {
  982. const keyChunks = Object.keys(usedChunkIds);
  983. let result = -1;
  984. for(let index = 0; index < keyChunks.length; index++) {
  985. const usedIdKey = keyChunks[index];
  986. const usedIdValue = usedChunkIds[usedIdKey];
  987. if(typeof usedIdValue !== "number") {
  988. continue;
  989. }
  990. result = Math.max(result, usedIdValue);
  991. }
  992. return result;
  993. }
  994. if(this.usedChunkIds) {
  995. nextFreeChunkId = getNextFreeChunkId(this.usedChunkIds) + 1;
  996. let index = nextFreeChunkId;
  997. while(index--) {
  998. if(this.usedChunkIds[index] !== index) {
  999. unusedIds.push(index);
  1000. }
  1001. }
  1002. }
  1003. const chunks = this.chunks;
  1004. for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
  1005. const chunk = chunks[indexChunk];
  1006. if(chunk.id === null) {
  1007. if(unusedIds.length > 0)
  1008. chunk.id = unusedIds.pop();
  1009. else
  1010. chunk.id = nextFreeChunkId++;
  1011. }
  1012. if(!chunk.ids) {
  1013. chunk.ids = [chunk.id];
  1014. }
  1015. }
  1016. }
  1017. sortItemsWithModuleIds() {
  1018. this.modules.sort(byId);
  1019. const modules = this.modules;
  1020. for(let indexModule = 0; indexModule < modules.length; indexModule++) {
  1021. modules[indexModule].sortItems(false);
  1022. }
  1023. const chunks = this.chunks;
  1024. for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
  1025. chunks[indexChunk].sortItems();
  1026. }
  1027. }
  1028. sortItemsWithChunkIds() {
  1029. this.chunks.sort(byId);
  1030. const modules = this.modules;
  1031. for(let indexModule = 0; indexModule < modules.length; indexModule++) {
  1032. modules[indexModule].sortItems(true);
  1033. }
  1034. const chunks = this.chunks;
  1035. for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
  1036. chunks[indexChunk].sortItems();
  1037. }
  1038. const byMessage = (a, b) => {
  1039. const ma = `${a.message}`;
  1040. const mb = `${b.message}`;
  1041. if(ma < mb) return -1;
  1042. if(mb < ma) return 1;
  1043. return 0;
  1044. };
  1045. this.errors.sort(byMessage);
  1046. this.warnings.sort(byMessage);
  1047. }
  1048. summarizeDependencies() {
  1049. function filterDups(array) {
  1050. const newArray = [];
  1051. for(let i = 0; i < array.length; i++) {
  1052. if(i === 0 || array[i - 1] !== array[i])
  1053. newArray.push(array[i]);
  1054. }
  1055. return newArray;
  1056. }
  1057. this.fileDependencies = (this.compilationDependencies || []).slice();
  1058. this.contextDependencies = [];
  1059. this.missingDependencies = [];
  1060. const children = this.children;
  1061. for(let indexChildren = 0; indexChildren < children.length; indexChildren++) {
  1062. const child = children[indexChildren];
  1063. this.fileDependencies = this.fileDependencies.concat(child.fileDependencies);
  1064. this.contextDependencies = this.contextDependencies.concat(child.contextDependencies);
  1065. this.missingDependencies = this.missingDependencies.concat(child.missingDependencies);
  1066. }
  1067. const modules = this.modules;
  1068. for(let indexModule = 0; indexModule < modules.length; indexModule++) {
  1069. const module = modules[indexModule];
  1070. if(module.fileDependencies) {
  1071. const fileDependencies = module.fileDependencies;
  1072. for(let indexFileDep = 0; indexFileDep < fileDependencies.length; indexFileDep++) {
  1073. this.fileDependencies.push(fileDependencies[indexFileDep]);
  1074. }
  1075. }
  1076. if(module.contextDependencies) {
  1077. const contextDependencies = module.contextDependencies;
  1078. for(let indexContextDep = 0; indexContextDep < contextDependencies.length; indexContextDep++) {
  1079. this.contextDependencies.push(contextDependencies[indexContextDep]);
  1080. }
  1081. }
  1082. }
  1083. this.errors.forEach(error => {
  1084. if(Array.isArray(error.missing)) {
  1085. error.missing.forEach(item => this.missingDependencies.push(item));
  1086. }
  1087. });
  1088. this.fileDependencies.sort();
  1089. this.fileDependencies = filterDups(this.fileDependencies);
  1090. this.contextDependencies.sort();
  1091. this.contextDependencies = filterDups(this.contextDependencies);
  1092. this.missingDependencies.sort();
  1093. this.missingDependencies = filterDups(this.missingDependencies);
  1094. }
  1095. createHash() {
  1096. const outputOptions = this.outputOptions;
  1097. const hashFunction = outputOptions.hashFunction;
  1098. const hashDigest = outputOptions.hashDigest;
  1099. const hashDigestLength = outputOptions.hashDigestLength;
  1100. const hash = crypto.createHash(hashFunction);
  1101. if(outputOptions.hashSalt)
  1102. hash.update(outputOptions.hashSalt);
  1103. this.mainTemplate.updateHash(hash);
  1104. this.chunkTemplate.updateHash(hash);
  1105. this.moduleTemplate.updateHash(hash);
  1106. this.children.forEach(function(child) {
  1107. hash.update(child.hash);
  1108. });
  1109. this.warnings.forEach(function(warning) {
  1110. hash.update(`${warning.message}`);
  1111. });
  1112. this.errors.forEach(function(error) {
  1113. hash.update(`${error.message}`);
  1114. });
  1115. // clone needed as sort below is inplace mutation
  1116. const chunks = this.chunks.slice();
  1117. /**
  1118. * sort here will bring all "falsy" values to the beginning
  1119. * this is needed as the "hasRuntime()" chunks are dependent on the
  1120. * hashes of the non-runtime chunks.
  1121. */
  1122. chunks.sort((a, b) => {
  1123. const aEntry = a.hasRuntime();
  1124. const bEntry = b.hasRuntime();
  1125. if(aEntry && !bEntry) return 1;
  1126. if(!aEntry && bEntry) return -1;
  1127. return 0;
  1128. });
  1129. for(let i = 0; i < chunks.length; i++) {
  1130. const chunk = chunks[i];
  1131. const chunkHash = crypto.createHash(hashFunction);
  1132. if(outputOptions.hashSalt)
  1133. chunkHash.update(outputOptions.hashSalt);
  1134. chunk.updateHash(chunkHash);
  1135. if(chunk.hasRuntime()) {
  1136. this.mainTemplate.updateHashForChunk(chunkHash, chunk);
  1137. } else {
  1138. this.chunkTemplate.updateHashForChunk(chunkHash, chunk);
  1139. }
  1140. this.applyPlugins2("chunk-hash", chunk, chunkHash);
  1141. chunk.hash = chunkHash.digest(hashDigest);
  1142. hash.update(chunk.hash);
  1143. chunk.renderedHash = chunk.hash.substr(0, hashDigestLength);
  1144. }
  1145. this.fullHash = hash.digest(hashDigest);
  1146. this.hash = this.fullHash.substr(0, hashDigestLength);
  1147. }
  1148. modifyHash(update) {
  1149. const outputOptions = this.outputOptions;
  1150. const hashFunction = outputOptions.hashFunction;
  1151. const hashDigest = outputOptions.hashDigest;
  1152. const hashDigestLength = outputOptions.hashDigestLength;
  1153. const hash = crypto.createHash(hashFunction);
  1154. hash.update(this.fullHash);
  1155. hash.update(update);
  1156. this.fullHash = hash.digest(hashDigest);
  1157. this.hash = this.fullHash.substr(0, hashDigestLength);
  1158. }
  1159. createModuleAssets() {
  1160. for(let i = 0; i < this.modules.length; i++) {
  1161. const module = this.modules[i];
  1162. if(module.assets) {
  1163. Object.keys(module.assets).forEach((assetName) => {
  1164. const fileName = this.getPath(assetName);
  1165. this.assets[fileName] = module.assets[assetName];
  1166. this.applyPlugins2("module-asset", module, fileName);
  1167. });
  1168. }
  1169. }
  1170. }
  1171. createChunkAssets() {
  1172. const outputOptions = this.outputOptions;
  1173. const filename = outputOptions.filename;
  1174. const chunkFilename = outputOptions.chunkFilename;
  1175. for(let i = 0; i < this.chunks.length; i++) {
  1176. const chunk = this.chunks[i];
  1177. chunk.files = [];
  1178. const chunkHash = chunk.hash;
  1179. let source;
  1180. let file;
  1181. const filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate :
  1182. chunk.isInitial() ? filename :
  1183. chunkFilename;
  1184. try {
  1185. const useChunkHash = !chunk.hasRuntime() || (this.mainTemplate.useChunkHash && this.mainTemplate.useChunkHash(chunk));
  1186. const usedHash = useChunkHash ? chunkHash : this.fullHash;
  1187. const cacheName = "c" + chunk.id;
  1188. if(this.cache && this.cache[cacheName] && this.cache[cacheName].hash === usedHash) {
  1189. source = this.cache[cacheName].source;
  1190. } else {
  1191. if(chunk.hasRuntime()) {
  1192. source = this.mainTemplate.render(this.hash, chunk, this.moduleTemplate, this.dependencyTemplates);
  1193. } else {
  1194. source = this.chunkTemplate.render(chunk, this.moduleTemplate, this.dependencyTemplates);
  1195. }
  1196. if(this.cache) {
  1197. this.cache[cacheName] = {
  1198. hash: usedHash,
  1199. source: source = (source instanceof CachedSource ? source : new CachedSource(source))
  1200. };
  1201. }
  1202. }
  1203. file = this.getPath(filenameTemplate, {
  1204. noChunkHash: !useChunkHash,
  1205. chunk
  1206. });
  1207. if(this.assets[file])
  1208. throw new Error(`Conflict: Multiple assets emit to the same filename ${file}`);
  1209. this.assets[file] = source;
  1210. chunk.files.push(file);
  1211. this.applyPlugins2("chunk-asset", chunk, file);
  1212. } catch(err) {
  1213. this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err));
  1214. }
  1215. }
  1216. }
  1217. getPath(filename, data) {
  1218. data = data || {};
  1219. data.hash = data.hash || this.hash;
  1220. return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data);
  1221. }
  1222. createChildCompiler(name, outputOptions, plugins) {
  1223. var idx = (this.childrenCounters[name] || 0);
  1224. this.childrenCounters[name] = idx + 1;
  1225. return this.compiler.createChildCompiler(this, name, idx, outputOptions, plugins);
  1226. }
  1227. checkConstraints() {
  1228. const usedIds = {};
  1229. const modules = this.modules;
  1230. for(let indexModule = 0; indexModule < modules.length; indexModule++) {
  1231. const moduleId = modules[indexModule].id;
  1232. if(usedIds[moduleId])
  1233. throw new Error(`checkConstraints: duplicate module id ${moduleId}`);
  1234. }
  1235. const chunks = this.chunks;
  1236. for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
  1237. const chunk = chunks[indexChunk];
  1238. if(chunks.indexOf(chunk) !== indexChunk)
  1239. throw new Error(`checkConstraints: duplicate chunk in compilation ${chunk.debugId}`);
  1240. chunk.checkConstraints();
  1241. }
  1242. }
  1243. }
  1244. module.exports = Compilation;