NormalModule.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const parseJson = require("json-parse-even-better-errors");
  7. const { getContext, runLoaders } = require("loader-runner");
  8. const querystring = require("querystring");
  9. const { HookMap, SyncHook, AsyncSeriesBailHook } = require("tapable");
  10. const {
  11. CachedSource,
  12. OriginalSource,
  13. RawSource,
  14. SourceMapSource
  15. } = require("webpack-sources");
  16. const Compilation = require("./Compilation");
  17. const HookWebpackError = require("./HookWebpackError");
  18. const Module = require("./Module");
  19. const ModuleBuildError = require("./ModuleBuildError");
  20. const ModuleError = require("./ModuleError");
  21. const ModuleGraphConnection = require("./ModuleGraphConnection");
  22. const ModuleParseError = require("./ModuleParseError");
  23. const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants");
  24. const ModuleWarning = require("./ModuleWarning");
  25. const RuntimeGlobals = require("./RuntimeGlobals");
  26. const UnhandledSchemeError = require("./UnhandledSchemeError");
  27. const WebpackError = require("./WebpackError");
  28. const formatLocation = require("./formatLocation");
  29. const LazySet = require("./util/LazySet");
  30. const { isSubset } = require("./util/SetHelpers");
  31. const { getScheme } = require("./util/URLAbsoluteSpecifier");
  32. const {
  33. compareLocations,
  34. concatComparators,
  35. compareSelect,
  36. keepOriginalOrder
  37. } = require("./util/comparators");
  38. const createHash = require("./util/createHash");
  39. const { createFakeHook } = require("./util/deprecation");
  40. const { join } = require("./util/fs");
  41. const {
  42. contextify,
  43. absolutify,
  44. makePathsRelative
  45. } = require("./util/identifier");
  46. const makeSerializable = require("./util/makeSerializable");
  47. const memoize = require("./util/memoize");
  48. /** @typedef {import("webpack-sources").Source} Source */
  49. /** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */
  50. /** @typedef {import("../declarations/WebpackOptions").Mode} Mode */
  51. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  52. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  53. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  54. /** @typedef {import("./Compiler")} Compiler */
  55. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  56. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  57. /** @typedef {import("./Generator")} Generator */
  58. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  59. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  60. /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  61. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  62. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  63. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  64. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  65. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  66. /** @typedef {import("./Parser")} Parser */
  67. /** @typedef {import("./RequestShortener")} RequestShortener */
  68. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  69. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  70. /** @typedef {import("./logging/Logger").Logger} WebpackLogger */
  71. /** @typedef {import("./util/Hash")} Hash */
  72. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  73. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  74. /**
  75. * @typedef {Object} SourceMap
  76. * @property {number} version
  77. * @property {string[]} sources
  78. * @property {string} mappings
  79. * @property {string=} file
  80. * @property {string=} sourceRoot
  81. * @property {string[]=} sourcesContent
  82. * @property {string[]=} names
  83. */
  84. const getInvalidDependenciesModuleWarning = memoize(() =>
  85. require("./InvalidDependenciesModuleWarning")
  86. );
  87. const getValidate = memoize(() => require("schema-utils").validate);
  88. const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
  89. /**
  90. * @typedef {Object} LoaderItem
  91. * @property {string} loader
  92. * @property {any} options
  93. * @property {string?} ident
  94. * @property {string?} type
  95. */
  96. /**
  97. * @param {string} context absolute context path
  98. * @param {string} source a source path
  99. * @param {Object=} associatedObjectForCache an object to which the cache will be attached
  100. * @returns {string} new source path
  101. */
  102. const contextifySourceUrl = (context, source, associatedObjectForCache) => {
  103. if (source.startsWith("webpack://")) return source;
  104. return `webpack://${makePathsRelative(
  105. context,
  106. source,
  107. associatedObjectForCache
  108. )}`;
  109. };
  110. /**
  111. * @param {string} context absolute context path
  112. * @param {SourceMap} sourceMap a source map
  113. * @param {Object=} associatedObjectForCache an object to which the cache will be attached
  114. * @returns {SourceMap} new source map
  115. */
  116. const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
  117. if (!Array.isArray(sourceMap.sources)) return sourceMap;
  118. const { sourceRoot } = sourceMap;
  119. /** @type {function(string): string} */
  120. const mapper = !sourceRoot
  121. ? source => source
  122. : sourceRoot.endsWith("/")
  123. ? source =>
  124. source.startsWith("/")
  125. ? `${sourceRoot.slice(0, -1)}${source}`
  126. : `${sourceRoot}${source}`
  127. : source =>
  128. source.startsWith("/")
  129. ? `${sourceRoot}${source}`
  130. : `${sourceRoot}/${source}`;
  131. const newSources = sourceMap.sources.map(source =>
  132. contextifySourceUrl(context, mapper(source), associatedObjectForCache)
  133. );
  134. return {
  135. ...sourceMap,
  136. file: "x",
  137. sourceRoot: undefined,
  138. sources: newSources
  139. };
  140. };
  141. /**
  142. * @param {string | Buffer} input the input
  143. * @returns {string} the converted string
  144. */
  145. const asString = input => {
  146. if (Buffer.isBuffer(input)) {
  147. return input.toString("utf-8");
  148. }
  149. return input;
  150. };
  151. /**
  152. * @param {string | Buffer} input the input
  153. * @returns {Buffer} the converted buffer
  154. */
  155. const asBuffer = input => {
  156. if (!Buffer.isBuffer(input)) {
  157. return Buffer.from(input, "utf-8");
  158. }
  159. return input;
  160. };
  161. class NonErrorEmittedError extends WebpackError {
  162. constructor(error) {
  163. super();
  164. this.name = "NonErrorEmittedError";
  165. this.message = "(Emitted value instead of an instance of Error) " + error;
  166. }
  167. }
  168. makeSerializable(
  169. NonErrorEmittedError,
  170. "webpack/lib/NormalModule",
  171. "NonErrorEmittedError"
  172. );
  173. /**
  174. * @typedef {Object} NormalModuleCompilationHooks
  175. * @property {SyncHook<[object, NormalModule]>} loader
  176. * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders
  177. * @property {SyncHook<[NormalModule]>} beforeParse
  178. * @property {SyncHook<[NormalModule]>} beforeSnapshot
  179. * @property {HookMap<AsyncSeriesBailHook<[string, NormalModule], string | Buffer>>} readResourceForScheme
  180. * @property {HookMap<AsyncSeriesBailHook<[object], string | Buffer>>} readResource
  181. * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
  182. */
  183. /**
  184. * @typedef {Object} NormalModuleCreateData
  185. * @property {string=} layer an optional layer in which the module is
  186. * @property {string} type module type
  187. * @property {string} request request string
  188. * @property {string} userRequest request intended by user (without loaders from config)
  189. * @property {string} rawRequest request without resolving
  190. * @property {LoaderItem[]} loaders list of loaders
  191. * @property {string} resource path + query of the real resource
  192. * @property {Record<string, any>=} resourceResolveData resource resolve data
  193. * @property {string} context context directory for resolving
  194. * @property {string=} matchResource path + query of the matched resource (virtual)
  195. * @property {Parser} parser the parser used
  196. * @property {Record<string, any>=} parserOptions the options of the parser used
  197. * @property {Generator} generator the generator used
  198. * @property {Record<string, any>=} generatorOptions the options of the generator used
  199. * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module
  200. */
  201. /** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
  202. const compilationHooksMap = new WeakMap();
  203. class NormalModule extends Module {
  204. /**
  205. * @param {Compilation} compilation the compilation
  206. * @returns {NormalModuleCompilationHooks} the attached hooks
  207. */
  208. static getCompilationHooks(compilation) {
  209. if (!(compilation instanceof Compilation)) {
  210. throw new TypeError(
  211. "The 'compilation' argument must be an instance of Compilation"
  212. );
  213. }
  214. let hooks = compilationHooksMap.get(compilation);
  215. if (hooks === undefined) {
  216. hooks = {
  217. loader: new SyncHook(["loaderContext", "module"]),
  218. beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]),
  219. beforeParse: new SyncHook(["module"]),
  220. beforeSnapshot: new SyncHook(["module"]),
  221. // TODO webpack 6 deprecate
  222. readResourceForScheme: new HookMap(scheme => {
  223. const hook = hooks.readResource.for(scheme);
  224. return createFakeHook(
  225. /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({
  226. tap: (options, fn) =>
  227. hook.tap(options, loaderContext =>
  228. fn(loaderContext.resource, loaderContext._module)
  229. ),
  230. tapAsync: (options, fn) =>
  231. hook.tapAsync(options, (loaderContext, callback) =>
  232. fn(loaderContext.resource, loaderContext._module, callback)
  233. ),
  234. tapPromise: (options, fn) =>
  235. hook.tapPromise(options, loaderContext =>
  236. fn(loaderContext.resource, loaderContext._module)
  237. )
  238. })
  239. );
  240. }),
  241. readResource: new HookMap(
  242. () => new AsyncSeriesBailHook(["loaderContext"])
  243. ),
  244. needBuild: new AsyncSeriesBailHook(["module", "context"])
  245. };
  246. compilationHooksMap.set(compilation, hooks);
  247. }
  248. return hooks;
  249. }
  250. /**
  251. * @param {NormalModuleCreateData} options options object
  252. */
  253. constructor({
  254. layer,
  255. type,
  256. request,
  257. userRequest,
  258. rawRequest,
  259. loaders,
  260. resource,
  261. resourceResolveData,
  262. context,
  263. matchResource,
  264. parser,
  265. parserOptions,
  266. generator,
  267. generatorOptions,
  268. resolveOptions
  269. }) {
  270. super(type, context || getContext(resource), layer);
  271. // Info from Factory
  272. /** @type {string} */
  273. this.request = request;
  274. /** @type {string} */
  275. this.userRequest = userRequest;
  276. /** @type {string} */
  277. this.rawRequest = rawRequest;
  278. /** @type {boolean} */
  279. this.binary = /^(asset|webassembly)\b/.test(type);
  280. /** @type {Parser} */
  281. this.parser = parser;
  282. this.parserOptions = parserOptions;
  283. /** @type {Generator} */
  284. this.generator = generator;
  285. this.generatorOptions = generatorOptions;
  286. /** @type {string} */
  287. this.resource = resource;
  288. this.resourceResolveData = resourceResolveData;
  289. /** @type {string | undefined} */
  290. this.matchResource = matchResource;
  291. /** @type {LoaderItem[]} */
  292. this.loaders = loaders;
  293. if (resolveOptions !== undefined) {
  294. // already declared in super class
  295. this.resolveOptions = resolveOptions;
  296. }
  297. // Info from Build
  298. /** @type {(WebpackError | null)=} */
  299. this.error = null;
  300. /** @private @type {Source=} */
  301. this._source = null;
  302. /** @private @type {Map<string, number> | undefined} **/
  303. this._sourceSizes = undefined;
  304. /** @private @type {Set<string>} */
  305. this._sourceTypes = undefined;
  306. // Cache
  307. this._lastSuccessfulBuildMeta = {};
  308. this._forceBuild = true;
  309. this._isEvaluatingSideEffects = false;
  310. /** @type {WeakSet<ModuleGraph> | undefined} */
  311. this._addedSideEffectsBailout = undefined;
  312. /** @type {Map<string, any>} */
  313. this._codeGeneratorData = new Map();
  314. }
  315. /**
  316. * @returns {string} a unique identifier of the module
  317. */
  318. identifier() {
  319. if (this.layer === null) {
  320. if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) {
  321. return this.request;
  322. } else {
  323. return `${this.type}|${this.request}`;
  324. }
  325. } else {
  326. return `${this.type}|${this.request}|${this.layer}`;
  327. }
  328. }
  329. /**
  330. * @param {RequestShortener} requestShortener the request shortener
  331. * @returns {string} a user readable identifier of the module
  332. */
  333. readableIdentifier(requestShortener) {
  334. return requestShortener.shorten(this.userRequest);
  335. }
  336. /**
  337. * @param {LibIdentOptions} options options
  338. * @returns {string | null} an identifier for library inclusion
  339. */
  340. libIdent(options) {
  341. let ident = contextify(
  342. options.context,
  343. this.userRequest,
  344. options.associatedObjectForCache
  345. );
  346. if (this.layer) ident = `(${this.layer})/${ident}`;
  347. return ident;
  348. }
  349. /**
  350. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  351. */
  352. nameForCondition() {
  353. const resource = this.matchResource || this.resource;
  354. const idx = resource.indexOf("?");
  355. if (idx >= 0) return resource.slice(0, idx);
  356. return resource;
  357. }
  358. /**
  359. * Assuming this module is in the cache. Update the (cached) module with
  360. * the fresh module from the factory. Usually updates internal references
  361. * and properties.
  362. * @param {Module} module fresh module
  363. * @returns {void}
  364. */
  365. updateCacheModule(module) {
  366. super.updateCacheModule(module);
  367. const m = /** @type {NormalModule} */ (module);
  368. this.binary = m.binary;
  369. this.request = m.request;
  370. this.userRequest = m.userRequest;
  371. this.rawRequest = m.rawRequest;
  372. this.parser = m.parser;
  373. this.parserOptions = m.parserOptions;
  374. this.generator = m.generator;
  375. this.generatorOptions = m.generatorOptions;
  376. this.resource = m.resource;
  377. this.resourceResolveData = m.resourceResolveData;
  378. this.context = m.context;
  379. this.matchResource = m.matchResource;
  380. this.loaders = m.loaders;
  381. }
  382. /**
  383. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  384. */
  385. cleanupForCache() {
  386. // Make sure to cache types and sizes before cleanup when this module has been built
  387. // They are accessed by the stats and we don't want them to crash after cleanup
  388. // TODO reconsider this for webpack 6
  389. if (this.buildInfo) {
  390. if (this._sourceTypes === undefined) this.getSourceTypes();
  391. for (const type of this._sourceTypes) {
  392. this.size(type);
  393. }
  394. }
  395. super.cleanupForCache();
  396. this.parser = undefined;
  397. this.parserOptions = undefined;
  398. this.generator = undefined;
  399. this.generatorOptions = undefined;
  400. }
  401. /**
  402. * Module should be unsafe cached. Get data that's needed for that.
  403. * This data will be passed to restoreFromUnsafeCache later.
  404. * @returns {object} cached data
  405. */
  406. getUnsafeCacheData() {
  407. const data = super.getUnsafeCacheData();
  408. data.parserOptions = this.parserOptions;
  409. data.generatorOptions = this.generatorOptions;
  410. return data;
  411. }
  412. restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  413. this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  414. }
  415. /**
  416. * restore unsafe cache data
  417. * @param {object} unsafeCacheData data from getUnsafeCacheData
  418. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  419. */
  420. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  421. super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  422. this.parserOptions = unsafeCacheData.parserOptions;
  423. this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
  424. this.generatorOptions = unsafeCacheData.generatorOptions;
  425. this.generator = normalModuleFactory.getGenerator(
  426. this.type,
  427. this.generatorOptions
  428. );
  429. // we assume the generator behaves identically and keep cached sourceTypes/Sizes
  430. }
  431. /**
  432. * @param {string} context the compilation context
  433. * @param {string} name the asset name
  434. * @param {string} content the content
  435. * @param {string | TODO} sourceMap an optional source map
  436. * @param {Object=} associatedObjectForCache object for caching
  437. * @returns {Source} the created source
  438. */
  439. createSourceForAsset(
  440. context,
  441. name,
  442. content,
  443. sourceMap,
  444. associatedObjectForCache
  445. ) {
  446. if (sourceMap) {
  447. if (
  448. typeof sourceMap === "string" &&
  449. (this.useSourceMap || this.useSimpleSourceMap)
  450. ) {
  451. return new OriginalSource(
  452. content,
  453. contextifySourceUrl(context, sourceMap, associatedObjectForCache)
  454. );
  455. }
  456. if (this.useSourceMap) {
  457. return new SourceMapSource(
  458. content,
  459. name,
  460. contextifySourceMap(context, sourceMap, associatedObjectForCache)
  461. );
  462. }
  463. }
  464. return new RawSource(content);
  465. }
  466. /**
  467. * @param {ResolverWithOptions} resolver a resolver
  468. * @param {WebpackOptions} options webpack options
  469. * @param {Compilation} compilation the compilation
  470. * @param {InputFileSystem} fs file system from reading
  471. * @param {NormalModuleCompilationHooks} hooks the hooks
  472. * @returns {NormalModuleLoaderContext} loader context
  473. */
  474. _createLoaderContext(resolver, options, compilation, fs, hooks) {
  475. const { requestShortener } = compilation.runtimeTemplate;
  476. const getCurrentLoaderName = () => {
  477. const currentLoader = this.getCurrentLoader(loaderContext);
  478. if (!currentLoader) return "(not in loader scope)";
  479. return requestShortener.shorten(currentLoader.loader);
  480. };
  481. const getResolveContext = () => {
  482. return {
  483. fileDependencies: {
  484. add: d => loaderContext.addDependency(d)
  485. },
  486. contextDependencies: {
  487. add: d => loaderContext.addContextDependency(d)
  488. },
  489. missingDependencies: {
  490. add: d => loaderContext.addMissingDependency(d)
  491. }
  492. };
  493. };
  494. const getAbsolutify = memoize(() =>
  495. absolutify.bindCache(compilation.compiler.root)
  496. );
  497. const getAbsolutifyInContext = memoize(() =>
  498. absolutify.bindContextCache(this.context, compilation.compiler.root)
  499. );
  500. const getContextify = memoize(() =>
  501. contextify.bindCache(compilation.compiler.root)
  502. );
  503. const getContextifyInContext = memoize(() =>
  504. contextify.bindContextCache(this.context, compilation.compiler.root)
  505. );
  506. const utils = {
  507. absolutify: (context, request) => {
  508. return context === this.context
  509. ? getAbsolutifyInContext()(request)
  510. : getAbsolutify()(context, request);
  511. },
  512. contextify: (context, request) => {
  513. return context === this.context
  514. ? getContextifyInContext()(request)
  515. : getContextify()(context, request);
  516. },
  517. createHash: type => {
  518. return createHash(type || compilation.outputOptions.hashFunction);
  519. }
  520. };
  521. const loaderContext = {
  522. version: 2,
  523. getOptions: schema => {
  524. const loader = this.getCurrentLoader(loaderContext);
  525. let { options } = loader;
  526. if (typeof options === "string") {
  527. if (options.startsWith("{") && options.endsWith("}")) {
  528. try {
  529. options = parseJson(options);
  530. } catch (e) {
  531. throw new Error(`Cannot parse string options: ${e.message}`);
  532. }
  533. } else {
  534. options = querystring.parse(options, "&", "=", {
  535. maxKeys: 0
  536. });
  537. }
  538. }
  539. if (options === null || options === undefined) {
  540. options = {};
  541. }
  542. if (schema) {
  543. let name = "Loader";
  544. let baseDataPath = "options";
  545. let match;
  546. if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
  547. [, name, baseDataPath] = match;
  548. }
  549. getValidate()(schema, options, {
  550. name,
  551. baseDataPath
  552. });
  553. }
  554. return options;
  555. },
  556. emitWarning: warning => {
  557. if (!(warning instanceof Error)) {
  558. warning = new NonErrorEmittedError(warning);
  559. }
  560. this.addWarning(
  561. new ModuleWarning(warning, {
  562. from: getCurrentLoaderName()
  563. })
  564. );
  565. },
  566. emitError: error => {
  567. if (!(error instanceof Error)) {
  568. error = new NonErrorEmittedError(error);
  569. }
  570. this.addError(
  571. new ModuleError(error, {
  572. from: getCurrentLoaderName()
  573. })
  574. );
  575. },
  576. getLogger: name => {
  577. const currentLoader = this.getCurrentLoader(loaderContext);
  578. return compilation.getLogger(() =>
  579. [currentLoader && currentLoader.loader, name, this.identifier()]
  580. .filter(Boolean)
  581. .join("|")
  582. );
  583. },
  584. resolve(context, request, callback) {
  585. resolver.resolve({}, context, request, getResolveContext(), callback);
  586. },
  587. getResolve(options) {
  588. const child = options ? resolver.withOptions(options) : resolver;
  589. return (context, request, callback) => {
  590. if (callback) {
  591. child.resolve({}, context, request, getResolveContext(), callback);
  592. } else {
  593. return new Promise((resolve, reject) => {
  594. child.resolve(
  595. {},
  596. context,
  597. request,
  598. getResolveContext(),
  599. (err, result) => {
  600. if (err) reject(err);
  601. else resolve(result);
  602. }
  603. );
  604. });
  605. }
  606. };
  607. },
  608. emitFile: (name, content, sourceMap, assetInfo) => {
  609. if (!this.buildInfo.assets) {
  610. this.buildInfo.assets = Object.create(null);
  611. this.buildInfo.assetsInfo = new Map();
  612. }
  613. this.buildInfo.assets[name] = this.createSourceForAsset(
  614. options.context,
  615. name,
  616. content,
  617. sourceMap,
  618. compilation.compiler.root
  619. );
  620. this.buildInfo.assetsInfo.set(name, assetInfo);
  621. },
  622. addBuildDependency: dep => {
  623. if (this.buildInfo.buildDependencies === undefined) {
  624. this.buildInfo.buildDependencies = new LazySet();
  625. }
  626. this.buildInfo.buildDependencies.add(dep);
  627. },
  628. utils,
  629. rootContext: options.context,
  630. webpack: true,
  631. sourceMap: !!this.useSourceMap,
  632. mode: options.mode || "production",
  633. _module: this,
  634. _compilation: compilation,
  635. _compiler: compilation.compiler,
  636. fs: fs
  637. };
  638. Object.assign(loaderContext, options.loader);
  639. hooks.loader.call(loaderContext, this);
  640. return loaderContext;
  641. }
  642. getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
  643. if (
  644. this.loaders &&
  645. this.loaders.length &&
  646. index < this.loaders.length &&
  647. index >= 0 &&
  648. this.loaders[index]
  649. ) {
  650. return this.loaders[index];
  651. }
  652. return null;
  653. }
  654. /**
  655. * @param {string} context the compilation context
  656. * @param {string | Buffer} content the content
  657. * @param {string | TODO} sourceMap an optional source map
  658. * @param {Object=} associatedObjectForCache object for caching
  659. * @returns {Source} the created source
  660. */
  661. createSource(context, content, sourceMap, associatedObjectForCache) {
  662. if (Buffer.isBuffer(content)) {
  663. return new RawSource(content);
  664. }
  665. // if there is no identifier return raw source
  666. if (!this.identifier) {
  667. return new RawSource(content);
  668. }
  669. // from here on we assume we have an identifier
  670. const identifier = this.identifier();
  671. if (this.useSourceMap && sourceMap) {
  672. return new SourceMapSource(
  673. content,
  674. contextifySourceUrl(context, identifier, associatedObjectForCache),
  675. contextifySourceMap(context, sourceMap, associatedObjectForCache)
  676. );
  677. }
  678. if (this.useSourceMap || this.useSimpleSourceMap) {
  679. return new OriginalSource(
  680. content,
  681. contextifySourceUrl(context, identifier, associatedObjectForCache)
  682. );
  683. }
  684. return new RawSource(content);
  685. }
  686. /**
  687. * @param {WebpackOptions} options webpack options
  688. * @param {Compilation} compilation the compilation
  689. * @param {ResolverWithOptions} resolver the resolver
  690. * @param {InputFileSystem} fs the file system
  691. * @param {NormalModuleCompilationHooks} hooks the hooks
  692. * @param {function((WebpackError | null)=): void} callback callback function
  693. * @returns {void}
  694. */
  695. _doBuild(options, compilation, resolver, fs, hooks, callback) {
  696. const loaderContext = this._createLoaderContext(
  697. resolver,
  698. options,
  699. compilation,
  700. fs,
  701. hooks
  702. );
  703. const processResult = (err, result) => {
  704. if (err) {
  705. if (!(err instanceof Error)) {
  706. err = new NonErrorEmittedError(err);
  707. }
  708. const currentLoader = this.getCurrentLoader(loaderContext);
  709. const error = new ModuleBuildError(err, {
  710. from:
  711. currentLoader &&
  712. compilation.runtimeTemplate.requestShortener.shorten(
  713. currentLoader.loader
  714. )
  715. });
  716. return callback(error);
  717. }
  718. const source = result[0];
  719. const sourceMap = result.length >= 1 ? result[1] : null;
  720. const extraInfo = result.length >= 2 ? result[2] : null;
  721. if (!Buffer.isBuffer(source) && typeof source !== "string") {
  722. const currentLoader = this.getCurrentLoader(loaderContext, 0);
  723. const err = new Error(
  724. `Final loader (${
  725. currentLoader
  726. ? compilation.runtimeTemplate.requestShortener.shorten(
  727. currentLoader.loader
  728. )
  729. : "unknown"
  730. }) didn't return a Buffer or String`
  731. );
  732. const error = new ModuleBuildError(err);
  733. return callback(error);
  734. }
  735. this._source = this.createSource(
  736. options.context,
  737. this.binary ? asBuffer(source) : asString(source),
  738. sourceMap,
  739. compilation.compiler.root
  740. );
  741. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  742. this._ast =
  743. typeof extraInfo === "object" &&
  744. extraInfo !== null &&
  745. extraInfo.webpackAST !== undefined
  746. ? extraInfo.webpackAST
  747. : null;
  748. return callback();
  749. };
  750. this.buildInfo.fileDependencies = new LazySet();
  751. this.buildInfo.contextDependencies = new LazySet();
  752. this.buildInfo.missingDependencies = new LazySet();
  753. this.buildInfo.cacheable = true;
  754. try {
  755. hooks.beforeLoaders.call(this.loaders, this, loaderContext);
  756. } catch (err) {
  757. processResult(err);
  758. return;
  759. }
  760. if (this.loaders.length > 0) {
  761. this.buildInfo.buildDependencies = new LazySet();
  762. }
  763. runLoaders(
  764. {
  765. resource: this.resource,
  766. loaders: this.loaders,
  767. context: loaderContext,
  768. processResource: (loaderContext, resourcePath, callback) => {
  769. const resource = loaderContext.resource;
  770. const scheme = getScheme(resource);
  771. hooks.readResource
  772. .for(scheme)
  773. .callAsync(loaderContext, (err, result) => {
  774. if (err) return callback(err);
  775. if (typeof result !== "string" && !result) {
  776. return callback(new UnhandledSchemeError(scheme, resource));
  777. }
  778. return callback(null, result);
  779. });
  780. }
  781. },
  782. (err, result) => {
  783. // Cleanup loaderContext to avoid leaking memory in ICs
  784. loaderContext._compilation =
  785. loaderContext._compiler =
  786. loaderContext._module =
  787. loaderContext.fs =
  788. undefined;
  789. if (!result) {
  790. this.buildInfo.cacheable = false;
  791. return processResult(
  792. err || new Error("No result from loader-runner processing"),
  793. null
  794. );
  795. }
  796. this.buildInfo.fileDependencies.addAll(result.fileDependencies);
  797. this.buildInfo.contextDependencies.addAll(result.contextDependencies);
  798. this.buildInfo.missingDependencies.addAll(result.missingDependencies);
  799. for (const loader of this.loaders) {
  800. this.buildInfo.buildDependencies.add(loader.loader);
  801. }
  802. this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable;
  803. processResult(err, result.result);
  804. }
  805. );
  806. }
  807. /**
  808. * @param {WebpackError} error the error
  809. * @returns {void}
  810. */
  811. markModuleAsErrored(error) {
  812. // Restore build meta from successful build to keep importing state
  813. this.buildMeta = { ...this._lastSuccessfulBuildMeta };
  814. this.error = error;
  815. this.addError(error);
  816. }
  817. applyNoParseRule(rule, content) {
  818. // must start with "rule" if rule is a string
  819. if (typeof rule === "string") {
  820. return content.startsWith(rule);
  821. }
  822. if (typeof rule === "function") {
  823. return rule(content);
  824. }
  825. // we assume rule is a regexp
  826. return rule.test(content);
  827. }
  828. // check if module should not be parsed
  829. // returns "true" if the module should !not! be parsed
  830. // returns "false" if the module !must! be parsed
  831. shouldPreventParsing(noParseRule, request) {
  832. // if no noParseRule exists, return false
  833. // the module !must! be parsed.
  834. if (!noParseRule) {
  835. return false;
  836. }
  837. // we only have one rule to check
  838. if (!Array.isArray(noParseRule)) {
  839. // returns "true" if the module is !not! to be parsed
  840. return this.applyNoParseRule(noParseRule, request);
  841. }
  842. for (let i = 0; i < noParseRule.length; i++) {
  843. const rule = noParseRule[i];
  844. // early exit on first truthy match
  845. // this module is !not! to be parsed
  846. if (this.applyNoParseRule(rule, request)) {
  847. return true;
  848. }
  849. }
  850. // no match found, so this module !should! be parsed
  851. return false;
  852. }
  853. _initBuildHash(compilation) {
  854. const hash = createHash(compilation.outputOptions.hashFunction);
  855. if (this._source) {
  856. hash.update("source");
  857. this._source.updateHash(hash);
  858. }
  859. hash.update("meta");
  860. hash.update(JSON.stringify(this.buildMeta));
  861. this.buildInfo.hash = /** @type {string} */ (hash.digest("hex"));
  862. }
  863. /**
  864. * @param {WebpackOptions} options webpack options
  865. * @param {Compilation} compilation the compilation
  866. * @param {ResolverWithOptions} resolver the resolver
  867. * @param {InputFileSystem} fs the file system
  868. * @param {function(WebpackError=): void} callback callback function
  869. * @returns {void}
  870. */
  871. build(options, compilation, resolver, fs, callback) {
  872. this._forceBuild = false;
  873. this._source = null;
  874. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  875. this._sourceTypes = undefined;
  876. this._ast = null;
  877. this.error = null;
  878. this.clearWarningsAndErrors();
  879. this.clearDependenciesAndBlocks();
  880. this.buildMeta = {};
  881. this.buildInfo = {
  882. cacheable: false,
  883. parsed: true,
  884. fileDependencies: undefined,
  885. contextDependencies: undefined,
  886. missingDependencies: undefined,
  887. buildDependencies: undefined,
  888. valueDependencies: undefined,
  889. hash: undefined,
  890. assets: undefined,
  891. assetsInfo: undefined
  892. };
  893. const startTime = compilation.compiler.fsStartTime || Date.now();
  894. const hooks = NormalModule.getCompilationHooks(compilation);
  895. return this._doBuild(options, compilation, resolver, fs, hooks, err => {
  896. // if we have an error mark module as failed and exit
  897. if (err) {
  898. this.markModuleAsErrored(err);
  899. this._initBuildHash(compilation);
  900. return callback();
  901. }
  902. const handleParseError = e => {
  903. const source = this._source.source();
  904. const loaders = this.loaders.map(item =>
  905. contextify(options.context, item.loader, compilation.compiler.root)
  906. );
  907. const error = new ModuleParseError(source, e, loaders, this.type);
  908. this.markModuleAsErrored(error);
  909. this._initBuildHash(compilation);
  910. return callback();
  911. };
  912. const handleParseResult = result => {
  913. this.dependencies.sort(
  914. concatComparators(
  915. compareSelect(a => a.loc, compareLocations),
  916. keepOriginalOrder(this.dependencies)
  917. )
  918. );
  919. this._initBuildHash(compilation);
  920. this._lastSuccessfulBuildMeta = this.buildMeta;
  921. return handleBuildDone();
  922. };
  923. const handleBuildDone = () => {
  924. try {
  925. hooks.beforeSnapshot.call(this);
  926. } catch (err) {
  927. this.markModuleAsErrored(err);
  928. return callback();
  929. }
  930. const snapshotOptions = compilation.options.snapshot.module;
  931. if (!this.buildInfo.cacheable || !snapshotOptions) {
  932. return callback();
  933. }
  934. // add warning for all non-absolute paths in fileDependencies, etc
  935. // This makes it easier to find problems with watching and/or caching
  936. let nonAbsoluteDependencies = undefined;
  937. const checkDependencies = deps => {
  938. for (const dep of deps) {
  939. if (!ABSOLUTE_PATH_REGEX.test(dep)) {
  940. if (nonAbsoluteDependencies === undefined)
  941. nonAbsoluteDependencies = new Set();
  942. nonAbsoluteDependencies.add(dep);
  943. deps.delete(dep);
  944. try {
  945. const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
  946. const absolute = join(
  947. compilation.fileSystemInfo.fs,
  948. this.context,
  949. depWithoutGlob
  950. );
  951. if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
  952. (depWithoutGlob !== dep
  953. ? this.buildInfo.contextDependencies
  954. : deps
  955. ).add(absolute);
  956. }
  957. } catch (e) {
  958. // ignore
  959. }
  960. }
  961. }
  962. };
  963. checkDependencies(this.buildInfo.fileDependencies);
  964. checkDependencies(this.buildInfo.missingDependencies);
  965. checkDependencies(this.buildInfo.contextDependencies);
  966. if (nonAbsoluteDependencies !== undefined) {
  967. const InvalidDependenciesModuleWarning =
  968. getInvalidDependenciesModuleWarning();
  969. this.addWarning(
  970. new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
  971. );
  972. }
  973. // convert file/context/missingDependencies into filesystem snapshot
  974. compilation.fileSystemInfo.createSnapshot(
  975. startTime,
  976. this.buildInfo.fileDependencies,
  977. this.buildInfo.contextDependencies,
  978. this.buildInfo.missingDependencies,
  979. snapshotOptions,
  980. (err, snapshot) => {
  981. if (err) {
  982. this.markModuleAsErrored(err);
  983. return;
  984. }
  985. this.buildInfo.fileDependencies = undefined;
  986. this.buildInfo.contextDependencies = undefined;
  987. this.buildInfo.missingDependencies = undefined;
  988. this.buildInfo.snapshot = snapshot;
  989. return callback();
  990. }
  991. );
  992. };
  993. try {
  994. hooks.beforeParse.call(this);
  995. } catch (err) {
  996. this.markModuleAsErrored(err);
  997. this._initBuildHash(compilation);
  998. return callback();
  999. }
  1000. // check if this module should !not! be parsed.
  1001. // if so, exit here;
  1002. const noParseRule = options.module && options.module.noParse;
  1003. if (this.shouldPreventParsing(noParseRule, this.request)) {
  1004. // We assume that we need module and exports
  1005. this.buildInfo.parsed = false;
  1006. this._initBuildHash(compilation);
  1007. return handleBuildDone();
  1008. }
  1009. let result;
  1010. try {
  1011. const source = this._source.source();
  1012. result = this.parser.parse(this._ast || source, {
  1013. source,
  1014. current: this,
  1015. module: this,
  1016. compilation: compilation,
  1017. options: options
  1018. });
  1019. } catch (e) {
  1020. handleParseError(e);
  1021. return;
  1022. }
  1023. handleParseResult(result);
  1024. });
  1025. }
  1026. /**
  1027. * @param {ConcatenationBailoutReasonContext} context context
  1028. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  1029. */
  1030. getConcatenationBailoutReason(context) {
  1031. return this.generator.getConcatenationBailoutReason(this, context);
  1032. }
  1033. /**
  1034. * @param {ModuleGraph} moduleGraph the module graph
  1035. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  1036. */
  1037. getSideEffectsConnectionState(moduleGraph) {
  1038. if (this.factoryMeta !== undefined) {
  1039. if (this.factoryMeta.sideEffectFree) return false;
  1040. if (this.factoryMeta.sideEffectFree === false) return true;
  1041. }
  1042. if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) {
  1043. if (this._isEvaluatingSideEffects)
  1044. return ModuleGraphConnection.CIRCULAR_CONNECTION;
  1045. this._isEvaluatingSideEffects = true;
  1046. /** @type {ConnectionState} */
  1047. let current = false;
  1048. for (const dep of this.dependencies) {
  1049. const state = dep.getModuleEvaluationSideEffectsState(moduleGraph);
  1050. if (state === true) {
  1051. if (
  1052. this._addedSideEffectsBailout === undefined
  1053. ? ((this._addedSideEffectsBailout = new WeakSet()), true)
  1054. : !this._addedSideEffectsBailout.has(moduleGraph)
  1055. ) {
  1056. this._addedSideEffectsBailout.add(moduleGraph);
  1057. moduleGraph
  1058. .getOptimizationBailout(this)
  1059. .push(
  1060. () =>
  1061. `Dependency (${
  1062. dep.type
  1063. }) with side effects at ${formatLocation(dep.loc)}`
  1064. );
  1065. }
  1066. this._isEvaluatingSideEffects = false;
  1067. return true;
  1068. } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
  1069. current = ModuleGraphConnection.addConnectionStates(current, state);
  1070. }
  1071. }
  1072. this._isEvaluatingSideEffects = false;
  1073. // When caching is implemented here, make sure to not cache when
  1074. // at least one circular connection was in the loop above
  1075. return current;
  1076. } else {
  1077. return true;
  1078. }
  1079. }
  1080. /**
  1081. * @returns {Set<string>} types available (do not mutate)
  1082. */
  1083. getSourceTypes() {
  1084. if (this._sourceTypes === undefined) {
  1085. this._sourceTypes = this.generator.getTypes(this);
  1086. }
  1087. return this._sourceTypes;
  1088. }
  1089. /**
  1090. * @param {CodeGenerationContext} context context for code generation
  1091. * @returns {CodeGenerationResult} result
  1092. */
  1093. codeGeneration({
  1094. dependencyTemplates,
  1095. runtimeTemplate,
  1096. moduleGraph,
  1097. chunkGraph,
  1098. runtime,
  1099. concatenationScope,
  1100. codeGenerationResults,
  1101. sourceTypes
  1102. }) {
  1103. /** @type {Set<string>} */
  1104. const runtimeRequirements = new Set();
  1105. if (!this.buildInfo.parsed) {
  1106. runtimeRequirements.add(RuntimeGlobals.module);
  1107. runtimeRequirements.add(RuntimeGlobals.exports);
  1108. runtimeRequirements.add(RuntimeGlobals.thisAsExports);
  1109. }
  1110. /** @type {function(): Map<string, any>} */
  1111. const getData = () => {
  1112. return this._codeGeneratorData;
  1113. };
  1114. const sources = new Map();
  1115. for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) {
  1116. const source = this.error
  1117. ? new RawSource(
  1118. "throw new Error(" + JSON.stringify(this.error.message) + ");"
  1119. )
  1120. : this.generator.generate(this, {
  1121. dependencyTemplates,
  1122. runtimeTemplate,
  1123. moduleGraph,
  1124. chunkGraph,
  1125. runtimeRequirements,
  1126. runtime,
  1127. concatenationScope,
  1128. codeGenerationResults,
  1129. getData,
  1130. type
  1131. });
  1132. if (source) {
  1133. sources.set(type, new CachedSource(source));
  1134. }
  1135. }
  1136. /** @type {CodeGenerationResult} */
  1137. const resultEntry = {
  1138. sources,
  1139. runtimeRequirements,
  1140. data: this._codeGeneratorData
  1141. };
  1142. return resultEntry;
  1143. }
  1144. /**
  1145. * @returns {Source | null} the original source for the module before webpack transformation
  1146. */
  1147. originalSource() {
  1148. return this._source;
  1149. }
  1150. /**
  1151. * @returns {void}
  1152. */
  1153. invalidateBuild() {
  1154. this._forceBuild = true;
  1155. }
  1156. /**
  1157. * @param {NeedBuildContext} context context info
  1158. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  1159. * @returns {void}
  1160. */
  1161. needBuild(context, callback) {
  1162. const { fileSystemInfo, compilation, valueCacheVersions } = context;
  1163. // build if enforced
  1164. if (this._forceBuild) return callback(null, true);
  1165. // always try to build in case of an error
  1166. if (this.error) return callback(null, true);
  1167. // always build when module is not cacheable
  1168. if (!this.buildInfo.cacheable) return callback(null, true);
  1169. // build when there is no snapshot to check
  1170. if (!this.buildInfo.snapshot) return callback(null, true);
  1171. // build when valueDependencies have changed
  1172. /** @type {Map<string, string | Set<string>>} */
  1173. const valueDependencies = this.buildInfo.valueDependencies;
  1174. if (valueDependencies) {
  1175. if (!valueCacheVersions) return callback(null, true);
  1176. for (const [key, value] of valueDependencies) {
  1177. if (value === undefined) return callback(null, true);
  1178. const current = valueCacheVersions.get(key);
  1179. if (
  1180. value !== current &&
  1181. (typeof value === "string" ||
  1182. typeof current === "string" ||
  1183. current === undefined ||
  1184. !isSubset(value, current))
  1185. ) {
  1186. return callback(null, true);
  1187. }
  1188. }
  1189. }
  1190. // check snapshot for validity
  1191. fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => {
  1192. if (err) return callback(err);
  1193. if (!valid) return callback(null, true);
  1194. const hooks = NormalModule.getCompilationHooks(compilation);
  1195. hooks.needBuild.callAsync(this, context, (err, needBuild) => {
  1196. if (err) {
  1197. return callback(
  1198. HookWebpackError.makeWebpackError(
  1199. err,
  1200. "NormalModule.getCompilationHooks().needBuild"
  1201. )
  1202. );
  1203. }
  1204. callback(null, !!needBuild);
  1205. });
  1206. });
  1207. }
  1208. /**
  1209. * @param {string=} type the source type for which the size should be estimated
  1210. * @returns {number} the estimated size of the module (must be non-zero)
  1211. */
  1212. size(type) {
  1213. const cachedSize =
  1214. this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type);
  1215. if (cachedSize !== undefined) {
  1216. return cachedSize;
  1217. }
  1218. const size = Math.max(1, this.generator.getSize(this, type));
  1219. if (this._sourceSizes === undefined) {
  1220. this._sourceSizes = new Map();
  1221. }
  1222. this._sourceSizes.set(type, size);
  1223. return size;
  1224. }
  1225. /**
  1226. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  1227. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  1228. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  1229. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  1230. */
  1231. addCacheDependencies(
  1232. fileDependencies,
  1233. contextDependencies,
  1234. missingDependencies,
  1235. buildDependencies
  1236. ) {
  1237. const { snapshot, buildDependencies: buildDeps } = this.buildInfo;
  1238. if (snapshot) {
  1239. fileDependencies.addAll(snapshot.getFileIterable());
  1240. contextDependencies.addAll(snapshot.getContextIterable());
  1241. missingDependencies.addAll(snapshot.getMissingIterable());
  1242. } else {
  1243. const {
  1244. fileDependencies: fileDeps,
  1245. contextDependencies: contextDeps,
  1246. missingDependencies: missingDeps
  1247. } = this.buildInfo;
  1248. if (fileDeps !== undefined) fileDependencies.addAll(fileDeps);
  1249. if (contextDeps !== undefined) contextDependencies.addAll(contextDeps);
  1250. if (missingDeps !== undefined) missingDependencies.addAll(missingDeps);
  1251. }
  1252. if (buildDeps !== undefined) {
  1253. buildDependencies.addAll(buildDeps);
  1254. }
  1255. }
  1256. /**
  1257. * @param {Hash} hash the hash used to track dependencies
  1258. * @param {UpdateHashContext} context context
  1259. * @returns {void}
  1260. */
  1261. updateHash(hash, context) {
  1262. hash.update(this.buildInfo.hash);
  1263. this.generator.updateHash(hash, {
  1264. module: this,
  1265. ...context
  1266. });
  1267. super.updateHash(hash, context);
  1268. }
  1269. serialize(context) {
  1270. const { write } = context;
  1271. // deserialize
  1272. write(this._source);
  1273. write(this.error);
  1274. write(this._lastSuccessfulBuildMeta);
  1275. write(this._forceBuild);
  1276. write(this._codeGeneratorData);
  1277. super.serialize(context);
  1278. }
  1279. static deserialize(context) {
  1280. const obj = new NormalModule({
  1281. // will be deserialized by Module
  1282. layer: null,
  1283. type: "",
  1284. // will be filled by updateCacheModule
  1285. resource: "",
  1286. context: "",
  1287. request: null,
  1288. userRequest: null,
  1289. rawRequest: null,
  1290. loaders: null,
  1291. matchResource: null,
  1292. parser: null,
  1293. parserOptions: null,
  1294. generator: null,
  1295. generatorOptions: null,
  1296. resolveOptions: null
  1297. });
  1298. obj.deserialize(context);
  1299. return obj;
  1300. }
  1301. deserialize(context) {
  1302. const { read } = context;
  1303. this._source = read();
  1304. this.error = read();
  1305. this._lastSuccessfulBuildMeta = read();
  1306. this._forceBuild = read();
  1307. this._codeGeneratorData = read();
  1308. super.deserialize(context);
  1309. }
  1310. }
  1311. makeSerializable(NormalModule, "webpack/lib/NormalModule");
  1312. module.exports = NormalModule;